Wednesday, June 28, 2017

Few Interesting facts of Attribute routing

We of us know that Attribute Routing has introduced to enhance flexibility of routing in ASP.NET MVC. So, here is my ItemController which marked as “Item” using routeprefix attribute and GetItem(int Id) action is decorated using Route attribute. So, to invoke 
GetItem, the route is “/Item/1” 

    [RoutePrefix("Item")]
    public class ItemController : Controller
    {

        [Route("{id}")]
        public void GetItem(int Id)
        {

        }
    }

Now, let’s think some situation where we want to override behavior of RoutePrefix. We have defined GetItemInfo() action with Route attribute prefixed by “~/” which implies that we need to specify “Item” to invoke the action. So, the route to access GetItemInfo() is
      
    [RoutePrefix("Item")]
    public class ItemController : Controller
    {

        [Route("~/SpecialItem/{id}")]
        public void GetItemInfo(int Id)
        {

        }
    }

Set Global Default Route

We know that, in time of route initialization in config file we can specify default route. Here is another way to implement same. Just specify “~/” in any action to mark the action as default action.

So Route to access GetItemInfo() is : /

    [RoutePrefix("Item")]
    public class ItemController : Controller
    {
        [Route("~/")]
        public void GetItemInfo()
        {

        }
    }


Now, What if we mark more than one action as default action? You will experience following exception.


Set Default route to specific RoutePrefix

If we place Empty string(“”) to some action, it will mark as default route for that RoutePrefix. So, In following example GetItemInfo() is default route under “Item” RoutePrefix.

So, to Invoke GetItemInfo() the route is “/Item”

    [RoutePrefix("Item")]
    public class ItemController : Controller
    {
        [Route("")]
        public void GetItemInfo()
        {

        }
    }

Here is another way to set default route. 

  RoutePrefix("Item")]
  [Route("{action=GetItemInfo}")]
    public class ItemController : Controller
    {
        public void GetItemInfo()
        {
        }
    }

Route matching by pattern

Using attribute routing, we can pick route by pattern. Now, all routes ended with “info” suffix will map to GetItemInfo() action. So, one sample route could be “/Item/anyinfo”

[RoutePrefix("Item")]
   
    public class ItemController : Controller
    {
        [Route("{*info}")]
        public void GetItemInfo()
        {

        }
    }

Set priority to route

We know that if there are multiple action mapping to same route, we will get exception. To get rid of from this situation, we can specify “Order”. In following example we specified Order in “Route” attribute to action. The route “Item/get/id” is mapping to both GetItemInfo() and GetAnotherItemInfo().

public class ItemController : Controller
    {
        [Route("get/{id}", Order =0)]
        public void GetItemInfo(int Id)
        {

        }

        [Route("get/{id}", Order = 1)]
        public void GetAnotherItemInfo(int Id)
        {

        }

    }

If we do not specify “Order” it will throw this exception.


MVC, register low order route value at first, we Once we go with “item/get/1” it will hit GetItemInfo() action.




Sunday, April 2, 2017

Evolution of AJAX World


If you have started you carrier around 7-10 years back as web developer then probably you have experienced the evaluation practically.

Because of huge advantage of AJAX, more or less 70-80 % of modern web application has adapted this technology. The new style of AJAX implementation came in market so quickly that it’s sometime hard to remember what things were before that?

Anyway, Long ago, Netscape added a feature in browser called live script which was capable to give flavor of offline processing like form validation in client side and bit more. Slowly Live script became JavaScript with more functionality and flexibility.

The inception of DynamicHTML has started in development world, slowly XML gain its popularity in AJAX world when Microsoft added a small function in IE5 to perform XMLHttpRequest call to server.

The classic AJAX using XMLHttpRequest

This is classic style to make AJAX call using vanilla JavaScript. If you worked in very old ASP, JSP or PHP application, probably you are familiar with this style of AJAX call.

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // Typical action to be performed when the document is ready:
       document.getElementById("demo").innerHTML = xhttp.responseText;
    }
};
xhttp.open("GET", "yourfilename.extension", true);
xhttp.send();

Oh, did I miss something? Yes, we need to detect browser prior to AJAX call, Just to make sure we are using proper XMLHttpRequest object. Yes, XMLHttpRequest object is browser specific.

JQuery changed the whole game

Then JQuery came in market, it played major role to change face of client side app development.  It combine and packed the above code into few lines and introduce the concept of Callback.

$.ajax({url: "yoururl.com", success: function(result){
        //enjoy with result variable
    }});

And that’s all, simple, compact, no code smell and maintainable. Now, in mean time other library too started wrapping classic XMLHttpRequest request using very similar syntax.

So, as a result the concept of callback has introduced in development world. The moto of callback is, call me once you have prepared the result, or call error in mess!.

Let’s return promise rather than actual result

People started to realize that, as it is asynchronous call, it should return something by which we can take decision. Let’s give some example. The below code is based on promise and then callback function.

requestSomeData("http://example.com ") // returns a promise for the response

    .then(function(response){ // ‘then’ is used to provide a promise handler
    
    return JSON.parse(response.body); // parse the body
    
   }) // returns a promise for the parsed body

    .then(function(data){
   
    return data.something; // get the price

   }) // returns a promise for the price

    .then(function(price){ // print out the price when it is fulfilled

        //do something with the data

  });

We can consider this as fully asynchronous execution plan, even if my JSON.parse() take huge time, the execution flow will not hang the thread because I have attached then callback to ensure that someone will take care once parse completed.

Angular and Other library utilize it best

Angular 1.X introduced a way to sync all asyn call using “$q” service. This is huge power to developer to process more than one asynchronous call and print consolidated result.

Want to have more control on AJAX call? Use Observable.

RxJs introduced the concept called Observable to have more grip on AJAX call. Let’s think that we need to cancel an AJAX call in middle. Assume, the situation where need to handle multiple AJAX call. Observable is preferred than promise here.

So, an observable is like a stream and allow to pass zero or more events where the callback is called for each event. The Observable covers more including promise.
For more info, please check Observable in Angular2

    









Saturday, April 1, 2017

Learning Angular2 ? Here you map yourself !


What is new in angular2?
               Let's see, do I really need to learn!


Advantages of angular2
               If there, industry will adapt quickly and I have to spend some amount of time to learn. Good advantages are bad news for "coder by incident" Engineer :)


Does typescript really need in angular2?
               It could be gossip, let's check reality. Oh!! People are recommending to use typescript, so I have to learn it.


Setting up typescript environment and start Hello World (before that bit struggle with NPM)
               All YouTube tutorial are using Visual Studio Code, but I want to setup in my Visual Studio Enterprise edition :)


Let’s setup angular2 in Visual Studio
               Spent good amount of time in old angular2 website of Google. Setting up typings.js, common.js, tsconfig.js etc finally with webpack, no idea! What is happening! Confused!!



Try angular2 cli or inbuilt project template with ASP.NET Core 1.0
               Feel that ASP.NET Core 1.0 template is best solution, almost 0 setup and production ready architecture :)


Learn architecture of angular2
               Let’s hands on by writing baby component and understand architecture. Learn data binding, routing, Template, directory bla bla...


Dependency injection in angular2
               Oh.. Not much change with angular 1.X, easy to pick up if u know 1.x


Now, let's implement in memory CRUD/TODO app. And here I am...


Tuesday, November 29, 2016

Work with service in Angular2

Conceptually service is independent snippet of code which contains certain functionality or business logic. In Angular2 service is nothing but class of typescript (If we use typescript) which we can inject to component or module.

Yes, we can inject service to both component and module level. In this example we will demonstrate same.

If you are new in Angular2 , I will recommend to go through my previous article to setup angular2 project in IDE.


So, let’s start to implement one simple service which will return list of Person Object.
Add app.dataService.ts file in app folder. Here is content of file.

import {Injectable} from "@angular/core";
export interface Person {
    name: string
}

@Injectable()
export class dataService{
   
    getPerson(): Person[]
    {
        return [
            { name: "Ram" },
            { name: "Syam" },
            { name: "Jodu" }
        ];
    }
}

Here Person interface is type which we are returning from getPerson() function. Please note that the @Injectable decorator is needed when we want to inject to some other unit of code.

Inject service to component

As we said, service can be injectable both to component and module. Here we will inject service to component. Here we have created PersonComponent where we are injecting service in provider section.

import {Component} from '@angular/core';
import {dataService ,Person } from './app.dataservice'
import {OnInit} from "@angular/core";

@Component({
    selector: 'person',
    template: `<ul>
    <li *ngFor="let p of _persons">{{p.name}}</li>
    </ul>`,
    providers: [dataService],
})
export class PersonComponent {

    public _persons: Person[];
    constructor(private _dataService: dataService)
    {
        this._persons = this._dataService.getPerson();
    }

}


In constructor we are consuming getPerson() function which populating _Person member. Now, let’s create a view to display the component. Here is our sample view.

<!DOCTYPE html>
<html>

<head lang="en">
    <base href="/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>
   
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>

    <!-- Configure SystemJS -->
    <script src="systemjs.config.js"></script>
   
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
</head>

<body>
    <person>Loading App...</person>

</body>
</html>


Once we run the application ,we will see that data is showing like this.



Inject service in module

Now, let’s see how we can inject service to module. Here mainModule of application where we are injecting service in provider section.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { PersonComponent } from './app.main_component';
import { dataService} from './app.dataservice';

@NgModule({
    imports: [BrowserModule ],
    declarations: [PersonComponent],
    bootstrap: [PersonComponent],
    providers: [dataService]
})
export class mainModule
{

};

Now, we can use the service in PersonComponent without inject it.

import {Component} from '@angular/core';
import {dataService, Person } from './app.dataservice'
import {OnInit} from "@angular/core";

@Component({
    selector: 'person',
    template: `<ul>
    <li *ngFor="let p of _persons">{{p.name}}</li>
    </ul>`
})
export class PersonComponent {

    public _persons: Person[];
    constructor(private _dataService: dataService) {

        this._persons = this._dataService.getPerson();
        console.log(JSON.stringify(this._persons));

    }

}

Monday, November 28, 2016

Main and Feature module in Angular2

We can assume Module as root node in angular2 application. A module may contains components (one or more), pipes, services which is logically related to some module. For example, if we create login module then probably login component, sign in component, logout component will be child of login module. So we can say that those component will hook up with login module. Again, those component may use login service, logout service etc. which again logically related to login functionality and can be inject to login module.

 Point to be noted that each angular2 application should have at least one module which will load in bootstrap to startup the application. We can call the module as main module.
The application may contains many sub module to support business functionality and those module could be call as feature module.

The feature module will attach to main module so that it will be accessible in application. To make available one module to other module we have to export it. The consumer module have to import same to consume it.

In this small example we will learn to attach one feature module to main module. I am assuming that you have Angular2 setup in your editor. If not please follow my previous article for step to step guide of angular setup.


Now, follow the steps to implement same.

The entire folder structure will be like this.


Step1) Create main component.

Create “app.main_component.ts” file under app folder of application.


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


@Component({
    selector: 'welcome',
    template: `<p>{{message}}</p> <login></login>`
})
export class welcomeComponent {
    private message: string;
    constructor() {
        this.message = "Welcome to app."
    }
}

Just notice that we have used “<login></login>” element in template section which is defined in our feature module which we will implement in steps.

Step2) Create main module.

Add main.ts under app folder in application and here is implementation.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { welcomeComponent } from './app.main_component';
import {loginModule} from './app.login_module';

@NgModule({
    imports: [BrowserModule , loginModule],
    declarations: [welcomeComponent],
    bootstrap: [welcomeComponent]
})
export class mainModule
{

};

Just notice that we have imported our feature module called “loginModule” in imports section of main module. The loginModule we will define in short.

Step 3) Setup main module for bootstrap.

Here is code to setup mainModule in bootstrap method. So mainModule will trigger when application will load first time. The file name is “main.ts”

import {platformBrowserDynamic}    from '@angular/platform-browser-dynamic';
import {mainModule} from './app.main_module';
platformBrowserDynamic().bootstrapModule(mainModule);

Step 4) now we will concentrate in feature module

Add “app.login_component” file under app folder.  The loginComponent contains very simple template, We can implement real time login template and handle event in real application.
import {Component} from '@angular/core'

@Component({
    selector: 'login',
    template: '<p> Welcome to login section..</p>'
})
export class loginComponent {

}

Step 5 ) Add login module

Add “app.login_module.ts” file under app folder. The login module is linked with loginComponent. In need we can attach more login/logout related component with this module  

import { NgModule } from '@angular/core';
import {loginComponent } from './app.login_component';
import { CommonModule } from '@angular/common';

@NgModule({
    imports: [CommonModule],
    declarations: [loginComponent],
    exports: [loginComponent]
})
export class loginModule {

};

Step 6) The last step is to create “index.html” page. And set it as startup page.

<!DOCTYPE html>
<html>

<head lang="en">
    <base href="/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>
   
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>

    <!-- Configure SystemJS -->
    <script src="systemjs.config.js"></script>
   
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
</head>

<body>
    <welcome>Loading App...</welcome>

</body>
</html>

Step 7) Run and Fun!!