Tuesday, 11 July 2017

$Broadcast(), $Emit() And $On() In AngularJS

AngularJS applications may need to communicate across the controllers. Such a communication might be needed to send notifications or to pass data between the controllers. Although there can be different approaches to achieve this goal, one that is readily available is the event system of $scope and $rootScope. Both of these objects - $scope and $rootScope - support three methods namely $broadcast(), $emit() and $on() that facilitate event driven publisher-subscriber model for sending notifications and passing data between the controllers. In this article I will discuss how to raise events using $broadcast() and $emit() and then how to handle those events using $on().

Overview of $broadcast(), $emit() and $on()

Before you dig into the examples discussed below it would be worthwhile to take a quick look at the purpose and use of $broadcast(), $emit() and $on().
$broadcast() as well as $emit() allow you to raise an event in your AngularJS application. The difference between $broadcast() and $emit() is that the former sends the event from the current controller to all of its child controllers. That means $broadcast() sends an even downwards from parent to child controllers. The $emit() method, on the other hand, does exactly opposite. It sends an event upwards from the current controller to all of its parent controllers. From the syntax point of view a typical call to $broadcast() and $emit() will look like this:

$scope.$broadcast("MyEvent",data);
$scope.$emit("MyEvent",data); 

Here, MyEvent is the developer defined name of the event that you wish to raise. The optional data parameter can be any type of data that you wish to pass when MyEvent is dispatched by the system. For example, if you wish to pass data from one controller to another that data can go as this second parameter.

An event raised by $broadcast() and $emit() can be handled by wiring an event handler using $on() method. A typical call to $on() will look like this:

$scope.$on("MyEvent", function(evt,data){ 
  // handler code here });

Now that you know what $broadcast(), $emit() and $on() do let's put them to use in the following examples.

Event system on $scope and $rootScope

When it comes to communicating between two or more AngularJS controllers there can be two possible arrangements:
  • Controllers under consideration are nested controllers. That means they have parent-child relationship.
  • Controllers under consideration are sibling controllers. That means they are at the same level without any parent-child relationship.
In the former case you will use $broadcast(), $emit() and $on() on the $scope object whereas in the later case you will use these methods on the $rootScope object. Let's see each of the possibility with an example.

Nested controllers

To see how $broadcast(), $emit() and $on() can be used with nested controllers, you will develop a simple application as shown below:


The above application consists of three AngularJS controllers - MyController1, MyController2 and MyController3 - nested inside each other. The outermost <div> (MYController1) has a button for raising an event handled SendDown. Similarly, the innermost <div> (MyController3) has a button for raising an event named SendUp. Thus the SendDown event is raised in MyController1 and can be handled by MyController1, MyController2 and MyController3. On the same lines SendUp event us raised inside MyController3 and is handled by MyController3, MyController2 and MyController1. Notice that although both the events look similar, the SendDown event travels from MyController1 to MyController3 whereas SendUp travels from MyController3 to MyController1.

Both the events send a string data ("some data") when the corresponding event is dispatched. You can easily substitute an object instead of string data. Upon handling the respective events a message is shown inside each <div> just to confirm that the handler has indeed executed and the data is received successfully.

Ok. Now let's see the code of all the controllers mentioned above. The MyController1 looks like this:

app.controller("MyController1", function ($scope, $rootScope) {

    //broadcast the event down
    $scope.OnClick = function (evt) {
        $scope.$broadcast("SendDown", "some data");
    }

    //handle SendDown event
    $scope.$on("SendDown", function (evt, data) {
        $scope.Message = "Inside SendDown handler 
                          of MyController1 : " + data;
    });

    //handle SendUp event
    $scope.$on("SendUp", function (evt, data) {
        $scope.Message = "Inside SendUp handler 
                          of MyController1 : " + data;
    });
});

MyController1 does three things. Firstly, it raises SendDown event using $broadcast() method. It uses $broadcast() because we wish to send the event from parent controller to child controllers. So, the SendData is dispatched by MyController inside the click event handler of the Broadcast button. Secondly, MyController1 handles SendData event using $on(). Since SendData is raised by MyController itself this step might not be needed at all. I am still handling the event just to point out that something like that is possible. The SendDown handler simply sets Message property of the $scope object. This Message will be displayed in the corresponding <div> element. Thirdly, MyController1 handles SendUp event. Recollect that this event is raised by MyController3 in the upward direction (child to parent) and MyController1 simply handles it.

The code of MyController2 is quite straightforward and is shown below:

app.controller("MyController2", function ($scope, $rootScope) {

    //handle SendDown event
    $scope.$on("SendDown", function (evt, data) {
        $scope.Message = "Inside SendDown handler of 
                          MyController2 : " + data;
    });

    //handle SendUp event
    $scope.$on("SendUp", function (evt, data) {
        $scope.Message = "Inside SendUp handler of 
                          MyController2 : " + data;
    });

});

MyController2 simply handles SendDown and SendUp events and sets Message property on the $scope object.

Finally, MyController3 does the following:

app.controller("MyController3", function ($scope, $rootScope) {

    //handle SendDown event
    $scope.$on("SendDown", function (evt, data) {
        $scope.Message = "Inside SendDown handler of 
                          MyController3 : " + data;
    });

    //emit SendUp event up
    $scope.OnClick = function (evt) {
        $scope.$emit("SendUp", "some data");
    }

    //handle SendUp event
    $scope.$on("SendUp", function (evt, data) {
        $scope.Message = "Inside SendUp handler of 
                          MyController3 : " + data;
    });
});

MyController3 is quite similar to MyController1. However, it raises SendUp event using $emit() method. This way SendUp event travels from child (MyController3) to the parents (MyController2 and MyController1). The event handlers of SendDown and SendUp simply assign the Message property.

The HTML markup of the page will look like this:

<body ng-app="MyApp">
 <div ng-controller="MyController1">
  <input type="button" value="Broadcast Down" 
         ng-click="OnClick($event)" />
  <h4>{{Message}}</h4>
   <div ng-controller="MyController2">
    <h4>{{Message}}</h4>
    <div ng-controller="MyController3">
     <h4>{{Message}}</h4>
     <input type="button" value="Emit Up" 
            ng-click="OnClick($event)" />
    </div>
   </div>
  </div>
</body>

If you run the application and click on the Broadcast button you should get results as shown above. Clicking on Emit button will produce the following result:


Sibling controllers

The above examples achieves communication and passes data between controllers having parent-child relationship. What if you wish to achieve the communication between sibling controllers? If so, you need to use $rootScope instead of $scope. That's because since there is no parent-child relationship, each controller will have its own scope and there won't be any inherited scope as in the previous example. Moreover, $emit() won't serve much purpose in case of sibling controllers. This is because $rootScope is a container scope for all the other scopes and can dispatch events only to its child controllers. So, only $broadcast() will serve some useful purpose in this case.

Assuming that there are three sibling controllers - MyController1, MyController2 and MyController3 - the application will take this form:


As before there are three controllers but they are siblings. The topmost <div> (MyController1) has Broadcast button that raises SendDown event on $rootScope object. All the controllers handle the SendData event and set Message property on their individual $scope object. The complete code of all the three controllers is shown below:

app.controller("MyController1", function ($scope, $rootScope) {
    //raise event on $rootScope
    $scope.OnClick = function (evt) {
        $rootScope.$broadcast("SendDown", "some data");
    }

    //event handler
    $scope.$on("SendDown", function (evt, data) {
        $scope.Message = "Inside MyController1 : " + data;
    });

});

app.controller("MyController2", function ($scope, $rootScope) {
    //event handler
    $scope.$on("SendDown", function (evt, data) {
        $scope.Message = "Inside MyController2 : " + data;
    });

});

app.controller("MyController3", function ($scope, $rootScope) {
    //event handler
    $scope.$on("SendDown", function (evt, data) {
        $scope.Message = "Inside MyController3 : " + data;
    });
});

As you can see, this time $broadcast() is called on $rootScope object to raise SendDown event. SendDown is handled by individual $scope objects as before.
A word of caution before I conclude this article - although event system discussed above looks straightforward and simple, if used excessively it can get messy in terms of overall management and application flow. So, give a thought before you jump in to raise too many events.

That's it for this article! Keep coding.

Continue Reading →

Monday, 10 July 2017

Select and SelectMany in LINQ

Select and SelectMany are projection operators. Select operator is used to select value from a collection and SelectMany operator is used to select values from a collection of collection i.e. nested collection.

Example: 

class Employee
{
 public string Name { get; set; }
 public List<string> Skills { get; set; }
}
 
class Program
{
 static void Main(string[] args)
 {
 List<Employee> employees = new List<Employee>();
 Employee emp1 = new Employee { Name = "Deepak", Skills = new List<string> { "C", "C++", "Java" } };
 Employee emp2 = new Employee { Name = "Karan", Skills = new List<string> { "SQL Server", "C#", "ASP.NET" } };
 
 Employee emp3 = new Employee { Name = "Lalit", Skills = new List<string> { "C#", "ASP.NET MVC", "Windows Azure", "SQL Server" } };
 
 employees.Add(emp1);
 employees.Add(emp2);
 employees.Add(emp3);
 
 // Query using Select()
 IEnumerable<List<String>> resultSelect = employees.Select(e=> e.Skills);
 
 Console.WriteLine("**************** Select ******************");
 
 // Two foreach loops are required to iterate through the results
 // because the query returns a collection of arrays.
 foreach (List<String> skillList in resultSelect)
 {
 foreach (string skill in skillList)
 {
 Console.WriteLine(skill);
 }
 Console.WriteLine();
 }
 
 // Query using SelectMany()
 IEnumerable<string> resultSelectMany = employees.SelectMany(emp => emp.Skills);
 
 Console.WriteLine("**************** SelectMany ******************");
 
 // Only one foreach loop is required to iterate through the results 
 // since query returns a one-dimensional collection.
 foreach (string skill in resultSelectMany)
 {
 Console.WriteLine(skill);
 }
 
 Console.ReadKey();
 }
}
 
/* Output
 
**************** Select ******************
 
C
C++
Java
 
SQL Server
C#
ASP.NET
 
C#
ASP.NET MVC
Windows Azure
SQL Server
 
**************** SelectMany ******************
 
C
C++
Java
SQL Server
C#
ASP.NET
C#
ASP.NET MVC
Windows Azure
SQL Server
*/
Continue Reading →

Thursday, 6 July 2017

Scopes in AngularJS Custom Directives

In this post we will learn about different kinds of scopes in AngularJS custom directives. First we’ll start with a high level introduction of directives and then focus on scopes.

Directives

Directives are one of the most important components of AngularJS 1.X, and have the following purposes:
1.       Gives special meaning to the existing element
2.       Creates a new element
3.       Manipulates the DOM

Beyond ng-app, ng-controller, and ng-repeat, there are plenty of built-in directives that come with AngularJS, including:
·         ng-maxlength
·         ng-minlength
·         ng-pattern
·         ng-required
·         ng-submit
·         ng-blur
·         ng-change
·         ng-checked
·         ng-click
·         ng-mouse
·         ng-bind
·         ng-href
·         ng-init
·         ng-model
·         ng-src
·         ng-style
·         ng-app
·         ng-controller
·         ng-disabled
·         ng-cloak
·         ng-hide
·         ng-if
·         ng-repeat
·         ng-show
·         ng-switch
·         ng-view

Mainly, directives perform either of the following tasks:
·         Manipulate DOM
·         Iterate through data
·         Handle events
·         Modify CSS
·         Validate data
·         Data Binding

Even though there are many built-in directives provided by the Angular team, there are times when you might need to create your own custom directives. A custom directive can be created either as an element, attribute, comment or class. In this post, a very simple custom directive can be created as shown in the listing below:


MyApp.directive('helloWorld', function () {
    return {
        template: "Hello IG"
    };
});

While creating custom directives, it’s important to remember:

• The directive name must be in the camel case;
• On the view, the directive can be used by separating the camel case name by using a dash, colon, underscore, or a combination of these.

Scopes in Custom Directives

Scopes enter the scene when we pass data to custom directives. There are three types of scopes:

1.       Shared scope
2.       Inherited scope
3.       Isolated scope

Shared scope
This type is requested when scope is false in the definition object or when scope is not specified (false is the default value of the property).
Shared scope simply means that the directive works with the same scope that is already available for the DOM node where the directive appears without creating a new one.


// 1. Shared scope (scope: false)
  .directive("nghSharedScopeDir", function ()
  {
    return {
      scope: false,
      template:
        '<label>First name: <input type="text" ng-model="firstName"/></label><br />' +
        '<label>Last name: <input type="text" ng-model="lastName"/></label><br />' +
        '<br />' +
        '<strong>First name:</strong> {{firstName}}<br />' +
        '<strong>Last name:</strong> {{lastName}}'
    };
  })

Inherited scope
This type is requested when scope is true in the definition object.
A new scope is created for our directive, but it inherits all the properties of the parent scope through JavaScript's prototypal inheritance: when the directive accesses a property on it's new scope, the property is first searched on the current scope and if it's found then it's value is returned, otherwise, if it's not found, the same property name is searched in the parent scope and that value is returned (the search traverses all the parents until the property is found or until there are no more parents); if a value is assigned to a property on the new directive's scope and the same property already exists in the parent, accessing the property value directly in the new scope will in fact override the parent's property value and any change to the property in the parent will not be propagated anymore to the child scope.


// 2. Inherited scope (scope: true)
  .directive("nghInheritedScopeDir", function ()
  {
    return {
      scope: true,
      template:
        '<label>First name: <input type="text" ng-model="firstName"/></label><br />' +
        '<label>Last name: <input type="text" ng-model="lastName"/></label><br />' +
        '<br />' +
        '<strong>First name:</strong> {{firstName}}<br />' +
        '<strong>Last name:</strong> {{lastName}}'
    };
  })

Isolated Scope
In Isolated scope, the directive does not share a scope with the controller; both directive and controller have their own scope. However, data can be passed to the directive scope in three possible ways.
1.       Data can be passed as a string using the @ string literal
2.       Data can be passed as an object using the = string literal
3.       Data can be passed as a function using  the & string literal

// 3. Isolated scope (scope: {})
  .directive("nghIsolatedScopeDir", function ()
  {
    return {
      scope:
        {
          firstName: '@dirFirstName',
          lastName: '=dirLastName',
          setNameMethod: '&dirUpdateNameMethod'
        },
      template:
        '<label>First name: <input type="text" ng-model="firstName"/></label><br />' +
        '<label>Last name: <input type="text" ng-model="lastName"/></label><br />' +
        '<button ng-click="execSetNameMethod()">Set name on external scope</button><br />' +
        '<br />' +
        '<strong>First name:</strong> {{firstName}}<br />' +
        '<strong>Last name:</strong> {{lastName}}',
      link: function (scope, element, attrs)
      {
        scope.execSetNameMethod = function ()
        {
          scope.setNameMethod(
            {
              newFirstName: scope.firstName,
              newLastName: scope.lastName
            });
        };
      }
    };
  })


Continue Reading →

New Features in ASP.NET Web API 2

ASP.NET Web API 2 has been released with a number of new exciting features.

1. Attribute Routing
Along with convention-based routing, Web API 2 now supports attribute routing as well.

In case of convention-based routing, we can define multiple route templates. When a request comes, it will be matched against already defined route templates, and forwarded to specific controller action according to matched template.

You can see the following default route template in routing table for Web API:






Config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{Controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

This routing approach has benefits that all routing templates are defined at one common location but for certain URI patterns, it really becomes difficult to support (like nested routing on same controller).

With ASP.NET Web API 2, we can easily support above mentioned URI pattern and others as well. Following shows an example of a URI pattern with attribute routing. URI Pattern --> books/1/authors




[Route("books/{bookId}/authors")]
public IEnumerable<Author> GetAuthorByBook(int bookId) { ..... }

2. CORS - Cross Origin Resource Sharing
Normally, browsers don't allow making cross-domain calls due to same-origin policy and we know that. So, what exactly is CORS (Cross Origin Resource Sharing)?

CORS is a mechanism that allows a web page to make an AJAX call to a domain other than the domain which actually rendered that specific web page. CORS is compliant with W3C standards and now ASP.NET Web API has support for it in version 2.

3. OWIN (Open Web Interface for .NET) self hosting
ASP.NET Web API 2 comes with a new self hosting package i.e. Microsoft.AspNet.WebApi. OwinSelfHost.   According to http://owin.org/
“OWIN defines a standard interface between .NET web servers and web applications. The goal of the OWIN interface is to decouple server and application, encourage the development of simple modules for .NET web development, and, by being an open standard, stimulate the open source ecosystem of .NET web development tools.”

So, according to above description, OWIN is an ideal option for self hosting a web application in a process other than IIS process.

There are a number of OWIN implementations like Giacomo, Kayak, Firefly etc. available (some may be partial or outdated) but Katana is the recommended one for Microsoft servers and Web API frameworks.

4. IHttpActionResult
Along with the existing two approaches of creating response from controller action, ASP.NET Web API 2 now supports another way of doing the same. IHttpResponseMessage is basically an interface which acts as a factory for HttpResponseMessage. It's very powerful because it extensify web api. Using this approach we can compose any specific type of response.
Please follow the link to know how to serve HTML with IHttpActionResult.

5. Web API OData
The Open Data Protocol (OData) is actually a web protocol for querying and updating data. ASP.NET Web API 2 has added support for $expand, $select, and $value options for OData. By using these options, we can control the representation that is returned from the server.

$expand: Normally, response doesn’t include related entities if we query an OData collection. By using $expand, we can get related entities inline in response.
$select: It’s used if we wanted to include subset of properties in response instead of all.
$value: It allows to return raw value of the property instead returning in OData format.
Continue Reading →

AngularJS Deferred & Promises

When you have started working on AngularJS. You have to deal with the asynchronous call. you must come to know $http and $resource services. These both services are used to get server side data asynchronously. To handle an asynchronous call, you need to define callbacks. Deferred-Promises is a design pattern which helps you to deal with these callbacks.

It is not a problem to work with $http/ $resource. The real problem arise when you have to deal with multiple callbacks which are dependent on each other.

Promise In Angularjs- $q Service

Promises in AngularJS is provided by $q service. $q service is a service that helps you to run your code asynchronously.

Deferred Object: Deferred is an object which exposes the promise. It has  mainly three methods resolve(), reject(), and notify(). Deferred returns promise object. When Deferred completes, You call methods either resolve(), reject(), and notify() . It calls callback register to either resolve(), reject(), or notify() according to how it has completed.


function sayHelloAsync(name) {
    return function () {
        var defer = $q.defer()
        setTimeout(function() {
            //Greet when your name is 'deepak'
            if (name == 'deepak') {
                defer.resolve('Hello, ' + name + '!');
            }
            else {
                defer.reject('Greeting ' + name + ' is not allowed.');
            }
        }, 1000);
        return defer.promise
    }   

Promise Object: A promise is an object which is return by a Deferred object. You can register different callbacks for different events resolve(), reject(), or notify() and it will execute when the async function has completed.


var helloPromise = sayHelloAsync('deepak');
helloPromise.then(function (data) {
    console.log(data);
}, function (error) {
    console.error(data);
})   

Promise API
A new promise is created when you create a defer. You can get the instance of promise object by defer.promise. It is used to getting the result of the defer when a promise has completed. There are three events where you can bind your listeners.

Some other useful features- $q.all()
$q.all() is one of the method that i use more frequently. $q.all accepts array of promises as argument. Once all of the promises get completed. you will get the result in callback function as array of results.


var promise1 = $http({method: 'GET', url: '/api-one-url', cache: 'true'});
var promise2 = $http({method: 'GET', url: '/api-two-url', cache: 'true'});
$q.all([promise1, promise2])
    .then(function(data){
        console.log(data[0], data[1]);
    });

Continue Reading →

Tuesday, 4 July 2017

AngularJS Life Cycle

An Overview of the AngularJS Life Cycle
Now that you understand the components involved in an AngularJS application, you need to understand what happens during the life cycle, which has three phases: bootstrap, compilation, and runtime. Understanding the life cycle of an AngularJS application makes it easier to understand how to design and implement your code.
The three phases of the life cycle of an AngularJS application happen each time a web page is loaded in the browser. The following sections describe these phases of an AngularJS application.

The Bootstrap Phase
The first phase of the AngularJS life cycle is the bootstrap phase, which occurs when the AngularJS JavaScript library is downloaded to the browser. AngularJS initializes its own necessary components and then initializes your module, which the ng-app directive points to. The module is loaded, and any dependencies are injected into your module and made available to code within the module.

The Compilation Phase
The second phase of the AngularJS life cycle is the HTML compilation stage. Initially when a web page is loaded, a static form of the DOM is loaded in the browser. During the compilation phase, the static DOM is replaced with a dynamic DOM that represents the AngularJS view.
This phase involves two parts: traversing the static DOM and collecting all the directives and then linking the directives to the appropriate JavaScript functionality in the AngularJS built-in library or custom directive code. The directives are combined with a scope to produce the dynamic or live view.

The Runtime Data Binding Phase
The final phase of the AngularJS application is the runtime phase, which exists until the user reloads or navigates away from a web page. At that point, any changes in the scope are reflected in the view, and any changes in the view are directly updated in the scope, making the scope the single source of data for the view.
AngularJS behaves differently from traditional methods of binding data. Traditional methods combine a template with data received from the engine and then manipulate the DOM each time the data changes. AngularJS compiles the DOM only once and then links the compiled template as necessary, making it much more efficient than traditional methods.


x
Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives