Wednesday, July 27, 2016

AngularJS And ASP.NET MVC Movie Library Application - Part Four AngularJS Routing with partial templates

DotnetPiper_Angular

Hope you got a chance to look into my last tutorials about technology stack, creating UI HTML page with Modules and Controllers, and Event Binding with UI elements. Kindly, find the links here:

Moving ahead, in this article, we’ll focus on integration of movie.html page with MVC layout page. Also, we’ll implement Angular routing in that.
Let’s get our hands busy with AngularJS & ASP.NET MVC Movie Library Application - Part Four.
So far, we’ve designed the following screen shot:
portal
For this purpose, I’ve created a few more pages so that we can implement routing easily. Kindly have a look at the image below, for reference.
reference
So, please create other pages as well. Probably after Part 6 of Movie Library Application, I’ll share my application with you for downloading.
Open the Solution Explorer and look for _Layout.cshtml page there. You can give reference of main.js (in our case it is routing.js) file as a reference there also, so that it would be applicable for all .cshtml pages.This is because _Layout page loads first in MVC life cycle.
Routing.js file contains all controllers' code used in all html pages e.g. Movie.html, searchMovie.html and tollywood.html.
It works in such a manner that as soon as the _layout.cshtml page loads, it also loads Module along with all respective controllers defined under this JavaScript file.
Kindly, find the code below for how to bind routing.js file.
code
If you have noticed in the above screenshot, I’ve set the menu using bootstrap which looks like the following screen, now:
screen
Understand ng_view: Another important factor is the usage of ng-view directive. In our angular app, we need to define ng-app directive once. Ng-view becomes the placeholder for views. Each view referred by the route is loaded in this section of the document which we have defined on _layout.cshtml. You can also define ng-view in main html file .There are a few ways to define it, as shown below. I’ve chosen <ng-view></ng-view> tag.
For my purpose, kindly refer to the above screen shot for reference and look at bottom of image.

  1. <div ng-view></div>
  2. <ng-view></ng-view>
  3. <div class="ng-view"></div>

Kindly, find the code below for_layout.cshtml, so that you may fit into your code segment also.
Code snippet _layout.cshtml

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8" />
  5. <title>@ViewBag.Title - My ASP.NET MVC Application</title>
  6. <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
  7. <meta name="viewport" content="width=device-width" />
  8.     @Styles.Render("~/Content/css") 
  9.     @Scripts.Render("~/bundles/modernizr") 
  10. <script src="~/Scripts/angular.min.js"></script>
  11. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-route.js"></script>
  12.     @*    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>*@ 
  13. <script src="~/Application/App.js"></script>
  14. <script src="~/Application/Routing.js"></script>
  15. </head>
  16. <body>
  17. <header>
  18. <div class="content-wrapper">
  19. <div class="float-right">
  20. <section id="login">
  21. </section>
  22. <nav>
  23. </nav>
  24. </div>
  25. </div>
  26. </header>
  27. <div id="body" ng-app="routingApp" class="float-center">
  28. <nav class="navbar navbar-inverse navbar-fixed-top">
  29. <div class="container-fluid">
  30. <div class="navbar-header">
  31. <a class="navbar-brand" href="www.dotnetpiper.com">DotnetPiper.Com</a>
  32. </div>
  33. <ul class="nav navbar-nav">
  34. <li class="active"><a href="#/Home"><b>Home</b></a></li>
  35. <li><a href="#/Movie"><b>Bollywood</b></a></li>
  36. <li><a href="#/SearchMovie"><b>Seacrh Movie Globally</b></a></li>
  37. <li><a href="#/Tolly"><b>Tollywood</b></a></li>
  38. </ul>
  39. <ul class="nav navbar-nav navbar-right">
  40. <li><a href="#"><span class="glyphicon glyphicon-user"></span>Sign Up</a></li>
  41. <li><a href="#"><span class="glyphicon glyphicon-log-in"></span>Login</a></li>
  42. </ul>
  43. </div>
  44. </nav>
  45. <ng-view></ng-view>
  46.         @RenderSection("featured", required: false) 
  47.         @RenderBody() 
  48. </div>
  49.     @* <footer>
  50. <div class="content-wrapper">
  51. <div class="float-left">
  52. <p>© @DateTime.Now.Year - My ASP.NET MVC Application</p>
  53. </div>
  54. </div>
  55. </footer>*@ 
  56.     @Scripts.Render("~/bundles/jquery") 
  57.     @RenderSection("scripts", required: false) 
  58. </body>
  59. </html>

Add Routing in AngularJS
We’ve included a JavaScript file, routing.js, which holds the application logic. Given below is the content of routing.js. Kindly ensure that you have given the reference for route.js, as shown below:

  1. /// <reference path="../Scripts/angular-route.js" />
  2. var routingApp = angular.module('routingApp', ['ngRoute']); 
  3. routingApp.config(['$routeProvider', function ($routeProvider) { 
  4. //alert("Route Initiated");
  5.     $routeProvider. 
  6.         when('/Home', { templateUrl: '/Application/login.html', controller: '/Application/testController' }). 
  7.         when('/Movie', { templateUrl: '/Application/Movie.html', controller: 'MovieController' }). 
  8.         when('/SearchMovie', { templateUrl: '/Application/SearchMovie.html', controller: 'ApiMovieController' }). 
  9.          when('/Tolly', { templateUrl: '/Application/Tollywood.html', controller: 'tollyController' }). 
  10.         otherwise({ redirectTo: '/' }); 
  11. }]); 

First, use .config() method to define $routeProvider configuration. The routeProvider identifies the route, e.g., whenever there will be a string “/Movie” in route URL, it should load template "/Application/Movie.html" from partial templates. (I’m calling these .html pages as partial pages).
After implementing the Routing, it should work in a way, as depicted below. Kindly notice the URLchanging on each click.
output
This is the complete code for routing.js which is main app file.

  1. /// <reference path="../Scripts/angular.js" />
  2. /// <reference path="../Scripts/fusioncharts.js" />
  3. /// <reference path="../Scripts/fusioncharts.charts.js" />
  4. /// <reference path="../Scripts/angular-route.js" />
  5. var routingApp = angular.module('routingApp', ['ngRoute']); 
  6. routingApp.config(['$routeProvider', function ($routeProvider) { 
  7. //alert("Route Initiated");
  8.     $routeProvider. 
  9.         when('/Home', { templateUrl: '/Application/login.html', controller: '/Application/testController' }). 
  10.         when('/Movie', { templateUrl: '/Application/Movie.html', controller: 'MovieController' }). 
  11.         when('/SearchMovie', { templateUrl: '/Application/SearchMovie.html', controller: 'ApiMovieController' }). 
  12.          when('/Tolly', { templateUrl: '/Application/Tollywood.html', controller: 'tollyController' }). 
  13.         otherwise({ redirectTo: '/' }); 
  14. }]); 
  15. routingApp.controller("tollyController", function ($scope) { 
  16.     $scope.tollyMessage = "Welcome to TollyWood to watch Action,Thriller and Suspence movies"; 
  17. }); 
  18. routingApp.controller("MovieController", ['$scope', function ($scope) { 
  19.     $scope.edit = false; 
  20.     $scope.message = "Welcome to DotnetPiper.com to learn Angular"; 
  21.     $scope.error = false; 
  22.     $scope.clear = false; 
  23.     $scope.success = false; 
  24. // alert("Servcie Called");
  25. var movies = [ 
  26.                 { title: "Revenent", year: "2015", rating: "5Star", plot: " A revenger Journey" }, 
  27.                  { title: "Counjouring2", year: "2016", rating: "4Star", plot: " A Complete Hourror" }, 
  28.                  { title: "DDLJ", year: "1995", rating: "SuperStar", plot: "Romantic love story" }, 
  29.                  { title: "Sultan", year: "2016", rating: "5Star", plot: "A Warrior" }, 
  30.                  { title: "BajiRao Mastani", year: "2015", rating: "4.5 Star", plot: "Film of the Year" } 
  31.     ]; 
  32.     $scope.movies = movies; 
  33.     $scope.AddMovie = function (movie) { 
  34. if ($scope.edit == true) { 
  35. var index = $scope.movies.indexOf(movie); 
  36. // alert("edit Called");
  37.             $scope.movies[index] = movie; 
  38. //alert(movie.rating);
  39.             $scope.updatedMovie = movie; 
  40.             $scope.success = true; 
  41.             $scope.movie = {}; 
  42.         } 
  43. else { 
  44. var newMovie = { 
  45.                 title: $scope.movie.title, 
  46.                 year: $scope.movie.year, 
  47.                 rating: $scope.movie.rating, 
  48.                 plot: $scope.movie.plot 
  49.             }; 
  50.             movies.push(newMovie); 
  51. // alert("Add Called");
  52.         } 
  53.     } 
  54.     $scope.DeleteMovie = function (movie, index) { 
  55.         movies.splice(index, 1); 
  56. // $scope.movie = movie;
  57.         $scope.updatedMovie = movie; 
  58.         $scope.success = false; 
  59.         $scope.clear = true; 
  60.         $scope.movie = {}; 
  61.         console.log(index); 
  62.     } 
  63.     $scope.EditMovie = function (movie, index) { 
  64.         $scope.selectedRow = null;  // initialize our variable to null
  65.         $scope.selectedRow = index; 
  66.         $scope.movie = movie; 
  67.         $scope.edit = true; 
  68.     } 
  69. }]); 

Hope it’ll help you some day. Enjoy Coding.

Learn WebAPi and MVC Here

Wednesday, July 20, 2016

AngularJS And ASP.NET MVC Movie Library Application - Part Three- EventBinding with UI Elements

I hope you have had a chance to look into my last tutorial. Here, I will talk about the Event binding with UI elements of Movie.html page within module and controller.

And this will the outcome after binding all control with controller’s function as depicted below:


Kindly find links here as shown below:

Moving ahead in this article, we’ll focus on how to bind UI controls events and link with the defined controller.
$scope plays a vital role whenever you bind the controller value with the specific view. Here, we are going to learn it. After using this, I believe that it would be a kind of ice-breaker and will ease all the further learnings. Let's get our hands dirty with AngularJS & ASP.NET MVC Movie Library Application Tutorials part three.
So far, we’ve designed the screen shot, given below:
screen shot
Hope, you will have also reached up to this level. Moving ahead, let's bind the fancy bootstrap glyphicon icon into an action.
Add the ng-click event, one by one, on each respective control.There are thee HTML button controls that exist. 
First – Add button with + symol
Second – Edit button with pencil symbol
Third - Cross with * Symbol.
Kindly paste the code segment, given below, into the movie.html page.
Code segment Movie.html

  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <h2>Movie Rating Portal</h2>
  5. <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  6. <style>
  7.         .selected 
  8.         { 
  9.             background-color: lightyellow; 
  10.             color: red; 
  11.             font-weight: bold; 
  12.         } 
  13. </style>
  14. </head>
  15. <body ng-app="routingApp" class="jumbotron">
  16. <div ng-controller="MovieController" class="container">
  17. <div ng-show="success" class="alert-success">Record has been upddated for movie :  {{updatedMovie.title}}</div>
  18. <div ng-show="clear" class="alert-success">Record has been deleted for movie :  {{updatedMovie.title}}</div>
  19. <div class="row col-md-8">
  20. <table class="table table-striped ">
  21. <thead class="thead-inverse">
  22. <th style="background-color: Highlight">Title</th>
  23. <th style="background-color: Highlight">Year of Release</th>
  24. <th style="background-color: Highlight">Rating</th>
  25. <th style="background-color: Highlight">Plot</th>
  26. <th style="background-color: Highlight">Actions</th>
  27. </thead>
  28. <tr>
  29. <!-- <td>EmployeeID:</td>-->
  30. <td>
  31. <input type="text" ng-model="movie.title" class="form-control" />
  32. </td>
  33. <td>
  34. <input type="text" ng-model="movie.year" class="form-control" />
  35. </td>
  36. <td>
  37. <input type="text" ng-model="movie.rating" class="form-control" />
  38. </td>
  39. <td>
  40. <input type="text" ng-model="movie.plot" class="form-control" />
  41. </td>
  42. <td>
  43. <button type="button" ng-click="AddMovie(movie)" class="btn btn-primary">
  44. <span class="glyphicon glyphicon-plus"></span>
  45. </button>
  46. </td>
  47. </tr>
  48. <tbody>
  49. <tr ng-repeat="movie in movies" ng-class="{'selected':$index == selectedRow}">
  50. <td>{{movie.title}} 
  51. </td>
  52. <td>{{movie.year}} 
  53. </td>
  54. <td>{{movie.rating}} 
  55. </td>
  56. <td>{{movie.plot }} 
  57. </td>
  58. <td>
  59. <button type="button" ng-click="EditMovie(movie,$index)" class="btn btn-warning">
  60. <span class="glyphicon glyphicon-pencil"></span>
  61. </button>
  62. <button type="button" ng-click="DeleteMovie(movie,$index)" class="btn btn-danger">
  63. <span class="glyphicon glyphicon-remove"></span>
  64. </button>
  65. </td>
  66. </tr>
  67. </tbody>
  68. </table>
  69. </div>
  70. </div>
  71. </body>
  72. </html>

 

code
Now, we are almost done with the UI part and have created the required ng-click events on all the buttons existing on the page.
Now,  it'stime to design the controller and write the code so that  every button should work very effectively. Thus, please copy and paste the code, given below and replace it within routing.js file.

  1. /// <reference path="../Scripts/angular.js" />
  2. var routingApp = angular.module('routingApp', []); 
  3. routingApp.controller("MovieController", ['$scope', function ($scope) { 
  4.     $scope.edit = false; 
  5.     $scope.message = "Welcome to DotnetPiper.com to learn Angular"; 
  6.     $scope.error = false; 
  7.     $scope.clear = false; 
  8.     $scope.success = false; 
  9. // alert("Servcie Called");
  10. var movies = [ 
  11.                 { title: "Revenent", year: "2015", rating: "5Star", plot: " A revenger Journey" }, 
  12.                  { title: "Counjouring2", year: "2016", rating: "4Star", plot: " A Complete Hourror" }, 
  13.                  { title: "DDLJ", year: "1995", rating: "SuperStar", plot: "Romantic love story" }, 
  14.                  { title: "Sultan", year: "2016", rating: "5Star", plot: "A Warrior" }, 
  15.                  { title: "BajiRao Mastani", year: "2015", rating: "4.5 Star", plot: "Film of the Year" } 
  16.     ]; 
  17.     $scope.movies = movies; 
  18.     $scope.AddMovie = function (movie) { 
  19. if ($scope.edit == true) { 
  20. var index = $scope.movies.indexOf(movie); 
  21. // alert("edit Called");
  22.             $scope.movies[index] = movie; 
  23. //alert(movie.rating);
  24.             $scope.updatedMovie = movie; 
  25.             $scope.success = true; 
  26.             $scope.movie = {}; 
  27.         } 
  28. else { 
  29. var newMovie = { 
  30.                 title: $scope.movie.title, 
  31.                 year: $scope.movie.year, 
  32.                 rating: $scope.movie.rating, 
  33.                 plot: $scope.movie.plot 
  34.             }; 
  35.             movies.push(newMovie); 
  36. // alert("Add Called");
  37.         } 
  38.     } 
  39.     $scope.DeleteMovie = function (movie,index) { 
  40.         movies.splice(index, 1); 
  41. // $scope.movie = movie;
  42.         $scope.updatedMovie = movie; 
  43.         $scope.success = false; 
  44.         $scope.clear = true; 
  45.         $scope.movie = {}; 
  46.         console.log(index); 
  47.     } 
  48.     $scope.EditMovie = function (movie, index) { 
  49.         $scope.selectedRow = null;  // initialize our variable to null
  50.         $scope.selectedRow = index; 
  51.         $scope.movie = movie;         
  52.         $scope.edit = true; 
  53.     } 
  54. }]); 

Run your Application now and it should perform the actions. Once you run an Application, give the path of your desired page. It should look, as given below, in the screenshot. For now, the button will be working as anticipated.
output
Kindly open Movie.html page and find the given below line and understand its actual fact. Please refer below the screen, given below:
code
There are three major cases here as shown below:
First – Add button with + symbol
Second – Edit button with pencil symbol
Third - Cross with * Symbol.

Kindly find GIF image, given below, which performs all the actions. It will help you to understand the facts.

Hope this will help you some day. Enjoy coding.

Tuesday, July 19, 2016

AngularJS And ASP.NET MVC Movie Library Application - Part Two Module,Controller,$Scope and Twitter Bootstrap

Hope you have had a chance to look into last the tutorial here which states about the technology stack and a other few vital keywords and terminology. Moving ahead in this article we’ll focus on adding a html page and will create module and controller as well as $scope element. Let’s get our hands dirty with AngularJS & ASP.NET MVC Movie Library Application Tutorials part two.

This is the technology stack for this Movie library application as shown below,
stack
Kindly create a MVC application as I have created and name it as per your need, for now I have also selected test project because we may write some TDD code later if needed though it is not essential. I’ve also added Application folder as per my need.
folder
After creating go to sample project, kindly go to NuGet package manager and choose AngularJS from there as shown in the below screen shots.
NuGet package manage
NuGet package manage
Go to the application folder and add an html page and named it Movie.html as shown in solution structure also. Add the following code in your respective page (movie.html) to make it function.
Code segment Movie.html
  1. <!DOCTYPE html>
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <h2>Movie Rating Portal</h2>
  5. <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  6. <script src="../Scripts/angular.js"></script>
  7. <style>
  8.         .selected 
  9.         { 
  10.             background-color: lightyellow; 
  11.             color: red; 
  12.             font-weight: bold; 
  13.         } 
  14. </style>
  15. </head>
  16. <body ng-app="routingApp" class="jumbotron">
  17. <div ng-controller="MovieController" class="container">
  18. <div ng-show="success" class="alert-success">Record has been upddated for movie :  {{updatedMovie.title}}</div>
  19. <div class="row col-md-8">
  20. <table class="table table-striped ">
  21. <thead class="thead-inverse">
  22. <th style="background-color: Highlight">Title</th>
  23. <th style="background-color: Highlight">Year of Release</th>
  24. <th style="background-color: Highlight">Rating</th>
  25. <th style="background-color: Highlight">Plot</th>
  26. <th style="background-color: Highlight">Actions</th>
  27. </thead>
  28. <tr>
  29. <!-- <td>EmployeeID:</td>-->
  30. <td>
  31. <input type="text" ng-model="movie.title" class="form-control" />
  32. </td>
  33. <td>
  34. <input type="text" ng-model="movie.year" class="form-control" />
  35. </td>
  36. <td>
  37. <input type="text" ng-model="movie.rating" class="form-control" />
  38. </td>
  39. <td>
  40. <input type="text" ng-model="movie.plot" class="form-control" />
  41. </td>
  42. <td>
  43. <button type="button" class="btn btn-primary">
  44. <span class="glyphicon glyphicon-plus"></span>
  45. </button>
  46. </td>
  47. </tr>
  48. <tbody>
  49. <tr ng-repeat="movie in movies" ng-class="{'selected':$index == selectedRow}">
  50. <td>{{movie.title}} 
  51. </td>
  52. <td>{{movie.year}} 
  53. </td>
  54. <td>{{movie.rating}} 
  55. </td>
  56. <td>{{movie.plot }} 
  57. </td>
  58. <td>
  59. <button type="button" class="btn btn-warning">
  60. <span class="glyphicon glyphicon-pencil"></span>
  61. </button>
  62. <button type="button" class="btn btn-danger">
  63. <span class="glyphicon glyphicon-remove"></span>
  64. </button>
  65. </td>
  66. </tr>
  67. </tbody>
  68. </table>
  69. </div>
  70. </div>
  71. </body>
  72. </html>
    [sourcecode language='csharp'  padlinenumbers='true' htmlscript='false' light='true' wraplines='true' firstline='1' collapse='false' autolinks='false' toolbar='false']
    
    [/sourcecode]
    

    Note : Kindly add the reference of bootstrap as given below on movie.html partial template file.

    1. <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> 

    We are almost done with the UI part and it’s time to create Module and a controller to make .html fully functional. Add a .js file too --  I’ve added routing.js file and added the following code segment in that.

    1. /// <reference path="../Scripts/angular.js" />
    2. var routingApp = angular.module('routingApp', []); 
    3. routingApp.controller("MovieController", ['$scope', function ($scope) { 
    4.     $scope.edit = false; 
    5.     $scope.message = "Welcome to DotnetPiper.com to learn Angular"; 
    6.     $scope.error = false; 
    7.     $scope.success = false; 
    8. // alert("Servcie Called");
    9.     var movies = [ 
    10.                 { title: "Revenent", year: "2015", rating: "5Star", plot: " A revenger Journey" }, 
    11.                  { title: "Counjouring2", year: "2016", rating: "4Star", plot: " A Complete Hourror" }, 
    12.                  { title: "DDLJ", year: "1995", rating: "SuperStar", plot: "Romantic love story" }, 
    13.                  { title: "Sultan", year: "2016", rating: "5Star", plot: "A Warrior" }, 
    14.                  { title: "BajiRao Mastani", year: "2015", rating: "4.5 Star", plot: "Film of the Year" } 
    15.     ]; 
    16.     $scope.movies = movies; 
    17. }]); 

     

    Note : Module is like a namespace which has various classes like controller. Each module may have many controllers, and each controller can be bind to divtable or other html element. Once you have bound controller to some element then you can access each property of controller using $scope within that element scope.
    Refer to given below image for reference,
    reference
    If you look at the image given below it is the Movie page which brings data from controller. For this purpose we have movie.html page which had a few controls. To beautify html controls I’ve added twitter bootstrap on each as permy need.
    One you run an application give the path of your desired page. It should look like as given below in screen shot. For now button would not be working. That we’ll cover inthe next part.
    application
    Hope it’ll help you some day. Enjoy Coding.

    Monday, July 18, 2016

    AngularJS And ASP.NET MVC Movie Library Application - Part One

    Here I’ve merely thought to write my thoughts about hands on Angular. This is a first article which tells you how to get your hands dirty with AngularJS & ASP.NET MVC Movie Library Application Tutorials.
    This is the technology stack for this Movie library application as shown below,
    application
    I’ve designed a Simple Movie Library application in which you will get familiar with a few keywords and components which you may be confronting in the coming days. Those keywords are shown below in the article,

    Component of Angular
    Description

    Module
    Modules serve as containers to assist you to organize code within your AngularJS application. Modules can contain sub-modules.

    $http
    $http is an AngularJS service for reading data from remote servers

    Services
    Services are a point where you can put common functionality to an AngularJS application. E.g. if you would like to share data with more than one controller then bthe est way is to promote that data to a service and then make it available via the service. Services extend controllers and make them more globally accessible.

    Routes Routing in Angular JS
    Routes allow us to determine ways to navigate to specific states within our application. It also allows us to define configuration options for each specific route, such as which template and controller to use.

    View
    The view in AngularJS is what exists after AngularJS has compiled and rendered the DOM. It’s a representation of whatever outcome

    @scope
    $scope is essentially the “glue” between the view and controller within an AngularJS application. And somewhere support two way binding with in application.

    controller
    The controller is responsible for defining methods and properties that the view can bind to and interact with. Controllers should be lightweight and only focus on the view they’re controlling.

    directive
    A directive is an extension of a view in AngularJS in that it allows us to create custom, reusable elements. You can also consider directives as decorators for your HTML. Directives are used to extend views and to make these extensions available for use in more than one place.

    Route Config
    The config block of an AngularJS application allows for configuration to be applied before the application actually runs. This is useful for setting up routes, dynamically configuring services, and so on.

    Dependency Injection
    How can we inject dependency in Angular controller and module?

    The application which we are about to build consists of almost all of the above defined keywords and the initial look of the application is as shown below.


    application
    There are a few points which we’ll cover in this application to make it complete,

    • The above screen shot is a sample form for Movie Library application which has the option to add edit movie and delete movie.
    • We’ll try to integrate one of the live movie apis in our application and will put search feature also to make searching easier.
    • As well as focus on Custom Directive and Custom Service.
    • Usage of $http to call to WebApi to populate data on html page.
    • Load partial templates to MVC view page.
    • Fusion chart integration with existing application, so that everyone may get an idea about this.
    • The structure of the Movie Library application would be like given below:
      structure

    And given below is the basic life cycle of the Angular App.
    basic life cycle
    Hope this will help you some day. Enjoy Coding

    Wednesday, July 13, 2016

    Error: [$injector:nomod] Module ‘ngRoute’, ‘ngResource’ is not available – AngularJS

    During An Angular Application devlopement i confronted various errors and the given below is one of them as shown below:

    Uncaught Error: [$injector:modulerr] Failed to instantiate module routingApp due to:

    Error: [$injector:modulerr] Failed to instantiate module ngRoute due to:

    Error: [$injector:nomod] Module 'ngRoute' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

    http://errors.angularjs.org/1.2.6/$injector/nomod?p0=ngRoute

    Solution

    The possible errors rises because of the latest js library is not placed in current file.so use the following link to mitigate such error.Add the given below reference in that file where you have placed routing configuration.

      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-route.js"></script>

    Hope it will resolve an error.

    Thanks

    Thursday, July 7, 2016

    Web API Pipeline Revealed: A True Practical Approach

    Web API Pipeline Revealed: A True Practical Approach

    What is WebApi?
    This question carries a lot of weight. Web API is a small word but it has lots of extensive features.
    Here is an excerpt about Web API:
    ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. It is an ideal platform for building RESTful applications on the .NET Framework. This poster shows how an HTTP request flows through the Web API pipeline, and how the HTTP response flows back. The diagram also shows extensibility points, where you can add custom code or even replace the default behavior entirely.
    This article is about WebApi and its Pipeline. Pipeline in simple words is HttpRequest as pipeline and HttpResponse as an output. Kindly refer to the image below:
    pipeline
    This will be an agenda for this article as shown below:
    • WebApi Definition.
    • WebApi Pipeline architecture
    • WebApi Hosting
    • WebApi HttpRequest & HttpResponse Message format
    • WebApi Delegate Handler
    • Routing Dispatcher and per-route message handler
    • HttpControllerDispatcher
    • Authentication & Authorization Filters
    • Model Binders, Value Providers and Action Filters
    • IHttpActionInvoker & Exception Filters
    • Result Conversation
    Web API Definition
    ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. It is an ideal platform for building RESTful applications on the .NET Framework. This poster shows how an HTTP request flows through the Web API pipeline, and how the HTTP response flows back. The diagram also shows extensibility points, where you can add custom code or even replace the default behavior entirely.
    Web API Architecture Here is typical pipeline architecture for Web API as in the following screenshot:
    Architecture
    Web API Hosting
    You can host Web API inside IIS or inside your own process (self-hosting).
    ASP.NET Hosting
    You can host Web API on ASP.NET server and IIS server. For more details kindly go through the following details how to host Web API in IIS: WebApi Hosting in Internet Information Server (IIS 7.5).
    Self-Hosting using OWIN In Self Hosting you can use OWIN to Self-Host ASP.NET Web API, The HttpServer pipeline starts at the HttpSelfHostServer which is an implementation of HttpServer and directly listens to HTTP requests.
    WebApi HttpRequest & HttpResponse Message format The HTTP request message is first converted to an HttpRequestMessage object, which provides strongly typed access to the HTTP message. There are two types of Http messages HttpRequest and HttpResponse. Each of this has their own format before sending it to respective server and received response from server.
    The structure of HttpRequestMessage format is as follows with a pictorial representation.
    1. <request-line> 
    2. <general-headers> 
    3. <request-headers> 
    4. <entity-headers> 
    5. <empty-line> 
    6. [<message-body>] 
    7. [<message-trailers>] 
    structure
    The structure of HttpResponseMessage format is as follows with a pictorial representation.
    1. <Status-line> 
    2. <general-headers> 
    3. <response-headers> 
    4. <entity-headers> 
    5. <empty-line> 
    6. [<message-body>] 
    7. [<message-trailers>] 
    structure
    This is the way to understand the HttpRequest and HttpResponse messages.
    Web API Delegate Handler HTTP message handlers are the first stage in the processing pipeline after the request leaves the service host. Further it travels in pipeline as HttpRequestMessage in Pipeline. They process HTTP request messages on the way in, and HTTP response messages on the way out. To create a custom message handler, derive from the DelegatingHandler class. You can add multiple message handlers. Message handlers can be global or assigned to a specific route and called as per-route message handler. Per-route message handler is invoked only when the request matches that route. Per-route message handlers are configured in the routing table. A message handler can create the response directly, skipping the rest of the pipeline.
    Delegate handlers are extensibility points which you can customize as per your need. One of the reasons may be to verify the request authenticity and to verify some potential information in the http request .You may also customize the Http response as well and customize messages. A message handler can create the response directly, skipping the rest of the pipeline. Kindly refer to the below image for reference to register global handler in pipeline. There is an example, how a message handler might help you,
    • Read or modify request headers.
    • Add a response header to responses.
    • Validate requests before they reach the controller.
    code
    config.MessageHandlers.Add(new CustomHandler_One());
    Routing Dispatcher and per-route message handler
    After registering global handler and its execution request reaches HttpRouteDispatcher and sends it further in pipeline. HttpRoutingDispatcher dispatches the request based on the route. As per the WebApi Pipeline diagram above HttpRouteDispatcher verifies whether Route handler is null or contains any handler and takes an anticipated action on the basis of that. Delegate handlers give you the privilege to customize the pipeline and allow you to skip the pipeline. You can add a message handler to a specific route when you define the route there i s a typical image which describes multiple handlers globally and per route handler in pipeline.
    Reference
    diagram
    Image Source: asp.net
    If you notice in above image that MessageHandler2 doesn’t go to the default HttpControllerDispatcher. Here, MessageHandler2 creates the response, on basis of requests that match "PerRoute" never go to a controller further and skips the pipeline. Kindly refer to the code shown below to register the Per-Route handler in WebApiConfig.cs file as shown below in screen shot and code segment as well.
    code
    1. public static class WebApiConfig 
    2. public static void Register(System.Web.Http.HttpConfiguration config)  
    3.   { 
    4.         config.MapHttpAttributeRoutes(); 
    5.         config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new
    6.         { 
    7.             id = RouteParameter.Optional 
    8.         }); 
    9.         config.MessageHandlers.Add(new CustomHandler_One()); 
    10.         config.Routes.MapHttpRoute(name: "PerRoute", routeTemplate: "api2/{controller}/{action}/{id}", defaults: new
    11.             { 
    12.                 id = RouteParameter.Optional 
    13.             }, constraints: null, handler: new CustomHandler_Two() 
    14. //handler: HttpClientFactory.CreatePipeline(
    15. //new HttpControllerDispatcher(config),
    16. //new DelegatingHandler[] { new CustomHandler_Two() })
    17.         ); 
    18.     } 
    If you want “PerRoute” handler to execute complete WebApi pipeline as well as further reach to HttpControllerDispatcher then you just require registering PerRoute handler in WebApiConfig as given below in code segment.
    1. public static class WebApiConfig 
    2. public static void Register(System.Web.Http.HttpConfiguration config)  
    3.   { 
    4.         config.MapHttpAttributeRoutes(); 
    5.         config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new
    6.          { 
    7.             id = RouteParameter.Optional 
    8.         }); 
    9.         config.MessageHandlers.Add(new CustomHandler_One()); 
    10.         config.Routes.MapHttpRoute(name: "PerRoute", routeTemplate: "api2/{controller}/{action}/{id}", defaults: new
    11.          { 
    12.                 id = RouteParameter.Optional 
    13.             }, constraints: null, 
    14. // handler: new CustomHandler_Two()
    15.             handler: HttpClientFactory.CreatePipeline(new HttpControllerDispatcher(config), new DelegatingHandler[] 
    16.             { 
    17. new CustomHandler_Two() 
    18.             })); 
    19.     } 
    code
    HttpControllerDispatcher
    HttpControllerDispatcher sends the request to a Web API controller.
    HttpControllerDispatcher is related to Delegate handler somewhere because whenever you create any custom handler it calls SendAsync(request, cancellationToken) method which redirects call to inner Handler and generally this inner handler is HttpControllerDispatcher which handles the controller action request. Kindly refer one of the following screen:
    table
    This is one of the execution flow of HttpRequest starts from HttpMessageHandler till controller descriptor and Action selector as per my understanding as shown below,
    image
    Authentication & Authorization Filters If I think deeply about an above picture than security is an always a major concern in Web-based applications. You should have proper set of implementation in form of Authenticaiton and authorization technique to secure that data. As you know that ASP.Net Web API is a lightweight framework used for building stateless RESTful services that run on HTTP. There is authentication filter introduced in WebApi2. Authentication filters allows you to create an authentication scheme for individual controllers or actions. Both of these works in a pattern like given below:
    • Authentication proves the identity of the client.
    • Authorization determines whether the client can access a particular resource. To implement Authentication filters class should implement System.Web.Http.Filters.IAuthenticationFilter interface.
    The IAuthenticationFilter interface has two methods
    • AuthenticateAsync authenticates the request by validating credentials in the request, if present.
    • ChallengeAsync adds an authentication challenge to the HTTP response, if needed.
    Here is the flow in the Web API 2 pipeline using Authentication and Authorization filter
    1. Web API creates an authentication filters before invoking an action. Authentication filter can be apply at action scope, controller scope, and global scope.
    2. Web API calls AuthenticateAsync on every filter. Each filter validates credentials in the request. If any filter successfully validates credentials, the filter creates an IPrincipal and attaches it to the request. If an error occurs at filter level than it skips the rest of the WebApi pipeline.
    3. Suppose if there is no error, the HttpRequest goes and execute through the rest of the pipeline.
    4. Finally, Web API calls every authentication filter’s ChallengeAsync method. Filters use this method to add a challenge to the response, if needed. Sometime it happens in response to a 401 error.
    5. The diagram showed below states a possibility and its execution flow. The authentication filter successfully authenticates the HttpRequest, an authorization filter authorizes the request, and the controller action returns 200 (OK). Reference http://asp.net
      flow
    Authentication filter has two methods AuthenticateAsync and ChallengeAsync as shown below in code snippet. The primary purpose of the ChallengeAsync is to manage and add challenge in response. There is a class named as ResultWithChallenge below in code segment which is responsible to call ExecuteAsync and further calls InnerResult. ExecuteAsync to create the HTTP response, and then adds the challenge if needed.
    1. public class CustomAuthenticationFilterAttribute: Attribute, IAuthenticationFilter  
    2.   #region IAuthenticationFilter Members
    3. public System.Threading.Tasks.Task AuthenticateAsync(HttpAuthenticationContext context, System.Threading.CancellationToken cancellationToken) { 
    4. return Task.FromResult(0); 
    5.     } 
    6. public System.Threading.Tasks.Task ChallengeAsync(HttpAuthenticationChallengeContext context, System.Threading.CancellationToken cancellationToken) { 
    7.         context.Result = new CustomResultChallenge(context.Result, "Authentication Failed!!!"); 
    8. return Task.FromResult(0); 
    9.     } 
    10.   #endregion# region IFilter Members
    11. public bool AllowMultiple 
    12.     { 
    13. get
    14.         { 
    15. return false; 
    16.         } 
    17.     }#endregion 
    Let’s verify that how does WebApi respond from ChallengeAsync with Unauthorized status. Press F5 and see WebApi is running after getting below screen shot:
    web api
    Send the Get request in order to verify the execution cycle as given below. Copy and paste the following Url (http://localhost:57888/api/employees/GetEmp/5) in PostMan tool as depicted below in screen shot.
    output
    As soon as you click on the send button it reaches to Custom value provider’s method to execute set of statement and gives you following output in an image shown below:
    output
    Model Binders, Value Providers
    image
    Model binding uses the request to create values for the parameters of the action .These values are passed to the action when the action is invoked or binding is a mechanism used by the WebApi to mapping request to an object defined in the controller. Model binding is the process of creating .NET objects using the data sent by the browser in an HTTP request. We have been relying on the model binding process each time defines an action method that takes a parameter. the parameter objects are created by model binding. Model binding is ASP.NET mechanism for mapping HTTP request data directly into action method parameters and custom .Net objects.
    • For example, when we receive a request for a URL such as "/Home/ Employees/23", the framework must map the details of the request in such a way that it can pass appropriate values or objects as parameters to our action method. A model binder gets raw input values from a value provider and later value provider takes the HTTP request and populates a dictionary of key-value pairs. Further the model binder uses this dictionary to populate the model.
    The action invoker, the component that invokes action methods, is responsible for obtaining values for parameters before it can invoke the action method.
    Value Providers Value Providers are the components that feed data to model binders. Feeding the data means installing the data to the Model binder for further use at the action level. Value provider takes the HTTP request and populates a dictionary of key-value pairs which is later used by model binder to populate the model.
    The framework contains a few built-in value providers named FormValueProvider, RouteDataValueProvider, QueryStringValueProvider and HttpFileCollectionValueProvider that fetch data from Request.Form, Request.QueryString, Request.Files and RouteData.Values.
    The code shown below for CustomValueProvider used at this application level as well as way to use it at action level in an image shown below:
    1. public class CustomHeaderValueProvider: IValueProvider 
    2.   #region IValueProvider Members
    3. public Dictionary < string, string > objCollection; 
    4. public CustomHeaderValueProvider(HttpActionContext context)  
    5.     { 
    6.         objCollection = new Dictionary < string, string > (); 
    7. foreach(var item in context.Request.Headers)  
    8.         { 
    9.             objCollection.Add(item.Key, string.Join(string.Empty, item.Value)); 
    10.         } 
    11.     } 
    12. public bool ContainsPrefix(string prefix) 
    13.     { 
    14. return objCollection.Keys.Contains(prefix); 
    15.     } 
    16. public ValueProviderResult GetValue(string key)  
    17.     { 
    18. string resultValue; 
    19. if (key == null) throw new Exception("NullReferenceException"); 
    20. if (objCollection.TryGetValue(key, out resultValue)) 
    21.         { 
    22. return new ValueProviderResult(resultValue, resultValue, System.Globalization.CultureInfo.InvariantCulture); 
    23.         } 
    24. return null; 
    25.     }#endregion 
    26. public class CustomValueProviderFactory: ValueProviderFactory  
    27. public override IValueProvider GetValueProvider(HttpActionContext actionContext) 
    28.     { 
    29. return new CustomHeaderValueProvider(actionContext); 
    30.     } 
    code
    reminder
    At the time of the model binding the DefaultModelBinder checks with the value providers to determine if they can return a value for the parameter (example empId) by calling the ContainsPrefix method. If none of the value providers registered can return then it checks through CustomtvalueProvider whether such a parameter is stored and if yes it returns the value.
    This is one of the best pictorial representations taken from http://asp.net site is shown below which is again self-explanatory.
    Image taken from http://asp.net
    image
    Kindly refer this link for more understanding on Model Binder Invoke Action with Model Binders andFetch Header Information Using CustomValueProvider in ASP.NET Web API
    IHttpActionInvoker & Action Filters
    Once ApiControllerActionInvoker selects an action to handle an HTTP request, and is responsible for producing HttpResponse of your action. The action invoker, the component that invokes action methods, is responsible for obtaining values for parameters before it can invoke the action method. In other words, the invoker gets an instance of HttpActionContext and is expected to produce an HttpResponseMessage out of it. For this purpose it has to invoke an ExecuteAsync method on the
    HttpActionDescriptor present on the HttpActionContext Action Invoker can be a point to manage your exception at global level and returns a response on basis of the result returned by action method of controller. There is an interface shown given below to implement custom action invoker which has method to implement as shown below:
    1. public interface IHttpActionInvoker{ 
    2. Task<HttpResponseMessage> InvokeActionAsync(HttpActionContext actionContext, CancellationToken cancellationToken); 
    There can be three possible scenarios which can be maintained at ActionInvoker level,
    1. You action returns an object than it has to convert into HttpResponseMessgae by IActionResultConverter and run content negotiation with the help of request.createResponse().
    2. If action returns IHttpActionResult than it can be convert into HttpResponseMessage at action invoker level. Which gives privilege to mold your response at this level?
    3. It can return HttpResponseMessage directly from action method.
    I’ve created Custom action invoker at my application level to achieve Exception Handling after returning result by the action and later apply code at action invoker level to change it into HttpResponseMessege.
    1. public class Custom_ControllerActionInvoker: ApiControllerActionInvoker, IHttpActionInvoker 
    2. public override System.Threading.Tasks.Task < System.Net.Http.HttpResponseMessage > InvokeActionAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken) { 
    3.         var objResult = base.InvokeActionAsync(actionContext, cancellationToken); 
    4.         actionContext.Request.Properties["RuntimeReturnType"] = objResult.GetType(); 
    5. if (objResult.Exception != null)  
    6.         { 
    7.             Debug.WriteLine("Exception thrwon by controller {0} :", actionContext.ControllerContext.Controller); 
    8. return Task.Run < HttpResponseMessage > (() => new HttpResponseMessage(HttpStatusCode.InternalServerError)); 
    9.         } else if (objResult.Result.StatusCode == HttpStatusCode.Forbidden)  
    10.         { 
    11. //Log critical error
    12.             Debug.WriteLine("Exception thrwon by controller {0} :", actionContext.ControllerContext.Controller); 
    13. return Task.Run < HttpResponseMessage > (() => new HttpResponseMessage(objResult.Result.StatusCode)); 
    14.         } 
    15. return objResult; 
    16.     } 
    code
    Kindly find a screen shot and code segment to register CustomActionInvoker in an application as shown below:
    code
    1. GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpActionInvoker), new Custom_ControllerActionInvoker()); 
    Action Filters Custom filters and attributes are an excellent way to inject extra processing logic into the MVC request response pipeline. At some level programmer would be happy to inject some pre-processing or post-processing logic for actions and controllers. In that case we use filters.

    This filter will be called before and after the action starts executing and after the action has executed. It comes under namespace using System.Web.Http.Filters;
    OnActionExecuting occurs just before the action method is called.
    OnActionExecuted occurs after the action method is called, but before the result is executed (before the view is rendered).
    1. public class CustomActionWebApiFilters: ActionFilterAttribute  
    2. public override void OnActionExecuting(HttpActionContext actionContext) 
    3.     { 
    4. // pre-processing
    5.         Debug.WriteLine("Action just added pre-processing logging/information..."); 
    6.     } 
    7. public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)  
    8.     { 
    9. //Write your custom logic here
    10.     } 
    I’ve also added Exception filter to manage exception at code level an the respective code shown below:
    1. public class CustomExceptionFilterAttribute: ExceptionFilterAttribute 
    2. public override void OnException(HttpActionExecutedContext actionExecutedContext)  
    3.     { 
    4. if (actionExecutedContext.Exception is ArgumentException) 
    5.         { 
    6.             actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented); 
    7.         } 
    8.     } 
    Kindly find a way to register an Exception filter in global.asax file as given below as well as uses at controller’s action level.
    1. GlobalConfiguration.Configuration.Filters.Add(new CustomExceptionFilterAttribute()); 
    code
    reminder
    IHttpActionInvoker can be applying to manage Exception at action level.
    IHttpActionInvoker can be used to read runtime context sent by action and made further amendment to send it further as HttpResponseMessage.You may learn more about Action filters in WebApi from thislink
    Result Conversation
    As name implies Result conversation is about to convert return value from action in form of HttpResponseMessege.The result returned by the an action can be in multiple form and those forms are given below with pictorial representation taken from
    Image taken from http://asp.net
    image
    • HttpResponseMessege: If return type is HttpResponseMessage sent it directly.
    • Void : If return type is void, create response with status 204 (No Content)
    • IHttpActionResult: Call ExecuteAsync to create an HttpResponseMessage, and then convert to an HTTP response message.
    • Other Types: For return types, Web API uses a media formatter to serialize the return value. Web API writes the serialized value into the response body. The response status code is 200 (OK).
    IHttpActionResult plays a vital role in HttpResponseMessege category ,because it allows you return your own return set after introducing in WebAPI2 .There are few advantages of IHttpActionResult are listed below:
    • Moves common logic for creating HTTP responses into separate classes. Which makes code readability easier.
    • Makes the controller action clear and concise, by hiding the low-level details of constructing the response.
    IHttpActionResult contains a single method, ExecuteAsync, which asynchronously creates an HttpResponseMessege.
    1. public async System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> ExecuteAsync(System.Threading.CancellationToken cancellationToken) 
    There is an example of IHttpActionResult which have been used at Authentication Filter level and states that ExecuteAsync just add Header value in response and returns. Please have a quick look at the code shown below.
    1. public class CustomResultChallenge: IHttpActionResult  
    2.   #region IHttpActionResult Members
    3. private readonly IHttpActionResult result; 
    4. private readonly string realm; 
    5. public CustomResultChallenge(IHttpActionResult result, string realm)  
    6.     { 
    7. this.result = result; 
    8. this.realm = realm; 
    9.     } 
    10. public async System.Threading.Tasks.Task < System.Net.Http.HttpResponseMessage > ExecuteAsync(System.Threading.CancellationToken cancellationToken)  
    11.     { 
    12.         var res = await result.ExecuteAsync(cancellationToken); 
    13. if (res.StatusCode == HttpStatusCode.Unauthorized)  
    14.         { 
    15.             res.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Basic", this.realm)); 
    16.         } 
    17. return res; 
    18.     }#endregion 
    Kindly see vital point marked yellow in the below screen shot;
    code
    Press F5 and run you WebApi as depicted below in an image,
    WebApi
    send
    Send the Get request in order to verify the execution cycle as given below. Copy and paste the following Url (http://localhost:57888/api/employees/GetEmp/5) in Postman tool as depicted below in screen shot.
    wrap
    As soon as you click on the send button it reaches to Custom handler one and goes on to next level. Kindly execute the complete HttpMessegePipeline one by one and add your points.
    So far we’ve get into each area of WebApi HttpRequest Pipeline and tried to understand few facts happen during its cycle.
    1. Bullet Points. HttpRequest first converts into HttpRequestMessege.
    2. HttpHandler are type of delegate handler and inject to verify the authenticity and to add some preprocessing logic before it goes further in pipeline. Delegate Handler can be creating on per-route basis. If come error/issue occurs at this level can skip the rest of pipeline.
    3. Authentication filters have been introduced in WebApi2.If come error/issue occurs at this level can skip the rest of pipeline.
    4. Mostly classes are derived from using System.Web.Http.
    5. Model Binders and Value Provides plays an important role in parameter binding as well as the added benefit of FormatterParameterBinding.
    6. WebApi2 gives privilege to return IHttpActionResult from action method of controller. Also supports HttpResponseMessege.
    7. You can manage exception at IHttpAcitonInvoker and at ExceptionFilters also.
    8. This is the final structure of an application given below in screen shot.
      solution
    Hope you would read all contexts and liked it.
    Download Sample Application : Download Sample App & PPT
    Disclaimer
    This is all my understanding about WebApi; I’d be happy if you run this sample application and get a chance to share your opinion.