Friday, November 8, 2013

Webapi vs MVC

Webapi is one of the most popular way of achieving RESTful service. It utilizes the HTTP verbs to handle the request and resonse.
Project wise i didnt see much of the difference between these 2. Here are few differences i could figure out -

mvc webapi
Controller inherit from MVC controller controller inhrit from APIController(Http Controller)
Common Routing based upon controller/action Common routing based upon controller/HttpVerb
Controller action returns a view Controller Action returns data
Routing defined by routeconfig class ->MapRoute method Routing defined by webapiconfig class ->MapHttpRoute method
Unlike MVC, Routing API here does not use any reference to MVC

If you see both webAPI and MVC are different from traditional requests. Traditionally the url used to have the extension of the file(like .aspx, .JSP, .ashx). But in this case we dont have any extension.
Hence in order to identify the request and proper routing at IIS level, we need to run the IIS in integrated mode. Which is mainly for .NET requests.

While creating a sample project on webapi i see that routing plays and important role here. But how does this application know that i have to hit the routing and then execute the code in corresponding controller.
Well as per my understanding and from few documentation from MSDN, i found that there is one httpmodule(named as URLRoutingModule) plays an important role. It actually captures data from the request(like HTTPContext etc) and using the routingHandler(MVCRouteHandler) it get the instance of MVCHandler. MVCHandler is nothing but a httphandler. This httphandler does not meant for a perticular extension or so. The job of this handler is to instantiate the controller and then process the request.
In MVC this handler is responsible for executing the ASP.NET lifecycle.

I am still exploring more on WebApi and lets see if we can get more indepth on this.

Thursday, September 26, 2013

Difference between == and === in javascript

In almost every programming language the easiest way for comparison is "==". But in javascript there is "===" also available. If you ask anyone what is the difference between == and === is, they will say the same thing, that is === also does the type checking. Well this is absolutely correct, but still the doubt is, how does it work?
Here are few examples -
0 == false -- > true
0 === false -- > false

1 == true --> true
1 === true --> false

2 == true --> false

In order to understand the behavior of == and ===, we need to know few internal methods of javascripts.

ToPrimitive -
Return a default value for the Object. The default value of an object is retrieved by calling the [[DefaultValue]] internal method of the object.

[[DefaultValue]] - get the output of "toString" or "valueOf" method on the object. If both method not available, then throw exception.

ToNumber -
Argument TypeResult
UndefinedNaN
Null0
Booleantrue - > 1, false - 0
NumberNo change
Stringif it is number as string, then return the number, else NaN
ObjectApply ToPrimitive, then apply ToNumber and get the output
Lets try to understand == first.
Example -> x== y
If the typeOf x and y are same, then there is no confusion, because its normal comparison, but the trick comes when the types are different.
Key Concept - Javascript internally converts x and y both into Numbers, if the Types are different and then do the comparison.
Lets try to practice it by example -
Variable TypeToNumberExample
String
Numeric number in string -> corresponding number
Nan, for everything else
'5' == 5 -> true
'a' == 2 -> false
ObjectApply toprimitive first, and then use above mentioned conversions for comparison
new String('1') == 1 -> true
new Boolean(false) == 0 -> true
NumberNo change
1==2 -> false
3==3 -> true
Boolean
true - > 1
false -> 0
true == 1 -> true ; false == 0 -> true
true == 3 -> false ; false == 1 -> false

In case of x and y being null or undefined, they are compared with following rules -
null == undefined -> true
 
In case of ===, the very first check javascript does is, to check the types of both x and y. Both are of different types then return false, else go ahead with further comparison.

Friday, August 16, 2013

Angular Directives - Compile vs link

In this post i will be talking more on directives.
In the previous post(http://softtechhelp.blogspot.in/2013/07/compile-vs-link-and-bootstrap-process.html) we talked the difference between compile and link and seen it by manual bootstrapping the Angular. In today's post we will try to visualize the same compile and link, while using Directives. understanding Compile and link becomes very important when you are working with directives and that the most practical case when you actually use the concept of compile and link.
Before starting small introduction of Directive -
It is a way provided by Angular to make your HTML more dynamic and rich. Using Directive we can create our component and can plug it anywhere in out HTML or can provide it as 3rd party component.
Directives has camel case notation. In HTML we access it by '-' dashcased. It is Simply precedence given by Jquery and others that HTML is case insensitive so have names separated by '-', but in javascript we will have to use special characters to support it. Hence to support both HTML and javascript we follow this convention in Angular Directives.
Without wasting any more time on theory, let begin our practical scenario and see how it works. Here is an example -
<body ng-controller="Demo">
      Name: <input ng-model="name" />
      <div>
          Hello <span ng-bind="name"></span>
      </div>    
      <div demo-greet></div>
  </body>

myApp.directive('demoGreet', function ($parse) {
return {
    //compile fn doesnt have access to scope.
    //event in the bootstrap var compositeLinkFn = $compile($rootElement);, we dont have access to scope
    compile: function compileFn(cElemtn, attrs) {
       console.log('compileFn(', cElemtn, attrs, ')');
       cElemtn.addClass('compiling');
       return function linkFn(scope, lElement, attrs) {
          console.log('linkFn(', scope, lElement, attrs, ')', cElemtn == lElement);

          lElement.text('Hello World');
       }
     }
  }
});

In the above example we have a directive "demoGreet", which has a compile function which returns link function. I have put in logging to see how many elements of that type got created. I have cElemtn(Compile)and IElement(Link) to see if both are same or not. Also ihave logged how many times does the compile and link get executed. Lets try to browse the page and see the console in chrome. This is how it looks like -


The above output shows, compile and link are same. If you see both are executed once and also true shows that the elements are also same. Well, If so, why do we have 2 different functions in Angular? Actually there is difference between the two . The difference is - compile doesn't have access to scope. In the previous article also we mentioned, after compile only while using link, scope comes into the picture. To see the actual difference we will try to use ng-repeat tag.

modify the HTML like this and see the output difference-
<div demo-greet ng-repeat="i in [1,0]"></div>
This time Compile function gets executed only once, whereas link function executed once for every iteration of repeater. Once we have repeater, the two are no longer similar.
Also if you see, both the elements has class "compiling" when compile function got executed only once. That is because the compile function works on template. It modified the template, which ng-repeat use to create new instance.
Compile function is used to modify the template, and link is more for linking with the objects.

I hope it clarifies the difference between two.

Friday, July 26, 2013

Compile vs link And Bootstrap process in AngularJS

To understand the difference between compile and link, we need to understand how Angular bootstrap the app, that is why i combined these 2 topics.
To bootstrap any angular app, it is just writing a "ng-app" tag in the HTML and that is all, but behind the scene what happens, we don't know. I tried to explore it in detail and that is what i came up with.
Before we go into the detail, please read startup section from Angular site (http://docs.angularjs.org/guide/concepts) -

Here is my understanding how it works -

Lets try to bootstrap the application manually, instead of relying upon Angular. For this we will have to wait for application's DOM to get ready. I have bootstrap code in the window.onload and here is the code with the detail comments -

Here is the HTML code -
 <body ng-controller="Demo">
      Name: <input ng-model="name" />
      <div>
          Hello <span ng-bind="name"></span>
      </div>
      <ul>
          <li ng-repeat="i in [1,2,3]">{{i}}</li>
      </ul>
  </body>

Here is the JavaScript -
var myApp = angular.module('myApp', []);
function Demo($scope) {}

window.onload = function () {
var $rootElement = angular.element(window.document);
var modules = [
'ng',            
'myApp',
function($provide){
$provide.value('$rootElement', $rootElement);
}
];

var $injector = angular.injector(modules);
var $compile = $injector.get('$compile');
var compositeLinkFn = $compile($rootElement);
var $rootScope = $injector.get('$rootScope');
compositeLinkFn($rootScope);
$rootScope.$apply();
}

Explaination of Code -
var $rootElement = angular.element(window.document);
wait for DOM to load;
get the root of the document,normally location of ngapp, in our case just the root element

var modules = [..];
get list of modules

Inside module the 1st module we mentioned is - 'ng' which os inbuilt module of Angular. for manual bootstrap we need to mention it. If we won't mention it we will get this error -Unknown provider: $compileProvider <- compile="" p="">
Next i mentioned myApp, which is the module i wanted to bootstrap
'myApp'

After this there is 3rd inline module, just for demonstration purpose.
function($provide){
$provide.value('$rootElement', $rootElement);
}

var $injector = angular.injector(modules);
Get the rootinjector of the application. There can only be one injector instance per application and not per module.
Above line creates the injector and returns its object.

var $compile = $injector.get('$compile')
It returns the compile service, which actually compile the code. If you read the article on Angular Overview from Angular official site, then it is the same compile service it was talking about.
compile service traverse the DOM and get the directives and returns the link fn collection.

var compositeLinkFn = $compile($rootElement);
We get the linking function using compile service.

var $rootScope = $injector.get('$rootScope');
get the rootscope. It is the same root element where we write the ng-app tag to make it an Angular app.

compositeLinkFn($rootScope);
Call the link function, that is where actual mapping of view with the original object happens.

$rootScope.$apply();
command Angular to render the view for you.

The above code demonstrate how Angular bootstrap the app, But it doesn't give any details on compile Vs link, Which is the topic of this article. Well Lets talk about it now.
Compile - It works on template. Its like adding a class element in to the DOM.
Link - It works on instances.
The concept of compile and link comes from C, where we first compile the code and then link it to actually execute it. The process is very much same in Angular as well.
In Angular not every directive will be able to demonstrate it, but "repeate" directive shows the difference very clearly.
To understand the difference lets try to debug the above code. Attach the debugger at line 2, 16 and 20. Here is the screent shot what i see when i am at line 2 -




The code looks very much similar to the one i have written in my HTML, no difference yet.Lets see what happens at line 16 - 



We actually compiled the repeat tag and repeater compile function knows it has to create bunch of copies, hence it keeps the original syntax in comment and then internally compile the template itself.
Lets move to line 20 - 

linking function creates the view.Once linking function is executes it creates the view, but it wont change the DOM itself, Once we call apply() function of angular, it renders the view for you.

Monday, July 22, 2013

AngularJS scope Inheritance-1

JavaScript prototypical inheritance -

Before talking about AngularJS scope inheritance lets have a quick recap on what is prototypical inheritance in javascript is.
We all know its possible to have parent child relationship in javascript(If you don't know, please go through the old articles under javascript section to get more insight). When we try to refer to any property in child object and if its available with child then we get the value immediately, but if we the property is not with child, then javascript try to get the value from its parent.
Let's try to understand it by example - 
say there is parent and child object. The prototype of child is parent. 
parent.p1 = 'p1';
child.c1='c1';

alert(child.c1) --> c1, directly from child object
alert(child.p1) -->p1 , from its parent

now we write child.p1 = 'cp1';
alert(child.p1); --> it will alert cp1. In other words defining the same property on child hides the parent's property.

Scope Inheritance in Angular - 
Scope inheritance is very much straight forward in angular, until we have 2 way binding to primitive types defined in parent from child. If we have such binding and child gets its own property which hides the parent property, then it causes unexpected output. This is not Angular specific, but the behavior of javascript only.

We will try to understand the scope inheritance in case of different directives defined in Angular. 
(For the detail of the functionality provided by different directives, please refer - http://softtechhelp.blogspot.in/2013/07/angular-js-inbuilt-directives.html )

ng-include
It creates a new child scope and inherits from parent. 
lets say we have following properties available in our controller scope(of index.htm) -
$scope.myPrimitive = 50;
$scope.myObject    = {aNumber: 11};

In our view we have following code -
tmpl1.htm -
<input ng-model="myPrimitive">

tmpl2 -
 <input ng-model="myObject.aNumber">

index.htm -
<div ng-include src="'/tmpl1.htm'"></div>
<div ng-include src="'/tmpl2.htm'"></div>

In our index.htm i have included both template htm using ng-include tag. If you see carefully we have 2 way binding with a primitive in tmpl1 and binding with reference type in tmpl2.
As per definition both child should create it's own scope and should inherit from parent scope. Which means both myPrimitive and myObject will be available to tmpl1 and tmpl2.

In tmpl1 i have tried to access myPrimitive and as its not been defined in current scope, hence it will be availed from its parent. In the similar way, myObject in tmpl2 will also be referred from parent scope only.

What will be the value of myPrmitive  and myObject.aNumber will be, if we type "123" and "456" in input box of tmpl1 and tmpl2?
The first impression comes is, it will be "123" and "456". But if you think about scoping, then typing any value in text box in tmpl1 will introduce a new property "myPrimitive" in child scope and parent property will remain intact. in case of myObject, in tmpl2 we are referring to myObject.aNumber. as myObject is not available in child scope, hence it will be referred from parent only and it will modify original parent's myObject.

What if we really want to modify the value of myPrmitive of parent from child input? The simplest way would be to use $parent.
So the code in tmpl1.htm would be -
<input ng-model="$parent.myPrimitive">

Here is the HTML which can demonstrate you the full example -
  <body>
    <div ng-controller="Ctrl">base page-<br />
        input 1 - <input ng-model="myPrimitive" /><br />
        input 2 - <input ng-model="myObject.aNumber" />
        <br />
        <div ng-include src="'tmpl1.html'"></div>
        <div ng-include src="'tmpl2.html'"></div>    
    </div>
  </body>

function Ctrl($scope) {
    $scope.myPrimitive = 50;
    $scope.myObject = { aNumber: 11 };
}
NOTE - in ng-include, if you are writing any html, then put single quote inside double quote to mention the html file path.

ng-repeat -
scoping in ng-repeat is slightly different. ng-repeat work on collection. So lets take an example of an array of primitives and array of javascript objects.
$scope.primitives= [ 123, 456 ];
$scope.objects = [{num: 111}, {num: 222}]
<ul><li ng-repeat="num in primitives">
       <input ng-model="num">
    </li>
<ul>
<ul><li ng-repeat="obj in objects ">
       <input ng-model="obj.num">
    </li>
<ul>

ng-repeat creates a new child scope for each iteration. And in case of primitive values, a copy of primitive is assigned to the child scope. Hence modifying the value in text box wont change anything in parent. The case will be different for objects, where original parent's  object will be modified.

Here is the HTML which can demonstrate you the full example -
    <div ng-controller="Ctrl">base page values-<br />
        primitive array items = {{primitives | json}}<br />
        object array items = {{objects | json}}
        <br />
     
        ng-repeat demo - <br />
         <ul>
            <li ng-repeat="obj in objects">
                <input ng-model="obj.num" />
            </li>
        </ul>
        <div>
             <div ng-repeat="item in primitives">
                <input ng-model="item" />
            </div>
        </div>
     
    </div>

function Ctrl($scope) {
    $scope.primitives = [123, 456];
    $scope.objects = [{ num: 111 }, { num: 222 }];
}

NOTE - If you try to type anything in the input binded with primitive, you will see you are not able to edit it. This is because, once you edit it, Angular's binding update it with the parent's value(which is still old). this is because editing child's field wont update the parent, and you will always see the old value.
For more detail on this problem, please read - 

ng-controller -
The scope inheritance will be very much same we discussed in ng-include.

ref - https://github.com/angular/angular.js/wiki/Understanding-Scopes#wiki-ngInclude

Sunday, July 14, 2013

AngularJS inbuilt directives

This post will give introduction about different tags(directives) available in Angular.

In this post we will be focusing on -
ng-include
ng-repeat
ng-controller
ng-view

ng-include-
Using ng-include tag we can fetch any external HTML file in our current HTML. Just like script tag where we can include external javascript file, in the similar way using ng-include we can include external html file as well. This HTML will be embedded into our original html itself.
Ex. - <div ng-include src="'view/menu.htm'" ></div>

ng-repeat-
This is equivalent to traditional foreach loop. Using this directive you can write a foreach loop in HTML as well. Generally we write ng-repeat on a collection. We take the each values of collection and repeate the underlying tag.
Ex . -
<ul ng-repeat="items in itemArray">
<li>
   <div>{{item.name}}<div>
</li>
</ul>

itemArray should be defined in the controller scope. The above code traverses on itemArray and repeat the "ul" tag with every value and populate the name property of item in the mentioned Div element.

ng-controller -
ng-controller is a directive by which angular supports the idea of code behind for MVC implementation.(There are alternative ways possible to define controller, but this is the simplest and popular way to define controller).
Here is the example from Angular official site -
The above diagram gives very simple view of how controller, view and scope are related. controller is defined in view with ng-controller directive and the corresponding scope is available in the function "MyCtrl".  Once Angular checks this directive in the HTML it looks for corresponding definition in the JavaScript and injector take cares of mapping the scope, view and controller.

ng-view-
This tag is very usefule once we write single page application using routing framework provided by Angular. We wont go into the detail of routing framework, but its more of the mechanism in which once you change the url, the corresponding view (defined in configuration) gets loaded automatically. This view render happens inside this ng-view tag only. It is very much similar to MVC ASP .NET app, where you hit the controller and the corresponding view get renders.
Ex. - available here - http://docs.angularjs.org/api/ng.directive:ngView

AngularJS Basic terms

Today we will try to understand the basic terms used in Angular. 

Injector -
Injector is responsible for assembling the application. We might have multiple services, controllers etc, which might be interdependent. injector take cares of initializing the prerequisite of any of the services, controllers.

Module -
Module is something which configures the injector. It tells the injector what all we have in our scope. anything defined in given module will be visible to injector. Once we create service or controller or anyother component in a single module, all will be linked together via injector. You can visualize module to be a container where all your components like service/controller etc will be defined and injector will manage them. components inside one module will directly wont be visible outside the module.

Scope - The scope in Angular is very much same as JavaScript scope. Scope defines the boundry of your code. Example  - in view we define the controller. The scope of that controller is very much limited to that view only.
<Div ng-controller='myCtrl' > </Div>
myCtrl is the controller which is nothing but a javascript function. Anything you define in this function will be available to this Div element. Hence we can say the scope for this controller is the mentined Div element.
this concept can be visualized with following diagram(taken from Angular official docs) -

rootScope -
rootScope is parent of all scopes. It is the scope of your module. you can access any scope from rootscope.

Directive -
Directives are custome html, which lets you teach html new tricks. for example say there is no tag in HTML named as "list". You can create a tag named as list using directive and write code to give list like behavior to this tag.

Other key words(Won't go into the details) -
Model - Application Data
View - What user sees
Controller - application behavior
$- angular namespace

Saturday, July 13, 2013

AngularJS overview

This is very high level introduction to what Angular is, and how it is different from any other javascript framework.

If you go to the home page of Angular the very first line explains it -
"AngularJS is a structural framework for dynamic web apps"
but what does it mean? Well the first impression comes to our mind when we think about Angular JS as a javascript library is, we already have many libraries (JQuery) available in javascript, which are very mature and very well adapted by the market, then why do we need a new one. Is there any advantage of Angular over JQuery? Well the answer would be NO.
Its not because Angular is not powerful, it is because JQuery and Angular serves different purpose. To achieve fully functional we app in Javascript, you might need to use Angular and JQuery together.

The question remain same, why Angular?
There is very good paragraph on Angular official web site -

The impedance mismatch between dynamic applications and static documents is often solved with:
  • a library - a collection of functions which are useful when writing web apps. Your code is in charge and it calls into the library when it sees fit. E.g., jQuery.
  • frameworks - a particular implementation of a web application, where your code fills in the details. The framework is in charge and it calls into your code when it needs something app specific. E.g., knockoutember, etc.
Angular takes another approach. It attempts to minimize the impedance mismatch between document centric HTML and what an application needs by creating new HTML constructs. Angular teaches the browser new syntax through a construct we call directives
Angular provides you an inbuilt MVC pattern for your client side application. you can have view,model and Controller in your javascript(Which is ofcourse not provided by core javascript).

Controller code you write in javascript(Or JQuery) and update the model. Angular framework takes the responsibility of updating the view for you.

Angular provide you a way by which you can make static HTML to be dynamic(using {{}} tag).
It allows you to attach code behind with the DOM element.

you can create your own customized tags,attributes for your application and provide them different behavior.

It allows you to write HTML component which can be reusable in different applications.

Saturday, March 16, 2013

JavaScript Scope Chain

If you are not familiar with execution context, please go through this link first -- http://softtechhelp.blogspot.in/2013/03/execution-context-in-javascript.html
Scope is collection of current Activation context and all parent execution context's Activation objects.

Here is an example -
function one() {
    var a = 1;
    two();
    function two() {
var b = 1;
        three();
        function three() {
   var c = 1;
            alert('I am at function three with-a+b+c-' + a + b + c);
        }
    }
}
one();

In the above code the execution stack will have following stack of execution contexts -
Global -> One() -> two() -> three()
So if we talk about the scope of function three() then it becomes -
[AO of three()] + [AO of two()] + [AO of one()] +[AO of Global()]

If you see we are trying to print value a,b and c from function three(), but it has only c defined in it. So in order to find the value of a and b it will traverse in "[AO of two()] + [AO of one()] +[AO of Global()]" and check if these variables are available in there.

Lexical Scope - All functions are statically bound to its parent context. Which means in the above example function three() will always be bound to two(), which in turn be bounded to one() and so on.
Example -
var myAlerts = [];
for (var i = 0; i < 5; i++) {
    myAlerts.push(
        function inner() {
            alert(i);
        }
    );
}
myAlerts[0](); // 5
myAlerts[1](); // 5
myAlerts[2](); // 5
myAlerts[3](); // 5
myAlerts[4](); // 5

In the above example function inner() was created in global context, hence it is statically bound to global. Hence once we try to print the value of i, it checks if it has "i" defined, if not then it goes to its parent context, where it finds i to be "5".

Excercise -
// a globally-scoped variable
var a = 1;

// global scope
function one() {
    alert(a);
}
one(); // 1

// local scope
function two(a) {
    alert(a);
}
two(2); //2

// local scope again
function three() {
    var a = 3;
    alert(a);
}
three(); //3

// Intermediate: no such thing as block scope in javascript
function four() {
    if (true) {
var a = 4;
    }
    alert(a); // alerts '4', not the global value of '1'
}
four(); //4

// Intermediate: object properties
function Five() {
    this.a = 5;
}
alert(new Five().a); //5

// Advanced: closure
var six = function () {
    var foo = 6;
    return function () {
// javascript "closure" means I have access to foo in here,
// because it is defined in the function in which I was defined.
alert(foo);
    }
} ();
six(); //6

// Advanced: prototype-based scope resolution
function Seven() {
    this.a = 7;
}

// [object].prototype.property loses to [object].property in the scope chain
Seven.prototype.a = -1; // won't get reached, because 'a' is set in the constructor above.
Seven.prototype.b = 8; // Will get reached, even though 'b' is NOT set in the constructor.

alert(new Seven().a); //7
alert(new Seven().b); //8      

Execution Context in JavaScript

Execution Context can be visualize as Environment/scope the current code is being evaluated in.
As per ECMA  - When control is transferred to ECMAScript executable code, control is entering an execution context. Active execution contexts logically form a stack. The top execution context on this logical stack is the running execution context.

Browser is a single threaded environment. Only 1 thing can happen at a time, other actions will be queued in "Execution Stack".
Every function and constructor call enters a new execution context, even if a function is calling itself recursively. Every return exits an execution context. A thrown exception, if not caught, may also exit one or more execution contexts.

Lets take an example here -
(function foo(i) {
    if (i === 3) {
        return;
    }
    else {
        foo(++i);
    }
}(0));

In the above excample foo calls itself 3 times. Hence along with the global context, it creates 4 more execution context(for i = 0,1,2,3).

Execution Context has 2 stages -
1) Create stage - function called, but not yet executed-
1.1 Create Variables, functions and arguments
a) Create the arguments object, check the context for parameters, initialize the name and value and create a reference copy.
b) For each function found, create a property in the variable object that is the exact function name, which has a reference pointer to the function in memory.
c) For each variable declaration found, create a property in the variable object that is the variable name, and initialize the value as undefined.
1.2 Create Scope chain
1.3 Create value of "this"
2) Activation/Execution stage -
Assign values, reference to functions and execute


Execution context can be visualize in following object format -
executionContextObj = {
    variableObject: { /* function arguments / parameters, inner variable and function declarations , Can also be visualize as Activation Object*/ },
    scopeChain: { /* variableObject + all parent execution context's variableObject */ },
    this: {}
}

When the JavaScript engine invokes any function, it creates a new object (Activation object) and all the local variable defined within the function and the named argument passed to the function along with ‘arguments’ object get defined as properties of this activation object. The activation object is also added to the front of the execution scope chain.
In current scenario when control enters an execution context for function code, an object called the "Activation object"(stage 1.1) is created and associated with the execution context. The activation object is initialised with a property with name arguments and attributes.
The activation object is then used as the variable object for the purposes of variable instantiation.
The activation object is purely a specification mechanism. It is impossible for an ECMA Script program to access the activation object. It can access members of the activation object, but not the activation object itself.

Here is an example -
function foo(i) {
    var a = 'hello';
    var b = function privateB() {
    };
    function c() {
    }
}
foo(22);

After stage 1 -
fooExecutionContext = {
    variableObject: { // stage 1.1
        arguments: { // stage a
            0: 22,
            length: 1
        },
        i: 22, // stage a
        c: pointer to function c() // stage b
        a: undefined, // stage c
        b: undefined  // stage c
    },
    scopeChain: { ... }, //stage 1.2
    this: { ... } // stage 1.3
}

After Stage 2 -
fooExecutionContext = {
    variableObject: {
        arguments: {
            0: 22,
            length: 1
        },
        i: 22,
        c: pointer to function c()
        a: 'hello',
        b: pointer to function privateB()
    },
    scopeChain: { ... },
    this: { ... }
}

Reference -
1) http://davidshariff.com/blog/what-is-the-execution-context-in-javascript/
2) http://bclary.com/2004/11/07/#a-10

Saturday, March 9, 2013

Template Method and Adapter Pattern

Template Method -

- The template of the flow is provided by an abstract base class, and the implementation is done by derived or subclasses.
- Example if we write a parser, then we will provide the flow of parsing in the base class in the following way
parser {
parseFile(){
 load();
 parse();
close();
}
}

excelParser : Parser{
load () {//load excel}
parse(){//parseExcel}
close(){close excel}
}
pdfParser : Parser{
load () {//load pdf}
parse(){//parse pdf}
close(){close pdf}
}

Adapter-

- Provide an intermediate class which can help translating one interface into another compatible one.
- As a simplest example lets consider there is data from one stream in one format and our class expect it in another format. In this case we provide an intermediate class which can convert it into desired format, that intermediate class is adaptor class.

- We can understand it in the form of class adaptor as well, say there is class consultant and employee. Employee implements IEmployee interface but consultant doesn't. If we want to put consultant into a list of IEmployee then we will have to provide another class say ConsultantToEmployee which implements IEmployee and extends consultant.

By this we can have consultants also get saved in the list of IEmployee.

Design Principles

open-close principle -
- open for extension and closed for modification.
- example in strategy, we expose all the behaviors using interface. In future if we want to modify any behavior, or want to add any new behavior, we can do it, because we are calling interface(open for extension) not the concrete class object. The user class will not have to modify anything to achieve this(close for modification).

double dispatch-
- 2 calls to complete an operation.
- an object provides its own instance to some other class to get operated on it.
- Example - patient goes to doctor and then doctor operates on him.
This is what happens in visitor pattern. object of visitor is passed to the class, from there it calls visit method to get its functionality done.

Visitor pattern and Strategy Pattern


Visitor-

 - separate algorithm from object, which provides ability to add new feature without modifying the structure.
 - works on double dispatch principle.
 - Isolate the behavior from original class and provide it in other visitor class
 - pass the visitor object to the class, and then use this object to execute the behavior
 -Ex - there is a printer and we want to print from a machine.
precondition - every machine should have ExecutePrint method,hence we can have an interface for this.
printer will have overridden method for printing from different kind of machines.
pseudo code -
desktop m1 = new desktop ();
Printer p = new Printer();
m1.ExecutePrint(p);//accept
Printer{
Print(desktop d1){// print for desktop}
Print(laptop l1){// print for laptop}
}
Desktop{
  ExecutePrint(Printer p)
 {
    p.Print(this);//visit
 }
}
laptop{
   ExecutePrint(Printer p)
   {
      p.Print(this);
   }
}

Strategy -
Isolate the behavior using interface.
- every class will call behavior using interface only, at run time the object of concrete class(implementing interface) will be passed.
- At run time we can decide which kind of object we want to pass, as the whole implementation is done using interface, so any kind of object for which this interface is been implemented, can be passed.
- Example-
Say there is interface IBehavior , and all behaviors implement this.
Behavior1 : IBehavior {}
Behavior2 : IBehavior {}

Now the classes will use IBehavior in its implementation and when we are trying to create the object of the class, we can pass the object of either Behavior1 or Behavior2 and then the object will execute the code accordingly.

Friday, March 8, 2013

Factory Pattern and Singleton Patterns

Factory-
 - hide constructor(make it private)
 - expose a method which will provide you the required object.

advantages -
 - get rid of the repetition of "new" key word whenever we create objects.
 - abstract the implementation
whenever we provide some kind of library, its always good to provide a factory which will provide users the desired object, instead of exposing the class.

limitations -
 - private constructor will cause problem in inheritance

NOTE - making constructor protected will let us derive the class, but then we will have to provide the same getter method for subclass as well, else it will return the base object always, even if we call it on derived class.

Singleton-

 - only one instance of a class.
 - single instance, global access.

singleton vs static - singleton can be implemented using static as well. but static class can not implement any interface, unless interface is simply a marker.

limitations -
 - inheritance is not possible.
 - testing might become tricky. 

Wednesday, January 16, 2013

Introduction to MVC in ASP.NET

MVC - Model - View - Controller
Most of the ASP.NET applications consist of UI + Code behind + middler layer + data layer.

Actually code behind(.aspx.cs) is not independent from .aspx file. We can not compile anyone one of them independently.

Because of that there are few problems we face while -
a) Testing - unit testing becomes tricky.
b) Code re usability - as .aspx.cs and .aspx files are connected with each other, its not straight to put that code somewhere else and reuse it in other classes.

MVC - write all your code behind in controller class and let UI be independent. return view object to UI and  show it to the user.

Session Management in MVC -
The problem with using the ASP.NET session or view state object is the scope. ASP.NET session objects have session scope and view state has page scope. For MVC we would like to see the scope limited to the controller and the view. In other words we would like to maintain data when the hit comes to the controller and reaches the view and after that the scope of the data should expire.
That’s where the new session management technique has been introduced in the ASP.NET MVC framework, i.e., ViewData. It is mainly to pass data fro controller to view.

Developer's notes

The view does not have a code-behind. So to display the view we need to use the <%: tag in the ASPX page.

Once we create MVC project and create controller, it will be given name as abccontroller and then will have to create view for this controller. If we want to invoke that view then will have to hit the url like this -
http://localhost/abc....note that its abc, not abccntroller .

Is it possible to have 2 view with one controller ?? - yes
or 2 controller for one view?? No;
Because if you see the url, there we actually hit the controller name and accordingly the view is decided and in controller we actually return new View object, this object is handed over to view which finally renders the page depending upon the object passed. Its not possible to pass view object to another controller and then send the final consolidated view.We will need to modify the design a little bit and will have to hack it, if we want anything like this.

Importance of Httppost attribute -
In controller above View definition, we can  write [Httppost]. It means that this view will handle only post requests. If we put this attribute and then send a GET request then we will get 404 response.

MVC Routing -
we can have multiple URL’s mapped to one controller or you can have more than one controller mapped to a single URL.
It would be great if we have some kind of mechanism by which we can configure these mappings. That’s what exactly MVC routing is meant for. Check the Global.asax file, all the mappings are stored there.
All routing mapping are stored in to a collection called as ‘routes’. This collection belongs to the namespace “System.Web.Routing”. To add a route you need to call the ‘MapRoute’ method and pass three parameters “name”,”url” and “defaults”.

If you check Global.asax you will find following entry there -
routes.MapRoute(
 "Default", // Route name
 "{controller}/{action}/{id}", // URL with parameters
 new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

This is the default route create by visual studio project. It means that if you hit following url:
http://localhost:2406/customer/DisplayAnotherCustomer ; Then it will invoke "customer" controller with "DisplayAnotherCustomer" as action. If you notice there is an id parameter also which is optional.
Lets try to modify the url and try to make it like this - http://localhost:2406/mvctest/customer/DisplayAnotherCustomer.

To do so i ll comment the mentioned line from Global.asax and will put the following line instead-
routes.MapRoute(
 "Customer", // Route name
 "mymvc/{controller}/{action}/{id}", // URL with parameters
 new { controller = "Customer", action = "DisplayAnotherCustomer", id = UrlParameter.Optional } // Parameter defaults
);

I have given route a name as "Customer" and mentioned the url to be "mymvc/{controller}/{action}/{id}".

Validation by route-
If we want to put any constraint(or validation), then we can use 4th parameter in MapRoute constructor. For example if we want the url like this - http://localhost:2406/mvctest/customer/DisplayAnotherCustomer/1
And depending upon number passed we want to take some action. Now its possible to put constraint in the url in following way -

routes.MapRoute(
 "Customer", // Route name
 "mymvc/{controller}/{action}/{id}", // URL with parameters
 new { controller = "Customer", action = "DisplayAnotherCustomer", id = 0 } // Parameter defaults
 , new { id = @"\d{1,2}" }
);
4th parameter take regular expression, where we have allowed all 2 digit numbers. Hence passing any string or any other character won't work(it will simply give 404).

Navigation -
If we want to provide navigation from one page to another, we can't directly provide href link on one page, as it is violation of MVC rule. Directly providing href link to the page will take us to the view first, rather than controller. As per MVC principle the hit should come to the controller first.
So the idea is to use Action instead of directly using aspx page.
Here is example -

<a href="GotoHome">Go Home</a><br />
GotoHome is action, which will load required view for us.

Wednesday, January 9, 2013

JavaScript Tips and Tricks-9

Lets try to understand the output of following function - 

function fun(){}
var fun1 = new fun();
var fun2 = fun(); //undefined
var fun3 = fun;

fun1.newProp1 = '1';
fun3.newProp2 = '2';

alert(fun1.newProp1);//-- 1
alert(fun3.newProp2);//-- 2

var fun4 = new fun();
alert(fun4.newProp2);//undefined

if we define fun in the following way -
function fun(){ return this;}
then fun2 will not be undefined, it will be window. because fun2 = fun() actually executes the function and assign the value back to fun2.
fun3 is also just pointing at the definition of fun, but we can not write var a = new fun3(); it will be undefined.

Moreover on the heap you will see just 2 objects, fun1 and fun4(along with the original definition of course).
Lets try to find the answer for following exercise -
    function fun(){
        this.a = '1';
        b = '2';
        var c = '3';
        return this;
    }
   
    var fun1 = new fun();
    alert('fun1.a ' + fun1.a);
    alert('fun1.b ' + fun1.b);
    alert('fun1.c ' + fun1.c);

    var fun2 = fun();
    alert('fun2.a ' + fun2.a);
    alert('fun2.b ' + fun2.b);
    alert('fun2.c ' + fun2.c);

    alert('window.a ' + window.a);
    alert('window.b ' + window.b);
    alert('window.c ' + window.c);

Answer -

var fun1 = new fun();
alert('fun1.a ' + fun1.a); //1
alert('fun1.b ' + fun1.b); // undefined
alert('fun1.c ' + fun1.c); // undefined

var fun2 = fun();
alert('fun2.a ' + fun2.a); //1
alert('fun2.b ' + fun2.b); //2
alert('fun2.c ' + fun2.c); // undefined

alert('window.a ' + window.a); //1
alert('window.b ' + window.b); //2
alert('window.c ' + window.c); // undefined