Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Friday, June 12, 2015

JSON Interview Questions

1) Mention what is JSON?
JSON is a simple data exchange format.  JSON means JavaScript Object Notation; it is language and platform independent.
2) Explain what is JSON objects?
An object can be defined as an unordered set of name/value pairs.  An object in JSON starts with {left brace} and finish or ends with {right brace}.  Every name is followed by: (colon) and the name/value pairs are parted by, (comma).
3) Explain how to transform JSON text to a JavaScript object?
One of the common use of JSON is to collect JSON data from a web server as a file or HTTP request, and convert the JSON data to a JavaScript, ant then it avails the data in a web page.
4) Mention what is the rule for JSON syntax rules? Give an example of JSON object?
JSON syntax is a set of the JavaScript object notation syntax.
  • Data is in name/value pairs
  • Data is separated by comma
  • Curly brackets hold objects
  • Square bracket holds arrays
5) Why must one use JSON over XML?
  • It is faster and lighter than XML as on the wire data format
  • XML data is typeless while JSON objects are typed
  • JSON types: Number, Array, Boolean, String
  • XML data are all string
  • Data is readily available as JSON object is in your JavaScript
  • Fetching values is as simple as reading from an object property in your JavaScript code
6) Mention what is JSON-RPC and JSON Parser?
  • JSON RPC: It is a simple remote procedure call protocol same as XML-RPC although it uses the lightweight JSON format instead of XML
  • JSON Parser: JSON parser is used to parse the JSON data into objects to use its value. It can be parsed by javaScript, PHP and jQuery
7) Mention what is the file extension of JSON?
File extension of JSON is .json
8) Mention which function is used to convert a JSON text into an object?
To convert JSON text into an object “eval” function is used.
9) Mention what are the data types supported by JSON?
Data types supported by JSON includes
  • Number
  • String
  • Boolean
  • Array
  • Object
  • Null
10) Mention what is the role of JSON.stringify?
JSON.stringify() converts an object into a JSON text and saves that JSON text in a string.
11) Show how to parse JSON in JQuery?
To parse JSON in JQuery, we will see the example
var json = ‘{“name”: “Guru 99”, “Description “: “Learn PHP Interactively with PHP Beginner Tutorials}
obj = $.parseJSON(json);
//alert(obj.name);
12) Mention what is the function used for encoding JSON in PHP?
For encoding JSON in PHP, json_encode () function is used.  This function returns the JSON representation of a value on success or false on failure.
13) Explain how you can convert a string into a JSON Array?
To convert a string into a JSON array, you need to create a JSONObject object for each of your objects, and add those to your JSON array.
14) Mention what are the JSON files?
  • JSON file type for JSON files is “.json”
  • The MIME type for JSON text is “application/json”
15) List out the uses of JSON?
Uses of JSON includes
  • When writing application based on JavaScript it uses JSON, which includes browser extension and websites
  • JSON is used for transmitting and serializing structured data over network connection
  • JSON is mainly used to transfer data between server and web application
  • Web service and API’s use JSON format to provide public data
  • JSON can be used with modern programming language
16) Mention what are the drawbacks of JSON?
Drawbacks of json are
  • It does not contain type definition
  • It lacks some sort of DTD
17) Mention what is the MIME type of JSON?
MIME type for JSON text is “application/json”
18) Mention what is JSONP?
JSONP stands for JSON with padding. It is a method used to bypass the cross-domain policies in web browsers. In other words, JSONP is the simple way to deal with browser restrictions when sending JSON responses from different domains from the client.
19) Mention what is the difference between JSON and JSONP?
  • JSON: JSON is a simple data format used for communication medium between different systems
  • JSONP: It is a methodology for using that format with cross domain ajax requests while not being affected by same origin policy issue.

Monday, March 9, 2015

AngularJS - Internalization

AngularJS supports inbuilt internationalization for three types of filters : Currency, Date, and Numbers. We only need to incorporate corresponding java script according to locale of the country. By default, it considers the locale of the browser. For example, for Danish locale, use the following script:
<script src="https://code.angularjs.org/1.2.5/i18n/angular-locale_da-dk.js"></script> 

Example Using Danish Locale

testAngularJS.htm

<html>
<head>
   <title>Angular JS Forms</title>
</head>
<body>
   <h2>AngularJS Sample Application</h2>
   <div ng-app="mainApp" ng-controller="StudentController">
      {{fees | currency }}  <br/><br/>
      {{admissiondate | date }}   <br/><br/>
      {{rollno | number }}  
   </div>
   <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
   <script src="https://code.angularjs.org/1.2.5/i18n/angular-locale_da-dk.js"></script> 
   <script>
      var mainApp = angular.module("mainApp", []);
     
      mainApp.controller('StudentController', function($scope) {
            $scope.fees = 100;
   $scope.admissiondate  = new Date();
            $scope.rollno = 123.45;
      });
      
   </script>
</body>
</html>

Output

Open the file testAngularJS.htm in a web browser and see the result.
AngularJS Internalization

Example Using Browser Locale

testAngularJS.htm

<html>
<head>
   <title>Angular JS Forms</title>
</head>
<body>
   <h2>AngularJS Sample Application</h2>
   <div ng-app="mainApp" ng-controller="StudentController">
      {{fees | currency }}  <br/><br/>
      {{admissiondate | date }}   <br/><br/>
      {{rollno | number }}  
   </div>
   <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
   <!-- <script src="https://code.angularjs.org/1.2.5/i18n/angular-locale_da-dk.js"></script> -->
   <script>
      var mainApp = angular.module("mainApp", []);
     
      mainApp.controller('StudentController', function($scope) {
            $scope.fees = 100;
   $scope.admissiondate  = new Date();
            $scope.rollno = 123.45;
      });
      
   </script>
</body>
</html>

Output

Open the file testAngularJS.htm in a web browser and see the result.
AngularJS Internalization

AngularJS - Custom Directives

Custom directives are used in AngularJS to extend the functionality of HTML. They are defined using directive function. A custom directive simply replaces the element for which it is activated. During bootstrap, the AngularJS application finds matching elements and does one-time activity using its compile() method of the custom directive. Then it processes the element using link() method of the custom directive based on the scope of the directive. AngularJS provides support to create custom directives for the following elements:
  • Element directive - This activates when a matching element is encountered.
  • Attribute - This activates when a matching attribute is encountered.
  • CSS - This activates when a matching CSS style is encountered.
  • Comment - Directive activates when a matching comment is encountered.

Understanding Custom Directive

Define custom HTML tags.
<student name="Mahesh"></student><br/>
<student name="Piyush"></student>
Define custom directive to handle the above HTML tags.
var mainApp = angular.module("mainApp", []);

//Create a directive, first parameter is the html element to be attached.   
//We are attaching student html tag. 
//This directive will be activated as soon as any student element is encountered in html
mainApp.directive('student', function() {
   //define the directive object
   var directive = {};
   //restrict = E, signifies that directive is Element directive
   directive.restrict = 'E';
   //template replaces the complete element with its text. 
   directive.template = "Student: <b>{{student.name}}</b> , Roll No: <b>{{student.rollno}}</b>";
   //scope is used to distinguish each student element based on criteria.
   directive.scope = {
       student : "=name"
   }
   //compile is called during application initialization. AngularJS calls it once when html page is loaded.
   directive.compile = function(element, attributes) {
      element.css("border", "1px solid #cccccc");
   //linkFunction is linked with each element with scope to get the element specific data.
      var linkFunction = function($scope, element, attributes) {
          element.html("Student: <b>"+$scope.student.name +"</b> , Roll No: <b>"+$scope.student.rollno+"</b><br/>");
          element.css("background-color", "#ff00ff");
      }
      return linkFunction;
   }
   return directive;
});
Define controller to update the scope for directive. Here, we use the value of name attribute as scope's child.
mainApp.controller('StudentController', function($scope) {
      $scope.Mahesh = {};
      $scope.Mahesh.name = "Mahesh Parashar";
      $scope.Mahesh.rollno  = 1;

      $scope.Piyush = {};
      $scope.Piyush.name = "Piyush Parashar";
      $scope.Piyush.rollno  = 2;
});

Example

<html>
<head>
   <title>Angular JS Custom Directives</title>
</head>
<body>
   <h2>AngularJS Sample Application</h2>
   <div ng-app="mainApp" ng-controller="StudentController">
  <student name="Mahesh"></student><br/>
  <student name="Piyush"></student>
   </div>
   <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
   <script>
      var mainApp = angular.module("mainApp", []);
   
      mainApp.directive('student', function() {
         var directive = {};
         directive.restrict = 'E';
         directive.template = "Student: <b>{{student.name}}</b> , Roll No: <b>{{student.rollno}}</b>";
         
         directive.scope = {
            student : "=name"
         }
   
         directive.compile = function(element, attributes) {
            element.css("border", "1px solid #cccccc");

            var linkFunction = function($scope, element, attributes) {
               element.html("Student: <b>"+$scope.student.name +"</b> , Roll No: <b>"+$scope.student.rollno+"</b><br/>");
               element.css("background-color", "#ff00ff");
            }

            return linkFunction;
         }

         return directive;
      });
   
      mainApp.controller('StudentController', function($scope) {
            $scope.Mahesh = {};
            $scope.Mahesh.name = "Mahesh Parashar";
            $scope.Mahesh.rollno  = 1;

            $scope.Piyush = {};
            $scope.Piyush.name = "Piyush Parashar";
            $scope.Piyush.rollno  = 2;
      });
      
   </script>
</body>
</html>

Output

Open testAngularJS.htm in a web browser and see the result.
AngularJS Custom Directives

AngularJS - Dependency Injection

Dependency Injection is a software design in which components are given their dependencies instead of hard coding them within the component. It relieves a component from locating the dependency and makes dependencies configurable. It also helps in making components reusable, maintainable and testable.
AngularJS provides a supreme Dependency Injection mechanism. It provides following core components which can be injected into each other as dependencies.
  • Value
  • Factory
  • Service
  • Provider
  • Constant

value

Value is a simple JavaScript object, which is required to pass values to the controller during config phase (config phase is when AngularJS bootstraps itself).
//define a module
var mainApp = angular.module("mainApp", []);
//create a value object as "defaultInput" and pass it a data.
mainApp.value("defaultInput", 5);
...
//inject the value in the controller using its name "defaultInput"
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
      $scope.number = defaultInput;
      $scope.result = CalcService.square($scope.number);

      $scope.square = function() {
      $scope.result = CalcService.square($scope.number);
   }
});

Factory

Factory is a function which is used to return value. It creates a value on demand whenever a service or a controller requires it. It generally uses a factory function to calculate and return the value.
//define a module
var mainApp = angular.module("mainApp", []);
//create a factory "MathService" which provides a method multiply to return multiplication of two numbers
mainApp.factory('MathService', function() {     
   var factory = {};  
   factory.multiply = function(a, b) {
      return a * b 
   }
   return factory;
}); 

//inject the factory "MathService" in a service to utilize the multiply method of factory.
mainApp.service('CalcService', function(MathService){
      this.square = function(a) { 
      return MathService.multiply(a,a); 
   }
});
...

Service

Service is a singleton JavaScript object containing a set of functions to perform certain tasks. Service is defined using service() function and it is then injected into the controllers.
//define a module
var mainApp = angular.module("mainApp", []);
...
//create a service which defines a method square to return square of a number.
mainApp.service('CalcService', function(MathService){
      this.square = function(a) { 
      return MathService.multiply(a,a); 
   }
});
//inject the service "CalcService" into the controller
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
      $scope.number = defaultInput;
      $scope.result = CalcService.square($scope.number);

      $scope.square = function() {
      $scope.result = CalcService.square($scope.number);
   }
});

Provider

Provider is used by AngularJS internally to create services, factory, etc. during the config phase. The following script can be used to create MathService that we created earlier. Provider is a special factory method with get() method which is used to return the value/service/factory.
//define a module
var mainApp = angular.module("mainApp", []);
...
//create a service using provider which defines a method square to return square of a number.
mainApp.config(function($provide) {
   $provide.provider('MathService', function() {
      this.$get = function() {
         var factory = {};  
         factory.multiply = function(a, b) {
            return a * b; 
         }
         return factory;
      };
   });
});

Constant

Constants are used to pass values at the config phase considering the fact that value cannot be used during the config phase.
mainApp.constant("configParam", "constant value");

Example

The following example shows the use of all the above-mentioned directives:

testAngularJS.htm

<html>
<head>
   <title>AngularJS Dependency Injection</title>
</head>
<body>
   <h2>AngularJS Sample Application</h2>
   <div ng-app="mainApp" ng-controller="CalcController">
      <p>Enter a number: <input type="number" ng-model="number" />
      <button ng-click="square()">X<sup>2</sup></button>
      <p>Result: {{result}}</p>
   </div>
   <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
   <script>
      var mainApp = angular.module("mainApp", []);
   
      mainApp.config(function($provide) {
         $provide.provider('MathService', function() {
            this.$get = function() {
               var factory = {};  
               factory.multiply = function(a, b) {
                  return a * b; 
               }
               return factory;
            };
         });
      });

      mainApp.value("defaultInput", 5);

      mainApp.factory('MathService', function() {     
         var factory = {};  
         factory.multiply = function(a, b) {
            return a * b; 
         }
         return factory;
      }); 

      mainApp.service('CalcService', function(MathService){
            this.square = function(a) { 
            return MathService.multiply(a,a); 
         }
      });

      mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
            $scope.number = defaultInput;
            $scope.result = CalcService.square($scope.number);

            $scope.square = function() {
            $scope.result = CalcService.square($scope.number);
         }
      });
   </script>
</body>
</html>

Output

Open testAngularJS.htm in a web browser and see the result.
AngularJS Dependency Injection

AngularJS - Services

AngularJS supports the concept of Separation of Concerns using services architecture. Services are JavaScript functions, which are responsible to perform only specific tasks. This makes them individual entities which are maintainable and testable. The controllers and filters can call them on requirement basis. Services are normally injected using the dependency injection mechanism of AngularJS.
AngularJS provides many inbuilt services. For example, $http, $route, $window, $location, etc. Each service is responsible for a specific task such as the $http is used to make ajax call to get the server data, the $route is used to define the routing information, and so on. The inbuilt services are always prefixed with $ symbol.
There are two ways to create a service:
  • Factory
  • Service

Using Factory Method

In this method, we first define a factory and then assign method to it.
      var mainApp = angular.module("mainApp", []);
      mainApp.factory('MathService', function() {     
         var factory = {};  
         factory.multiply = function(a, b) {
            return a * b 
         }
         return factory;
      }); 

Using Service Method

In this method, we define a service and then assign method to it. We also inject an already available service to it.
mainApp.service('CalcService', function(MathService){
    this.square = function(a) { 
  return MathService.multiply(a,a); 
 }
});

Example

The following example shows use of all the above mentioned directives:

testAngularJS.htm

<html>
<head>
   <title>Angular JS Forms</title>
</head>
<body>
   <h2>AngularJS Sample Application</h2>
   <div ng-app="mainApp" ng-controller="CalcController">
      <p>Enter a number: <input type="number" ng-model="number" />
      <button ng-click="square()">X<sup>2</sup></button>
      <p>Result: {{result}}</p>
   </div>
   <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
   <script>
      var mainApp = angular.module("mainApp", []);
      mainApp.factory('MathService', function() {     
         var factory = {};  
         factory.multiply = function(a, b) {
            return a * b 
         }
         return factory;
      }); 

      mainApp.service('CalcService', function(MathService){
            this.square = function(a) { 
            return MathService.multiply(a,a); 
         }
      });

      mainApp.controller('CalcController', function($scope, CalcService) {
            $scope.square = function() {
            $scope.result = CalcService.square($scope.number);
         }
      });
   </script>
</body>
</html>

Output

Open the file testAngularJS.htm in a web browser and see the result.
AngularJS Services

AngularJS - Scopes

Scope is a special JavaScript object that connects controller with views. Scope contains model data. In controllers, model data is accessed via $scope object.
<script>
      var mainApp = angular.module("mainApp", []);

      mainApp.controller("shapeController", function($scope) {
         $scope.message = "In shape controller";
         $scope.type = "Shape";
      });
</script>
The following important points are considered in above example:
  • The $scope is passed as first argument to controller during its constructor definition.
  • The $scope.message and $scope.type are the models which are used in the HTML page.
  • We assign values to models that are reflected in the application module, whose controller is shapeController.
  • We can define functions in $scope.

Scope Inheritance

Scope is controller-specific. If we define nested controllers, then the child controller inherits the scope of its parent controller.
<script>
      var mainApp = angular.module("mainApp", []);

      mainApp.controller("shapeController", function($scope) {
         $scope.message = "In shape controller";
         $scope.type = "Shape";
      });
   
      mainApp.controller("circleController", function($scope) {
         $scope.message = "In circle controller";   
      });
</script>
The following important points are considered in above example:
  • We assign values to the models in shapeController.
  • We override message in child controller named circleController. When message is used within the module of controller named circleController, the overridden message is used.

Example

The following example shows use of all the above mentioned directives.

testAngularJS.htm

<html>
<head>
   <title>Angular JS Forms</title>
</head>
<body>
   <h2>AngularJS Sample Application</h2>
   <div ng-app="mainApp" ng-controller="shapeController">
      <p>{{message}} <br/> {{type}} </p>
      <div ng-controller="circleController">
         <p>{{message}} <br/> {{type}} </p>
      </div>
      <div ng-controller="squareController">
         <p>{{message}} <br/> {{type}} </p>
      </div>
   </div>
   <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
   <script>
      var mainApp = angular.module("mainApp", []);

      mainApp.controller("shapeController", function($scope) {
         $scope.message = "In shape controller";
         $scope.type = "Shape";
      });

      mainApp.controller("circleController", function($scope) {
         $scope.message = "In circle controller";   
      });

      mainApp.controller("squareController", function($scope) {
         $scope.message = "In square controller";
         $scope.type = "Square";
      });

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

Output

Open the file testAngularJS.htm in a web browser and see the result.
AngularJS Scopes

AngularJS - Views

AngularJS supports Single Page Application via multiple views on a single page. To do this, AngularJS has provided ng-view and ng-template directives, and $routeProvider services.

ng-view Directive

The ng-view directive simply creates a place holder where a corresponding view (HTML or ng-template view) can be placed based on the configuration.

Usage

Define a div with ng-view within the main module.
<div ng-app="mainApp">
...
   <div ng-view></div>

</div>    

ng-template Directive

The ng-template directive is used to create an HTML view using script tag. It contains id attribute which is used by $routeProvider to map a view with a controller.

Usage

Define a script block with type as ng-template within the main module.
<div ng-app="mainApp">
...
   <script type="text/ng-template" id="addStudent.htm">
      <h2> Add Student </h2>
         {{message}}
   </script>

</div>    

$routeProvider Service

The $routeProvider is a key service which sets the configuration of URLs, maps them with the corresponding HTML page or ng-template, and attaches a controller with the same.

Usage 1

Define a script block with type as ng-template within the main module.
<div ng-app="mainApp">
...
   <script type="text/ng-template" id="addStudent.htm">
      <h2> Add Student </h2>
         {{message}}
   </script>

</div>    

Usage 2

Define a script block with main module and set the routing configuration.
 var mainApp = angular.module("mainApp", ['ngRoute']);
      
      mainApp.config(['$routeProvider',
         function($routeProvider) {
            $routeProvider.
               when('/addStudent', {
                  templateUrl: 'addStudent.htm',
                  controller: 'AddStudentController'
               }).
               when('/viewStudents', {
                  templateUrl: 'viewStudents.htm',
                  controller: 'ViewStudentsController'
               }).
               otherwise({
                  redirectTo: '/addStudent'
               });
         }]);
    
The following points are important to be considered in the above example:
  • $routeProvider is defined as a function under config of mainApp module using key as '$routeProvider'.
  • $routeProvider.when defines a URL "/addStudent", which is mapped to "addStudent.htm". addStudent.htm should be present in the same path as main HTML page. If the HTML page is not defined, then ng-template needs to be used with id="addStudent.htm". We used ng-template.
  • "otherwise" is used to set the default view.
  • "controller" is used to set the corresponding controller for the view.

Example

The following example shows the use of all the above-mentioned directives.

testAngularJS.htm

<html>
<head>
   <title>Angular JS Views</title>
   <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
   <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.min.js"></script>
</head>
<body>
   <h2>AngularJS Sample Application</h2>
   <div ng-app="mainApp">
      <p><a href="#addStudent">Add Student</a></p>
      <p><a href="#viewStudents">View Students</a></p>
      <div ng-view></div>
      <script type="text/ng-template" id="addStudent.htm">
         <h2> Add Student </h2>
         {{message}}
      </script>
      <script type="text/ng-template" id="viewStudents.htm">
         <h2> View Students </h2>     
         {{message}}
      </script> 
   </div>

   <script>
      var mainApp = angular.module("mainApp", ['ngRoute']);
      
      mainApp.config(['$routeProvider',
         function($routeProvider) {
            $routeProvider.
               when('/addStudent', {
                  templateUrl: 'addStudent.htm',
                  controller: 'AddStudentController'
               }).
               when('/viewStudents', {
                  templateUrl: 'viewStudents.htm',
                  controller: 'ViewStudentsController'
               }).
               otherwise({
                  redirectTo: '/addStudent'
               });
         }]);

         mainApp.controller('AddStudentController', function($scope) {
            $scope.message = "This page will be used to display add student form";
         });

         mainApp.controller('ViewStudentsController', function($scope) {
            $scope.message = "This page will be used to display all the students";
         });
   </script>
</body>
</html>

Output

Open the file testAngularJS.htm in a web browser and see the result.
AngularJS Views