Thursday, 2 June 2016

41. Angularjs Route resolve

                       Yes, Angular route configuration provides a property is "resolve" which help us to load/redirect once route transactions done successfully.

once studentsList property successfull...then route navigation done. otherwise not happen.


perviously studentcontroller is




now change our controller as


without late...once promise object returned   or resolve (route transactions done) successfully. route is opened.


<!DOCTYPE html>
<html>
<head>
    <title></title>
<meta charset="utf-8" />
    <script src="Scripts/angular.js" ></script>
    <script type="text/javascript">
        var myapp = angular.module('myapp',[]);
        myapp.controller('mycontroller', function ($scope,$http)
        {
            $scope.message = "Hello";
            $scope.Customer = { "CustomerId": "", "CustomerName": "", "CustomerAddress": "" };        
            $scope.getdata = function ()
            {
                $http({ method: "GET", url: "http://localhost:53133/api/Customers/AllCustomers" }).success(function (result) {
                    debugger;
                    $scope.Customers = result;
                });
            }        
            $scope.AddCustomer = function ()
            {
                debugger;
                //$scope.Customer = customer;
                debugger;
                $http(
                    { method: "POST", url: "http://localhost:53133/api/Customers/AddCustomer",data :$scope.Customer }).success(function (result) {
                        debugger;
                        if (result == true)
                        {
                            //   $scope.Customers = result;
                            $scope.getdata();
                            $scope.Customer = { "CustomerId": "", "CustomerName": "", "CustomerAddress": "" };

                        }

                    });

            }
            $scope.GetCustomer = function (customerid)
            {
             
                debugger;
                $http({ method: "GET", url: "http://localhost:53133/api/Customers/GetCustomer?id=" + customerid }).success(function (result)
                {
                    debugger;
                    if (result != null)
                    {
                        $scope.Customer.CustomerId = result.CustomerId;
                        $scope.Customer.CustomerName = result.CustomerName;
                        $scope.Customer.CustomerAddress = result.CustomerAddress;
                    }
                 
                });

            }
            $scope.UpdateCustomer = function (Customer)
            {
                debugger;
                $scope.updatecustomer = Customer;                              
                $http({ method: "PUT", data: $scope.updatecustomer, url: "http://localhost:53133/api/Customers/UpdateCustomer?id="+$scope.updatecustomer.CustomerId }).success(function (result) {
                    debugger;
                    if (result==true)
                    {                                            
                        $scope.getdata();
                        $scope.Customer = { "CustomerId": "", "CustomerName": "", "CustomerAddress": "" };
                    }
                    else
                    {
                        debugger;
                    }
                });
                debugger;
            }
            $scope.getdata();
        });

    </script>
</head>

<body ng-app="myapp">
 
    <div ng-controller="mycontroller">
        {{message}}
        <form id="frm1">
                 <input type="hidden" id="txtCustomerId" ng-model="Customer.CustomerId" />
                <input type="text" id="txtCustomerName" ng-model="Customer.CustomerName" placeholder="Enter Name" />
                <input type="text" id="txtCustomerAddress" ng-model="Customer.CustomerAddress" placeholder="Enter Address" />
                <input type="submit" id="btnCustomer" value="Add Customer" ng-click="AddCustomer()" />
                <input type="submit" id="btnCustomer" value="Add Customer" ng-click="UpdateCustomer(Customer)" />


        </form>
        <table style="border:medium">
            <tr>
                <th>CustomerId</th>
                <th>Customer Name</th>
                <th>Customer Address</th>
            </tr>
            <tr ng-repeat="customer in Customers">
                <td >
                    {{ customer.CustomerId}}
                </td>
                <td>
                    {{customer.CustomerName}}
                </td>

                <td>
                    {{customer.CustomerAddress}}
                </td>
                <td>
                    <a href="#" ng-click="GetCustomer(customer.CustomerId)" >Edit</a>
                </td>
            </tr>

        </table>
    </div>
</body>
</html>

and webapi

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using WebAPICustomerInfo.Models;

namespace WebAPICustomerInfo.Controllers
{
    [RoutePrefix("api/Customers")]
    public class CustomersController : ApiController
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        [Route("AllCustomers")]
        // GET: api/Customers
        public IQueryable<Customer> GetCustomers()
        {
            return db.Customers;
        }

        [Route("GetCustomer")]
        // GET: api/Customers/5
        [ResponseType(typeof(Customer))]
        public IHttpActionResult GetCustomer(int id)
        {
            Customer customer = db.Customers.Find(id);
            if (customer == null)
            {
                return NotFound();
            }

            return Ok(customer);
        }

        [Route("UpdateCustomer")]
        // PUT: api/Customers/5
        [ResponseType(typeof(bool))]
        public IHttpActionResult PutCustomer(int id,Customer customer)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != customer.CustomerId)
            {
                return BadRequest();
            }

            db.Entry(customer).State = EntityState.Modified;
            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CustomerExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Ok(true);        
        }

        [Route("AddCustomer")]
        // POST: api/Customers
        [ResponseType(typeof(bool))]
        public IHttpActionResult PostCustomer(Customer customer)
        {
            ModelState.Remove("CustomerId");
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            db.Customers.Add(customer);
            int i=db.SaveChanges();
            if (i==1)
            {
              // List<Customer> customerslist = db.Customers.ToList();
               return Ok(true);
            }
            else
            {
                return BadRequest();
            }           
        }

        [Route("DeleteCustomer")]
        // DELETE: api/Customers/5
        [ResponseType(typeof(Customer))]
        public IHttpActionResult DeleteCustomer(int id)
        {
            Customer customer = db.Customers.Find(id);
            if (customer == null)
            {
                return NotFound();
            }

            db.Customers.Remove(customer);
            db.SaveChanges();

            return Ok(customer);
        }


        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool CustomerExists(int id)
        {
            return db.Customers.Count(e => e.CustomerId == id) > 0;
        }
    }
}
----------

 public class ClaimsAuthorizeAttribute : AuthorizationFilterAttribute
    {
        public string ClaimType { get; set; }
        public string ClaimValue { get; set; }

        public override Task OnAuthorizationAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
        {
            var principal = actionContext.RequestContext.Principal as ClaimsPrincipal;
            if (!principal.Identity.IsAuthenticated)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                return Task.FromResult<object>(null);
            }

            if (!(principal.HasClaim(x => x.Type == ClaimType && x.Value == ClaimValue)))
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                return Task.FromResult<object>(null);
            }
            //User is Authorized, complete execution
            return Task.FromResult<object>(null);
        }
   
    }
------------------

 public class GenericRepository<C, T> : IGenericRepository<T> where T : class where C : ApplicationDbContext, new()
    {

        private C _entities = new C();
        private ApplicationDbContext e = new ApplicationDbContext();
        private DbSet<T> dbSet;
        public GenericRepository()
        {
            this.dbSet = _entities.Set<T>();
        }
        public C Context
        {
            get { return _entities; }
            set { _entities = value; }
        }

        public int Add(T entity)
        {
            T t = _entities.Set<T>().Add(entity);
            int i = _entities.SaveChanges();
            return i;
        }

        public int Delete(int id)
        {

            T dentity = _entities.Set<T>().Find(id);
            T t = _entities.Set<T>().Remove(dentity);
            int i=_entities.SaveChanges();
            return i;      
        }

        public T Edit(T entity)
        {
            T tentity = _entities.Set<T>().Attach(entity);
            _entities.Entry(tentity).State = System.Data.Entity.EntityState.Modified;      
            _entities.SaveChanges();
            return tentity;
        }

        public DbSet<T> Get(string id)
        {      
            DbSet<T> dbseet=_entities.Set<T>();
            return dbseet;
        }
        public IQueryable<T> GetAll()
        {
            IQueryable<T> query = _entities.Set<T>();
            return query;
        }

        public void Save()
        {
            throw new NotImplementedException();
        }
    }
---------------
 public interface IGenericRepository<T> where T : class
    {
        DbSet<T> Get(string id);
        IQueryable<T> GetAll();
        int Add(T entity);
        int Delete(int id);
        T Edit(T entity);
        void Save();
    }
----

  public GenericRepository<ApplicationDbContext, LossInformation> lossinfocontext;
        public LossinformationController()
        {
            this.lossinfocontext = new GenericRepository<ApplicationDbContext, LossInformation>();
        }  
----
 [TestMethod]
        public void TestMethod1()
        {
            WebApplication2.Controllers.PersonController pc = new                 WebApplication2.Controllers.PersonController();
            IList<Person> testproducts = pc.Get() as List<Person>;
            int k = testproducts.Count;
            Assert.AreEqual(2,k);
        }


http://stackoverflow.com/questions/18924996/logging-request-response-messages-when-using-httpclient

http://perezgb.com/2015/07/02/better-logging-for-web-api-and-mvc/



Install-Package NuGetEnablePackageRestore


40. Angulajs optional parameters

we can define optional params also in route like

step1:


step2:

step3 :


step4:



step5 :




39. Angularjs route change events



   Different events that are triggered when a route change occurs in an angular application.
   Logging the events and event handler properties.

When route change/navigation occurs in angular application

$routeChangeStart
$locationChangeStart
$routeChangeSuccess
$locationChangeSuccess
                           events will be triggered.
now we will learn predefined events($routeChangeStart, $locationChangeStart) in more depth..


use Developer tools to know more all properties of each event parameter(event,next,current).

38. Angularjs : Cancel route change

   Generally a web page has many hyperlinks to navigate to otherpages, by change some time unknowingly click on any other links...it will redirect to respective pages. then that current page data will be lost if we are in middle of something so that if we provide any message to the user about next occured event of the page.

in those cases generally in web. we promt an alert. same mechinasm we will implement using

$route--$routeChangeStart    or        $locationChangeStart events.









             

37. Angularjs difference between $scope && $routeScope


  $scope : is an object available to current controller it's created and it's children in the view.
  $rootScope: is globally accessable to all the controllers. and keep in mind is
  ( $routeScope can be defined     any controller(Home,Students,courese...ect) access by all the controllers).

Example :




36. Angularjs route reload

Instead of reload/refresh entire application(module) for application data of a particular route data then recommend is $route service. Which provide a method called.----reload() which reload only current controller content only. (not entire app data) so that



instead of this 8 requests done by refresh the page. so that we need only one route should reload of entire page. other controllers not required any refreshes.

then define $route service like below to get only students data.



 now i need to call this route only from view(students.html). then 


35. Angularjs : CaseInsensitiveMatch & Inline Templates


              Angularjs provide 2 features( CaseInsensitiveMatch && Inline Templates) which very useful in web application angularjs projects.

CaseInsensitiveMatch

           Bydefault routes which we define in .config() are case-sensitive. when try to access a route using Uppercase or Lowercase which is not exactly defined in $routeProvider. angular will simply ignore this. means angular not handles case sensitive nature.

               so that to handle this we config object has a property is caseInsensitiveMatch : true. 

.when("/courses",
 {
    templateUrl: "Templates/Courses.html",
    controller: "Coursescontroller",
    caseInsensitiveMatchtrue
 })
NOW We can access this route using /course or /COURSES also.

i want provide this caseInsensitiveMatch to entire my config routes then (instead of writing every route like above set caseInsensitiveMatch at route level.

   $routeProvider.caseInsensitiveMatch=true;
   $routeProvider.when(.....);

we any route any case(upper/lower) it works.

InlineTemplates :

   tell now seen templateUrl of $routeProvider is an html file. like bleow  -I & II

            $routeProvider.when("/home",
                                          { templateUrl: "Templates/Home.html", -----I
                                            controller: "Homecontroller",
                                            controllAs: "HomeCtrl"})
                                         .when("/courses",
                                          {
                                              templateUrl: "Templates/Courses.html",------II
                                              controller: "Coursescontroller",
                                              caseInsensitiveMatch: true
                                          })
so content of view coming from sprated html files. there is not rule content of templateUrl should be an html file.

templatUrl  allows to write content of view inline itself also.

$routeProvider.when("/home",
                   {
                     template: "<h2>Inline content not from html file</b></h2>",
                     controller: "Homecontroller"
                })
this time we used template property not templateUrl Property.