Friday, January 19, 2018

Pipes in Angular 2

Pipes used to format data. A pipe takes the data and transforms this input to the desired output.

There are many built-in pipes in Angular 2.

Date Pipes

<div>
    <h4>Date Pipe Example</h4>
    <b>Date format:</b> My joining Date is {{joiningDate | date}}.<br/>
    <b>Specific Date Format:</b> My joining Date is {{joiningDate | date:"dd/MM/yyyy"}}<br/>
</div>

Uppercase Pipe

<div>
    <h4>Upper Case Pipe Example</h4>
    My name is {{name | uppercase}}!
</div>

You can write your own custom pipes. Here's a custom pipe named ExponentialStrengthPipe


import { Pipe, PipeTransform } from '@angular/core';
/*
 * Raise the value exponentially
 * Takes an exponent argument that defaults to 1.
 * Usage:
 *   value | exponentialStrength:exponent
 * Example:
 *   {{ 2 | exponentialStrength:10 }}
 *   formats to: 1024
*/
@Pipe({name: 'exponentialStrength'})
export class ExponentialStrengthPipe implements PipeTransform {
  transform(value: number, exponent: string): number {
    let exp = parseFloat(exponent);
    return Math.pow(value, isNaN(exp) ? 1 : exp);
  }
}

A pipe is a class decorated with pipe metadata.
The pipe class implements the PipeTransform interface's transform method that accepts an input value followed by optional parameters and returns the transformed value.
There will be one additional argument to the transform method for each parameter passed to the pipe. Your pipe has one such parameter: the exponent.
To tell Angular that this is a pipe, you apply the @Pipe decorator, which you import from the core Angular library.
The @Pipe decorator allows you to define the pipe name that you'll use within template expressions. It must be a valid JavaScript identifier. Your pipe's name is exponentialStrength.

And component is

import { Component } from '@angular/core';

@Component({
  selector: 'app-power-booster',
  template: `
    <h2>Power Booster</h2>
    <p>Super power boost: {{2 | exponentialStrength :2: 10}}</p>
  `
})
export class PowerBoosterComponent {

 }

**********************
In your component's template you can use multiple arguments by separating them with colons:

{{ myData | myPipe: 'arg1':'arg2':'arg3'... }}
From your code it will look like this:

new MyPipe().transform(myData, arg1, arg2, arg3)
And in your transform function inside your pipe you can use the arguments like this:

export class MyPipe implements PipeTransform {   
    transform(value:any, arg1:any, arg2:any, arg3:any):any {
}


Passing data from Child to Parent

To pass data from child to parent we use @Output decorator to decorate any property of child component. The property type

must be an event.

Child Component is

import {Component } from '@angular/core'

@Component({
selector :'child-selector',
templateUrl : 'child.component.html'
})
export class ChildComponent
{

@Output() emplName : EventEmitter<string> = new EventEmitter<string>();

onClick()
{

this.emplName.emit("Employee name is Faizan");
}

}

And Child.template.html is

<h2>
I am a nested Component </h2>

<span (click)="onclick()">Click Me</span>


Parnet.component.html is



<h1>I am container</h1>

<child-selector (emplName)='ongetempname($event)'  ></child-selector>

Parent Component class is

import {Component} from '@angular/core'
@Component({
selector :'parent-selector',
templare : 'parent.component.html'
directives :[ChildComponent]})

export class ParentComponent
{
onGetEmpName(message:string):void{
alert("Employe name is " + message);
}

}

Passing Data from Parent To Child Angular 2

Let's First  create a basic component

import {Component } from '@angular/core';

@Component(

selector : 'child-selector',
template : 'child.component.html'
})


export class ChildComponent
{
}

And child.component.html is

<p>
  child.component works! Value get from parent is : {{title}}
</p>



And Parent Component is

import {Component} from '@angular/core';

@Component(
{
selector : 'parent-selector',
template : parent.component.html"
}
)

export class ParentComponent
{

parentTitle:string ="ParentTitle";
}


And parent.component.html is

<p>
  parent.component works!
</p>

<app-child-component [title]="parentTitle"></app-child-component>



Now if you want to pass data from parent to child you have to use @Input decorator in child component as below

export class ChildComponent
{

@Input() title : string;

}

And parent should be like this

import {Component} from '@angular/core'

@Component(

selector : 'parent-selector',
template : 'parent.component.html',
directives : [ChildComponent]

}
)
export class ParentComponent
{

childTitle : String ="This will be passed to child";

}

parent.component.html file is

<p>
  parent.component works!
</p>

<app-child-component [childTitle]="parentTitle"></app-child-component>


Component Angular 2

In Angular 2, “everything is a component.”

In Component we define the behavior of custom dom element.

A Component consists of the following −

Template − This is used to render the view for the application. This contains the HTML that needs to be rendered in the application. This part also includes the binding and directives.

Class − This is like a class defined in any language such as C. This contains properties and methods. This has the code which is used to support the view. It is defined in TypeScript.

Metadata − This has the extra data defined for the Angular class. It is defined with a decorator.

Component is also a type of directive with template,styles and logic part.

Basically there are three types of directives in angular2 according to documentation.

Component
Structural directives
Attribute directives

Example

import { Component } from '@angular/core';

@Component({
  selector: 'my-component',
  template: `
   
Hello my name is {{name}}.

     
   
   `
})
export class MyComponent {
  name: string;
  constructor() {
    this.name = 'Max'
  }
  sayMyName() {
    console.log('My name is', this.name)
  }
}

Thursday, January 18, 2018

What is Race Condition?

A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Because the thread scheduling algorithm can swap between threads at any time, you don't know the order in which the threads will attempt to access the shared data. Therefore, the result of the change in data is dependent on the thread scheduling algorithm, i.e. both threads are "racing" to access/change the data.

Problems often occur when one thread does a "check-then-act" (e.g. "check" if the value is X, then "act" to do something that depends on the value being X) and another thread does something to the value in between the "check" and the "act". E.g:

if (x == 5) // The "Check"
{
   y = x * 2; // The "Act"

   // If another thread changed x in between "if (x == 5)" and "y = x * 2" above,
   // y will not be equal to 10.
}

The point being, y could be 10, or it could be anything, depending on whether another thread changed x in between the check and act. You have no real way of knowing.

In order to prevent race conditions from occurring, you would typically put a lock around the shared data to ensure only one thread can access the data at a time. This would mean something like this:

// Obtain lock for x
if (x == 5)
{
   y = x * 2; // Now, nothing can change x until the lock is released. 
              // Therefore y = 10
}
// release lock for x

Tuesday, January 16, 2018

in Parameter

'in' used to pass read only reference of a variable.

1.Can be used to pass a variable as a reference (value type and reference type both).
2.Only for input not for output.
3."in variable" must be initialized before passing it as a parameter.
4. Can not be decalred inline.
5. It is not necessary to use them in a variabe before leaveing the control.
6. Value type vairable are passed as read only, While reference type variables properties can be change but you can not re-allocate them again.

class Program  
    {  
        static void Main(string[] args)  
        {  
            Product product = new Product();  
            Modify(in product);  
        }  
        public static void Modify(in Product product)  
        {  
            //product = new Product();  // not allowed
            product.ProductId = 101;  
            product.ProductName = "Laptop";  
            product.Price = 60000;  
            WriteLine($"Id: {product.ProductId} Name: {product.ProductName} Price: {product.Price}");  
        }  
    }  
    class Product  
    {  
        public int ProductId { get; set; }  
        public string ProductName { get; set; }  
        public decimal Price { get; set; }  
    }  

Below will give comiple time error because structure is value type and value type variables properties can not be change with in paramtere.

class Program  
    {  
        static void Main(string[] args)  
        {  
            Product product = new Product();  
            Modify(in product);  
        }  
        public static void Modify(in Product product)  
        {  
            //product = new Product();  
            product.ProductId = 101;  
            product.ProductName = "Laptop";  
            product.Price = 60000;  
            WriteLine($"Id: {product.ProductId} Name: {product.ProductName} Price: {product.Price}");  
        }  
    }  
    struct Product  
    {  
        public int ProductId { get; set; }  
        public string ProductName { get; set; }  
        public decimal Price { get; set; }  
    }  

Why we need another keyword 'in'.
The reason is that if we pass a value type variable without reference then each time a new copy will be created. So, it will take extra memory and performance will be slower.

So instead of passing a copy of value type, we can pass a read-only reference of a value type variable which will make it faster and will use less memory.

Source : http://www.c-sharpcorner.com/article/c-sharp-7-2-in-parameter-and-performance/

Friday, January 12, 2018

Action Selectors:

Action selector is the attribute that can be applied to the action methods. It help routing engine to select correct action
nethod.

There are three Action Selectors:
1. ActionName : It allows us to specify a different action name than the method name

[ActionName("find")]
public ActionResult GetByid()
{

}

2. NonAction : It indicates that a public method of a Controller is not an action method.
3. ActionVerbs : The ActionVerbs selector is used when you want to control the selection of an action method based on a Http request method. 

Why MVC is fast

ASP.NET Web Form Problems:

Complexity : HTML and ASP.NET mark up code are used in a Single Page that's why code become very complex.

Tightly Coupled-Aspx page and cs page(code behind file) are tightly coupled.so that we can not work separately.

Unwanted Html and Java Script : When we drag and drop the controls then unwanted html and java script is automatically inserted in our code that's why page become heavier and it takes time to load on browser.

View state-One of the main problems with ASP.NET web forms is the viewstate mechanism, which takes a lot of bandwidth because it serializes all the form inputs and sends it on post commands.

Response Time -for any single events it follows the complete Page Life cycle Events life cycle that's why response time of any ASP.NET application is become more than the MVC application.

Benefits of MVC

Separation of Concerns -In MVC  every part is spearated UI, Business Logic , Model. Clean separation of UI.

More Control-The ASP.NET MVC framework provides more control over the HTML , JavaScript and CSS than the traditional Web Forms.

Testability- Is it testabel using unit test cases, wile ASP .Net was not.

Lightweight-ASP.NET MVC framework doesn’t use View State and thus reduces the bandwidth of the requests to an extent.

Full features of ASP.NET-One of the key advantages of using ASP.NET MVC is that it is built on top of ASP.NET framework and hence most of the features of the ASP.NET like membership providers , roles etc can still be used.

.  SEO friendly URL by design (though now this is possible in ASP.NET 4 as well)

-  Session, JS, Ajax works.  Validation is even more powerful with DataAnnotations and jquery.
-Business logic is stored in a single state called model where in traditional asp.net platform, each page has its own business logic making it complex.

--View based solution for Action based requirement
--HTML is not the only response type

Because of the tight coupling between view and code behind even the response type is fixed in webform , its by default HTML. If you wish to change it you need to play around with Content-type and “Response.End” methods etc which is quiet tedious.

If we create “Action” first structure then the action has all the luxury in the world to decide what kind of response type should go out. This makes our system more flexible in terms of same action with different outputs.

 FlexibleCombination of view and data

Making behind code a normal class for unit testing


Wednesday, January 10, 2018

What is .axd files

The AXD files are used by various ASP.NET applications to handle embedded resource requests.

The AXD files are trace handler files that provide instructions to the associated application for the retrieval of embedded resources such as JavaScript files, CSS files and images. They are commonly used to manage website administration requests. These handlers can be built into an application or custom created for a user.

Source : https://file.org/extension/axd

Attribute Based Routing

There are two types of routing (introduced in ASP.NET MVC 5).

Convention based routing - using MapRoute
Attribute based routing - Specify the route on each action method.

routes.MapRoute(
   name: "MyCustomRoute",
   url: "CustomController/{action}/{id}",
   defaults: new { action = "Index", id = UrlParameter.Optional }
 );

It will call CustomController and specified action method.


Attribute Based Routing :

Attribute Routing (introduced in MVC 5) is the ability to add routes to the Route Table via attributes so that the route definitions are in close proximity to their corresponding actions. We will still populate the Route Table, but we will do it in a different manner.

To enable attribute routing, we need to use MapMvcAttributeRoutes() in the RouteConfig

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapMvcAttributeRoutes(); //Enables Attribute Routing
    }
}

Example

public class HomeController : Controller
{
[Route("Users/Index")] //Route: /Users/Index
    public ActionResult Index() { ... }
}

What that [Route] attribute does is specify a route to be added to the Route Table which maps to this action.

Comman Route Prefix with Attribute Routing


To make your url neat, clear and user friendly, we can define the prefix in URL after domain name. We can use RoutePrefix attribute to define the prefix.

[RoutePrefix("Articles")]  
public class ArticleController: Controller  
{  
    [Route("{id}")] //Route: /Articles/13  
    public ActionResult Details(int id)  
        {  
            //other code goes here  
        }  
        [Route("{username}")] //Route: /Articles/mukeshkumar  
    public ActionResult MyArticleDetails(string username)  
    {  
        //other code goes here  
    }  
}  

Override the common route prefix with Attribute Routing


Sometimes, it is required to show different prefix in url with particular action. If you have already defined the Prefix for the whole controller then you can override it. To override the RoutePrefix, use ~ sign with prefix name with particular action in the Route attribute.

[RoutePrefix("Articles")]  
public class ArticleController: Controller  
{  
    [Route("~/ArticleList/{id}")] //Route: /ArticleList/13  
    public ActionResult Details(int id)  
    {  
        //other code goes here  
    }  
}  

Route Constraints with Attribute Routing


When we use Route Constraints with Route attribute, it basically restrict or force how parameters will match.

public class ArticleController: Controller  
{  
    [Route("Articles/{id:int}")] //Route: /Articles/13  
    public ActionResult Details(int id)  
        {  
            //other code goes here  
        }  
        [Route("Articles/{username}")] //Route: /Articles/mukeshkumar  
    public ActionResult GetUserDetails(string username)  
    {  
        //other code goes here  
    }  
}  

Attribute Routing in Area of ASP.NET MVC


In we are using Area in ASP.NET MVC project and want to use attribute routing, we need to use RouteArea attribute to define the area name and all will be same.

[RouteArea("Admin")]  
[RoutePrefix("Home")]  
[Route("{action}")]  
public class HomeController: Controller  
{  
    // route: /Admin/Home/Index  
    public ActionResult Index()  
        {  
            return View();  
        }  
        // route: /Admin/Home/Employees  
        [Route("employees")]  
    public ActionResult GetEmployees()  
        {  
            return View();  
        }  
        // route: /department  
        [Route("~/Department")]  
    public ActionResult Departments()  
    {  
        return View();  
    }  
}  

Name attribute

As we use Custom Routing in ASP.NET MVC. We can achieve Custom Routing to define the Name of Route and use this route on the basis of Route name.

[Route("Articles", Name = "MyArticle")]  
 public ActionResult GetAllArticle()  
 {  
 }  
<a href="@Url.RouteUrl("MyArticle ")">My Article</a>

In the above code, if you pass integer value as parameter after “Articles/” then it will hit to first route otherwise second.

Hackable URLs

One of the things Routing allows us to do is to create "hackable" URLs; that is, URLs whose meaning is easily read, understood, and extended upon by human beings. We can use Routing to turn this messy URL:

www.example.com/article.aspx?id=69&title=my-favorite-podcasts

into a much cleaner one:

www.example.com/articles/69/my-favorite-podcasts

The concept of "hackable" URLs goes a bit further, too. If I was a user looking at the clean URL, I might append "/comments" on the end of it:

www.example.com/articles/69/my-favorite-podcasts/comments

"Hackable" URLs implies that this should display the comments for that article. If it does, then I (the user) have just discovered how I can view the comments for any given article, without needing to scroll through the page and hunt down the appropriate link.

Source : https://exceptionnotfound.net/attribute-routing-vs-convention-routing/

Different types of Convention based Routing in ASP.NET MVC

1. Using Static URL segments in Routing


In routing, we can also specify a static segments and remaining as dynamically passed variable.
Fo this url http://localhost:63087/CustomController/Index

Index method of CustomController will be called.

 routes.MapRoute ("Admin","Admin/{action}",
      new {controller="Home"});

For above if request is /Admin/Index than home controller will be called with specified action.

2. Defining variable length routing


This type of routing is used to accept any number of url arguments and popularly known as CatchAll scenario where any data after specific segments are caught.

routes.MapRoute("CatchAll", "{controller}/{action}/{id}/{*catchall}",
     new { controller = "RoutingStuffs", action = "CatchAll", id = UrlParameter.Optional });

In the above code, after id segments we have {*catchall} that catches all segments of data after id like below

http://localhost:63087/RoutingStuffs/CatchAll/50/Delete/And/Other/Parameter -
In this case controller is RoutingStuffs, action method is CatchAll, id is 50 and remaining url segments comes under catchall.

The CatchAll action method of the RoutingStuffs controller should be defined like this

public ActionResult CatchAll(string id = null, string catchall = null)
        {
            return View();
        }

Here, we get the catchall parameter value = "Delete/And/Other/Parameter".


3. Prioritizing controller by Namespaces in Routing

In case we have more than one controller with the same name in different namesapce, as a result it throws below error.

Multiple types were found that match the controller name RoutingStuffs. This can happen if the route that services this request ...... does not specify namespaces to search for a controler that match the request. If this is the ase, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.

To overcome this issue,  we can specify namespace

routes.MapRoute("CatchAllPriorityHome", "Home/Route/{controller}/{action}/{id}/{*catchall}",
      new { controller = "RoutingStuffs", action = "CatchAll", id = UrlParameter.Optional },
      new[] { "MVCTraining5.Controllers" });

 routes.MapRoute("CatchAllPriority", "Route/{controller}/{action}/{id}/{*catchall}",
      new { controller = "RoutingStuffs", action = "CatchAll", id = UrlParameter.Optional },
      new[] { "MVCTraining5.Controllers.OtherFolder" });

In above code snippet, the first MapRoute method specify if the url starts with "Home/Route/....." then go for RoutingStuffs controller that is in the MVCTraining5.Controllers namespace, if not found then look for other namespaces.

The second MapRoute method specify that if the url starts with "/Route/........" then go for the RoutingStuffs controller that is in the MVCTraining5.Controllers.OtherFolder namespace.

4. Constraining Routes using Regular Expression or Hard coded values

We can also constraint the routes by specifying the Regular Expression for controller, action method etc.

routes.MapRoute("ConstrainRouteRA", "{controller}/{action}/{id}/{*catchall}",
   new { controller = "RoutingStuffs", action = "Index", id = UrlParameter.Optional },
   new { controller = "^R.*", action = "^Index$|^About$" });

Above route will be applicable to only those request whose controller starts with "R" or action method is either Index or About.

routes.MapRoute("ConstraintRouteHttp", "{controller}/{action}/{id}/{*catchall}",
  new { controller = "RoutingStuffs", action = "Index", id = UrlParameter.Optional },
  httpMethod = new HttpMethodConstraint("GET", "POST") });

Above route will be applicable to only those request whose controller name is RoutingStuffs, and request type is either "GET" or "POST".

routes.MapRoute("ConstraintRouteRange", "{controller}/{action}/{id}/{*catchall}",
  new { controller = "RoutingStuffs", action = "Index", id = UrlParameter.Optional },
  new
      {       
        id = new RangeRouteConstraint(10, 20)
     });

It is applicable if id is in between 10 and 20.

Note, that RangeRouteContraint and other value constraints are supported only in ASP.NET MVC 5+.

Similar to RangeRouteContraint, there are few more value constraints
BoolRouteConstraint - checks for value that can be parsed as boolean
DateTimeRouteConstraint - checks for value that can be parsed as date and time
AlphaRouteConstraint - checks for alphabets character either upper or lower case
IntRouteConstraint - checks for value that can be parsed as integer
MaxLengthRouteConstraint & MinLengthRouteConstraint - checks for maximum and minimum length of the characters

5. Custom constraint route in ASP.NET MVC


Think about a scenario, where a particular feature or style of your app doesn't work in Google chrome but works in all other browser like Internet Explorer and FireFox. In this case we can use custom constraint routing.

To define a custom constraint, we need to create a class file that looks something like

using System.Web;
using System.Web.Routing;

namespace MVCTraining5.Utility
{
    public class BrowserDetectConstraint : IRouteConstraint
    {
        string _userAgent = string.Empty;

        public BrowserDetectConstraint(string userAgent)
        {
            _userAgent = userAgent;
        }

        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            return httpContext.Request.UserAgent != null
                && httpContext.Request.UserAgent.Contains(_userAgent);
        }
    }
}

When we inherit this class file with IRouteConstraint, we have to implement Match method. Here at the instantiation of the class we are passing the user agent to check, the same is being matched and returns true/false in the Match method.

The above custom constraint can be used like below

routes.MapRoute("ConstraintCustomChrome", "{controller}/{action}/{id}/{*catchall}",
  new { controller = "RoutingStuffs", action = "Index", id = UrlParameter.Optional },
  new
     {
       customConstraint = new Utility.BrowserDetectConstraint("Chrome")
     }, new[] { "MVCTraining5.Controllers.OtherFolder" });

routes.MapRoute("ConstraintCustom", "{controller}/{action}/{id}/{*catchall}",
  new { controller = "RoutingStuffs", action = "Index", id = UrlParameter.Optional }
  , new[] { "MVCTraining5.Controllers" });

The first MapRouote method of the above code use BrowserDetectConstraint by passing Chrome as user agent parameter. If the request comes with this user agent (i.e, from Google Chrome browser), RoutingStuffs controller from MVCTraining5.Controllers.OtherFolder is called otherwise second MapRoute executes and call the RoutingStuffs controller from MVCTraining5.Controllers namespace.

Some Key Points

1.  Controller value is required in default. If no controller defined within than project will compile but show error on view : controller is required.

2. In case of static url segment (If no controller is enclosed in in braces) it match the pattern only, if matches take the controller value from default.



Source : http://www.dotnetfunda.com/articles/show/3029/different-types-of-routing-in-aspnet-mvc

Tuesday, January 9, 2018

Routing in ASP.Net MVC

ASP.Net MVC routing is a pattern matching system whihc is responsible for mapping incoming browser request to specific MVC controller actions.

When ASP .Net appliation launches then the application register one or more patterns with the framework route table to inform the routing engine what to do with the request that matches those patern. When the routing engine receives a request at runtime, it matches the request URL with the URL pattern registered with it and gives the response accordingly.

ASP .Net routing is setup in two places.

First in Web Config file : There are four section related to it (system.web.httpModules,system.web.httpHandlers,system.webserver.modules and system.webserver.handlers)

Second in Global.asax file : Here route table is created and RegisterRoutes method called

  protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
        }

When the request URL matches any registered route pattern in the route table then the routing engine forward the request to appropriate handler for the request, Thereafter the route is processed and gets a view on the UI. Otherwise 04 HTTP status code returned.

Properties of Route:

Route Name : A name unique give to that route.

Url :  Where Url pattern is define like {controller}/{action}/{id}

defaults: You can assign default value for paramtere controller,action and id

Constraints : A set of constraints to apply against the URL pattern.

When Launches the application first of all Application_Start event handler call the RegisterRoutes() method from RouteConfig class. It has a parameter called route which is a Collection of routes that contains all the registered routes in the application.

 public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  routes.MapRoute(
            name: "Student",
            url: "students/{id}",
            defaults: new { controller = "Student", action = "Index"}
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
        }

Monday, January 8, 2018

Angular 2

What is the lifecycle hooks in Angular 2?

What are the component in Angular 2?

How do You inject series in component?

How do You pass values from child to parent (vice-versa)?

How many pipes in Angular 2?
Ans :
https://angular.io/guide/pipes Features of Angular 2?

Implementation in Angular 2?

Code of component ?

How to show data from component to view

difference between observable and promises

subcribe , map and subject

NgModule 

where to do configuration for angular 2

is angular 2 will run without typescript
Ans : Yes.

https://medium.com/@areai51/angular-2-without-node-and-typescript-f80cfc853904

interpolation

data binding in angular 2

how to send data from parent to child  vice versa

pipes in angular 2

is constructor in component is the part of life cycle.

MVC

What is routing?
What are Filters in MVC?
Difference between Keep and Peek.

Shared By Noor

Modules in Angular

Modules is a mechanism to group components,directives,pipes and services which are related. An angular application can be thought as a puzzle where piece or module is complete in itself.
Modules are classes where we can hide or show directives,pipes and services to outer world using export keyword.
Ex. Using NgModule decorator we can create module





+


import { NgModule } from '@angular/core';

@NgModule({
  imports: [ ... ],
  declarations: [ ... ],
  bootstrap: [ ... ]
})
export class AppModule { }
Property import expect an array of modules.

Property declarations expects an array of components, directives and pipes that are part of module.

Property bootstrap expects an array of component genrally we define here root component.

Example of app.module

import {NgMdule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {AppCompnonent} ./app-component'


@NgModule(
{
imports :[BrowserModule]
declarations:[AppComponent]
bootstrap:[AppComponent]
}
)
export class AppModule
{

}

Here our module is importing BrowserModule, which indicate that app-module is root module.
BrowserNModule is built-in module that imports basic directives,pipes and services. In angular Js we we have to explicitly imports those dependencies. to use *ngFor and *ngIf.

Here AppComponent is root component that's why it is given in bootstrap. Because in declarations we have to define all component that's why we have to define it again in declaration.

There are two types of modules. Root module and feature module.In an angular application there is one root module and others are feature module.

By convention, the root module should always be named AppModule.

Bootstrapping an Application

To bootstrap and angualr application, we need to inform Angular which one is our root module to perform the compilation in browser. This compilation is known as "Just in Time" compilation.

main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';

platformBrowserDynamic().bootstrapModule(AppModule);

It is also possible to perform the compilation as a build step of our workflow. This method is called "Ahead of Time" (AOT) compilation and will require a slightly different bootstrap process


Sunday, January 7, 2018

Filters in MVC

MVC Filters are used to execute custom logic before or after executing action method.
MVC Filter types:
Authorization filters
Action filters
Result filters
Exception filters
Filters can be applied globally in FilterConfig class, at controller level or action method level.
Custom filter class can be created by implementing FilterAttribute class and corresponding interface.


Authorization filters : Perform authentication and authorizes before executing action method.
Build-in filter are [Authorize],[RequireHttps] and interface is IAuthorizationFilter. IAuthorization contains one method OnAuthorization

Action filters : Perform some operation before and after the action method. Interface name is IActionFilter. Example : View Data Modification, OutputCache is an ex of Action Filter.

IAction Filter contains two methods
OnActionExecuting - Runs before execution of Action method.
OnActionExecuted - Runs after execution of Action method.

Result Filter : Perform some operation before or after the execution of View result. Built-in filter is [OutputCache]
and interface is IResultFilter.

IResultFilter contains two methods

OnResultExecuting - Runs before content is rendered to View.
OnResultExecuted - Runs after content is rendered to view.

Excepton Filter : Perform some operation if there is an unhandled exception
thrown during the execution of the ASP .net MVC pipleine. Built-i filter is [HandleError] and interface is IExceptionFilter.


IExceptionFilter contains one method

OnException

An exception filter execute when there is an unhandled exception occurs in application.
HandleErrorAtribute([HandleError]) class is a built-is exception filter class.It renders Error.cshtml
included in Shared.

Please make sure that CustomError mode is on in System.web section of web.config, in order for HandleErrorAttribute work properly.

<customErrors mode="On" />

Some built-in filter

AuthorizeAttribute. Restricts access by authentication and optionally authorization.
HandleErrorAttribute. Specifies how to handle an exception that is thrown by an action method.
OutputCacheAttribute. Provides output caching.
RequireHttpsAttribute. Forces unsecured HTTP requests to be resent over HTTPS.

Register Filters
Filters can be applied at three level.

Global Level : In Application_Start event by using
default FilterConfig.RegisterGlobalFilters() method.

Global filters will be applied to all the controller and action methods of an application.

The [HandleError] filter is applied globaly in MVC Application by default in every MVC application created using Visual Studio as shown below.
of Global.asax by using default

// MvcApplication class contains in Global.asax.cs file 
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    }
}

// FilterConfig.cs located in App_Start folder 
public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }
}

2. Controller level

Filters can also be applied to the controller class. So, filters will be applicable to all the action method of Controller class if it is applied to a controller class.

[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

}

3. Action method level:

You can apply filters to an individual action method also.

public class HomeController : Controller
{
    [HandleError]
    public ActionResult Index()
    {
        return View();
    }

}

The same way, you can apply multiple built-in or custom filters globally or at controller or action method level for different purpose such as [Authorize],[RequireHttps], [ChildActionOnly],[OutputCache],[HandleError].

Filter Order:
As mentioned above, MVC includes different types of filters and multiple filters can be applied to a single controller class or action method. So, filters run in the following order.

Authorization filters
Action filters
Response filters
Exception filters

Create Custom Filter:
You can create custom filter attributes by implementing an appropriate filter interface for which you want to create a custom filter and also derive a FilterAttribute class so that you can use that class as an attribute.

For example, implement IExceptionFilter and FilterAttribute class to create custom exception filter. In the same way implement an IAuthorizatinFilter interface and FilterAttribute class to create a custom authorization filter.

class MyErrorHandler : FilterAttribute, IExceptionFilter
{
    public override void IExceptionFilter.OnException(ExceptionContext filterContext)
    {
        Log(filterContext.Exception);

        base.OnException(filterContext);
    }

    private void Log(Exception exception)
    {
        //log exception here..

    }
}

Alternatively, you can also derive a built-in filter class and override an appropriate method to extend the functionality of built-in filters.

class MyErrorHandler : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        Log(filterContext.Exception);

        base.OnException(filterContext);
    }

    private void Log(Exception exception)
    {
        //log exception here..

    }
}

Canceling Filter Execution

You can cancel filter execution in the OnActionExecuting and OnResultExecuting methods by setting the Result property to a non-null value.

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    //Check your condition here
    if (true)
    {
        //Create your result , cancel here
        filterContext.Result = new EmptyResult();
    }
    else
        base.OnActionExecuting(filterContext);
}

Overload in Depth


using System;

class Test
{
    static void Foo(int x)
    {
        Console.WriteLine("Foo(int x)");
    }

    static void Foo(double y)
    {
        Console.WriteLine("Foo(double y)");
    }
    
    static void Main()
    {
        Foo(10);
    }
}

This is absolutly fine and Foo(int x) will be printed. If we remove the first method than method of double will be called.
Here compiler decides which conversion is better so in this case int to int is better than int to double.
So fist method wins.

Second case


using System;

class Test
{
    static void Foo(int x, int y)
    {
        Console.WriteLine("Foo(int x, int y)");
    }

    static void Foo(int x, double y)
    {
        Console.WriteLine("Foo(int x, double y)");
    }

    static void Foo(double x, int y)
    {
        Console.WriteLine("Foo(double x, int y)");
    }
    
    static void Main()
    {
        Foo(5, 10);
    }
}

Here first method will win since it  beat second method on second parameter and third method on first
parameter.


Third case

using System;

class Test
{
    static void Foo(int x, double y)
    {
        Console.WriteLine("Foo(int x, double y)");
    }

    static void Foo(double x, int y)
    {
        Console.WriteLine("Foo(double x, int y)");
    }
    
    static void Main()
    {
        Foo(5, 10);
    }
}

Here no method wins outright, the compiler will report an error:
Error:
error CS0121: The call is ambiguous between the following methods or
properties: 'Test.Foo(int, double)' and 'Test.Foo(double, int)'

Difference Between Keep and Peek

Temp data persist the value for next request depending on following condition

1. Normal Read
2. Not Read
3. Read and Keep
4. Peek and Read


If you have read the data from TempData inside view or any other class than data will be deleted.

stringstr = TempData["MyData"];

Even if you are displaying the data it is also normal read
@TempData["MyData"];

2.If data not read than it will available until next next request.

3. If you read the data and called Keep method than data will be persisted.

@TempData["MyData"];
TempData.Keep("MyData");

4. You have read the data using Peek method than data will be read and persisted
stringstr = TempData.Peek("Td").ToString()


So the difference between keep and peek is keep force to persisted the data but not read the data. While
Peek read the data and persisted it for next request.

Saturday, January 6, 2018

Java Script

1. Datatypes are defined at runtime in javascript.

var x= "str";

console.log(typeof x) //Output String

s=10;

console.log(typeof x) //Output int

2. There are three primitive types in javascript

1. string
2. boolean
3. number

float number is also consider as number.

3. If a variable is not defined anywhere only assigned a value inside function it is assume global by default and it can be accessed outside function

function F1()
{
    x=9;
}

F1();
alert(x);

4. According to point 3 it can create problem so avoid this we use 'use strict'. By using this line we can not use a variable without defining it.

'use strict'
function F1()
{
    x=9;
}

F1();

alert(x);

This will give error. 'x' is not defined.  So in this way  x can not be used without defining it so while we define it, it will be local. So can not be used outside F1.

5. In java script declaration is pulled up.

alert(x);
var x=10;

it will run and  give message undefined.

alert(x);

Though above code will run so no message will appear. And error will be there.
Null reference error.

6. Immediate invoking function

(function()
{
alert("hi");
}());

Closure in Javascript

Closure are function inside function.  They help to create isolated stateful function.
var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();

add();
add();
add();

The variable add is assigned the return value of a self-invoking function.

The self-invoking function only runs once. It sets the counter to zero (0), and returns a function expression.

This way add becomes a function. The "wonderful" part is that it can access the counter in the parent scope.

This is called a JavaScript closure. It makes it possible for a function to have "private" variables.

The counter is protected by the scope of the anonymous function, and can only be changed using the add function.


A closure is a function having access to the parent scope, even after the parent function has closed.


And help to access private variable of a function.

Followers

Link