Saturday, 28 May 2016

AngularJS - Part 3

Before continuing this, please refer Angular JS- Part 2

AngularJS – Controllers

In Angular, a Controller is defined by a JavaScript constructor function that is used to augment the Angular Scope.
When a Controller is attached to the DOM via the ng-controller directive, Angular will instantiate a new Controller object, using the specified Controller's constructor function. A new child scope will be created and made available as an injectable parameter to the Controller's constructor function as $scope.
If the controller has been attached using the controller as syntax then the controller instance will be assigned to a property on the new scope.
<div ng-app = "" ng-controller = "studentController">
   ...
</div>

AngularJS – Filters

A filter formats the value of an expression for display to the user. They can be used in view templates, controllers or services and it is easy to define your own filter.
The underlying API is the filterProvider.

Using filters in view templates

Filters can be applied to expressions in view templates using the following syntax:
{{ expression | filter }}
Following is the list of commonly used filters:-
Sr.No. Name Description
1 uppercase converts a text to upper case text.
2 lowercase converts a text to lower case text.
3 currency formats text in a currency format.
4 filter filter the array to a subset of it based on provided criteria.
5 orderby orders the array based on provided criteria.

uppercase filter

Add uppercase filter to an expression using pipe character. Here we've added uppercase filter to print student name in all capital letters.
Enter first name:<input type = "text" ng-model = "student.firstName">
Enter last name: <input type = "text" ng-model = "student.lastName">
Name in Upper Case: {{student.fullName() | uppercase}}

 

lowercase filter

Add lowercase filter to an expression using pipe character. Here we've added lowercase filter to print student name in all lowercase letters.
Enter first name:<input type = "text" ng-model = "student.firstName">
Enter last name: <input type = "text" ng-model = "student.lastName">
Name in Upper Case: {{student.fullName() | lowercase}}

 

currency filter

Add currency filter to an expression returning number using pipe character. Here we've added currency filter to print fees using currency format.
Enter fees: <input type = "text" ng-model = "student.fees">
fees: {{student.fees | currency}}

 

filter filter

To display only required subjects, we've used subjectName as filter.
Enter subject: <input type = "text" ng-model = "subjectName">
Subject:
<ul>
  <li ng-repeat = "subject in student.subjects | filter: subjectName">
     {{ subject.name + ', marks:' + subject.marks }}
  </li>
</ul>

 

orderby filter

To order subjects by marks, we've used orderBy marks.
Subject:
<ul>
  <li ng-repeat = "subject in student.subjects | orderBy:'marks'">
     {{ subject.name + ', marks:' + subject.marks }}
  </li>
</ul>

 

AngularJS – Tables

Table data is normally repeatable by nature. ng-repeat directive can be used to draw table easily. Following example states the use of ng-repeat directive to draw a table.
<table>
   <tr>
      <th>Name</th>
      <th>Marks</th>
   </tr>
   <tr ng-repeat = "subject in student.subjects">
      <td>{{ subject.name }}</td>
      <td>{{ subject.marks }}</td>
   </tr>
</table>

 <<Angular JS- Part 2                                    Angular JS- Part 4>>

AngularJS - Part 2

Before continuing this, please refer AngularJS - Part 1


AngularJS Components

The AngularJS framework can be divided into following three major parts −
  • ng-app − This directive defines and links an AngularJS application to HTML.
  • ng-model − This directive binds the values of AngularJS application data to HTML input controls.
  • ng-bind − This directive binds the AngularJS Application data to HTML tags.

 

AngularJS page life cycle  

 

Component of Angular Description
Module Modules serve as containers to assist in organizing code within your AngularJs application. Modules can contain sub-modules.
Services Services are a point where you can put common functionality to an AngularJs application. For example if you would like to share data with more than one controller then the best way is to promote that data to a service and then make it available via the service. Services extend controllers and make them more globally accessible.
Routes Routes allow us to determine ways to navigate to specific states within our application. It also allows us to define configuration options for each specific route, such as which template and controller to use.
View The view in AngularJs is what exists after AngularJs has compiled and rendered the DOM. It's a representation of whatever outcome from
@scope $scope is essentially the “glue” between the view and controller within an AngularJs application. And somewhere supports two-way binding within the application.
Controller The controller is responsible for defining methods and properties that the view can bind to and interact with. Controllers should be lightweight and only focus on the view they're controlling.
directive A directive is an extension of a view in AngularJs in that it allows us to create custom, reusable elements. You can also consider directives as decorators for your HTML. Directives are used to extend views and to make these extensions available for use in more than one place.
Config The config block of an AngularJs application allows for the configuration to be applied before the application actually runs. This is useful for setting up routes, dynamically configuring services and so on.
 

 

AngularJS directives

 

At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element (e.g. via event listeners), or even to transform the DOM element and its children.
AngularJS directives are used to extend HTML. These are special attributes starting with ng- prefix. We're going to discuss following directives −
  • ng-app − This directive starts an AngularJS Application.
  • ng-init − This directive initializes application data.
  • ng-model − This directive defines the model that is variable to be used in AngularJS.
  • ng-repeat − This directive repeats html elements for each item in a collection.

 

ng-app directive

ng-app directive starts an AngularJS Application. It defines the root element. It automatically initializes or bootstraps the application when web page containing AngularJS Application is loaded. It is also used to load various AngularJS modules in AngularJS Application. In following example, we've defined a default AngularJS application using ng-app attribute of a div element.
<div ng-app = "">
   ...
</div>

ng-init directive

ng-init directive initializes an AngularJS Application data. It is used to put values to the variables to be used in the application. In following example, we'll initialize an array of countries. We're using JSON syntax to define array of countries.
<div ng-app = "" 
ng-init = "countries = [{locale:'en-US',name:'United States'}, 
{locale:'en-GB',name:'United Kingdom'}, 
{locale:'en-FR',name:'France'}]">
   ...
</div>

ng-model directive

ng-model directive defines the model/variable to be used in AngularJS Application. In following example, we've defined a model named "name".
<div ng-app = "">
   ...
   <p>Enter your Name: <input type = "text" ng-model = "name"></p>
</div>

ng-repeat directive

ng-repeat directive repeats html elements for each item in a collection. In following example, we've iterated over array of countries.
<div ng-app = "">
   ...
   <p>List of Countries with locale:</p>
   <ol>
      <li ng-repeat = "country in countries">
         {{ 'Country: ' + country.name + ', Locale: ' + country.locale }}
      </li>
   </ol>
</div>

 

AngularJS - Custom Directives

 

Custom directives are used in AngularJS to extend the functionality of HTML. Custom directives are defined using "directive" function. A custom directive simply replaces the element for which it is activated. AngularJS application during bootstrap finds the matching elements and do one time activity using its compile() method of the custom directive then process the element using link() method of the custom directive based on the scope of the directive. AngularJS provides support to create custom directives for following type of elements.
  • Element directives − Directive activates when a matching element is encountered.
  • Attribute − Directive activates when a matching attribute is encountered.
  • CSS − Directive activates when a matching css style is encountered.
  • Comment − Directive activates when a matching comment is encountered

 

 

AngularJS – Expressions

 

Expressions are used to bind application data to html. Expressions are written inside double braces like {{ expression}}. Expressions behaves in same way as ng-bind directives. AngularJS application expressions are pure javascript expressions and outputs the data where they are used.

Using numbers

<p>Expense on Books : {{cost * quantity}} Rs</p>

 

Using strings

<p>Hello {{student.firstname + " " + student.lastname}}!</p>

 

Using object

<p>Roll No: {{student.rollno}}</p>
 

Using array

<p>Marks(Math): {{marks[3]}}</p>




<<Angular JS- Part 1                                          Angular JS- Part 3>>

Friday, 20 May 2016

AngularJS - Part 1

Introduction


AngularJS is a structural framework for dynamic web apps. 
AngularJS is an open source web application framework. It was originally developed in 2009 by Misko Hevery and Adam Abrons. It is now maintained by Google. Its latest version is 1.4.3.

Features

  • AngularJS is a powerful JavaScript based development framework to create RICH Internet Application(RIA).
  • AngularJS provides developers options to write client side application (using JavaScript) in a clean MVC(Model View Controller) way.
  • Application written in AngularJS is cross-browser compliant. AngularJS automatically handles JavaScript code suitable for each browser.
  • AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache License version 2.0.

Core Features

Following are most important core features of AngularJS −
  1. Data-binding − It is the automatic synchronization of data between model and view components.
  2. Scope − These are objects that refer to the model. They act as a glue between controller and view.
  3. Controller − These are JavaScript functions that are bound to a particular scope.
  4. Services − AngularJS come with several built-in services for example $http to make a XMLHttpRequests. These are singleton objects which are instantiated only once in app.
  5. Filters − These select a subset of items from an array and returns a new array.
  6. Directives − Directives are markers on DOM elements (such as elements, attributes, css, and more). These can be used to create custom HTML tags that serve as new, custom widgets. AngularJS has built-in directives (ngBind, ngModel...)
  7. Templates − These are the rendered view with information from the controller and model. These can be a single file (like index.html) or multiple views in one page using "partials".
  8. Routing − It is concept of switching views.
  9. Model View Whatever − MVC is a design pattern for dividing an application into different parts (called Model, View and Controller), each with distinct responsibilities. AngularJS does not implement MVC in the traditional sense, but rather something closer to MVVM (Model-View-ViewModel). The Angular JS team refers it humorously as Model View Whatever.
  10. Deep Linking − Deep linking allows you to encode the state of application in the URL so that it can be bookmarked. The application can then be restored from the URL to the same state.
  11. Dependency Injection − AngularJS has a built-in dependency injection subsystem that helps the developer by making the application easier to develop, understand, and test.

Why You Should Use AngularJS?


Most frameworks nowadays are simply a bundling of existing tools. They are an integrated tool set, but not very elegant. Angular is the next generation framework where each tool was designed to work with every other tool in an interconnected way.
Here are 10 reasons why you should be using Angular today.
  1. MVC done right
  2. A declarative user interface.
  3. Data models are POJO
  4. Behavior with directives
  5. Flexibility with filters
  6. Write less code
  7. DOM manipulations where they belong
  8. Service providers where they belong
  9. Context aware communication
  10. Unit testing ready

Advantages of AngularJS

  • AngularJS provides capability to create Single Page Application in a very clean and maintainable way.
  • AngularJS provides data binding capability to HTML thus giving user a rich and responsive experience
  • AngularJS code is unit testable.
  • AngularJS uses dependency injection and make use of separation of concerns.
  • AngularJS provides reusable components.
  • With AngularJS, developer write less code and get more functionality.
  • In AngularJS, views are pure html pages, and controllers written in JavaScript do the business processing.

Disadvantages of AngularJS

Though AngularJS comes with lots of plus points but same time we should consider the following points
  • Not Secure − Being JavaScript only framework, application written in AngularJS are not safe. Server side authentication and authorization is must to keep an application secure.
  • Not degradable − If your application user disables JavaScript then user will just see the basic page and nothing more.

Thursday, 19 May 2016

Asp.Net Web API

Introduction

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

It is very similar to ASP.NET MVC since it contains the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection. But it is not a part of the MVC Framework. It is a part of the core ASP.NET platform and can be used with MVC and other types of Web applications like Asp.Net WebForms. It can also be used as a stand-alone Web services application.


Why Asp.Net Web API (Web API) ?

 If you like to expose your service data to the browsers and as well as all modern devices apps in fast and simple way, you should have an API which is compatible with browsers and all devices.

Web API is the great framework for exposing your data and service to different-different devices. Moreover Web API is open source an ideal platform for building REST-ful services over the .NET Framework. Unlike WCF Rest service, it use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats) and you don't need to define any extra config settings for different devices unlike WCF Rest service.


Web API Features

  1.  It supports convention-based CRUD Actions since it works with HTTP verbs GET,POST,PUT and DELETE.
  2. Responses have an Accept header and HTTP status code.
  3. Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.
  4. It may accepts and generates the content which may not be object oriented like images, PDF files etc.
  5. It has automatic support for OData. Hence by placing the new [Queryable] attribute on a controller method that returns IQueryable, clients can use the method for OData query composition.
  6. It can be hosted with in the applicaion or on IIS.
  7. It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection that makes it more simple and robust.


Why to choose Web API ?

  1. If we need a Web Service and don’t need SOAP, then ASP.Net Web API is best choice.
  2. It is Used to build simple, non-SOAP-based HTTP Services on top of existing WCF message pipeline.
  3. It doesn't have tedious and extensive configuration like WCF REST service.
  4. Simple service creation with Web API. With WCF REST Services, service creation is difficult.
  5. It is only based on HTTP and easy to define, expose and consume in a REST-ful way.
  6. It is light weight architecture and good for devices which have limited bandwidth like smart phones.
  7. It is open source.


Asp.Net Web API VS Asp.Net MVC

  1. Asp.Net MVC is used to create web applications that returns both views and data but Asp.Net Web API is used to create full blown HTTP services with easy and simple way that returns only data not view.
  2. Web API helps to build REST-ful services over the .NET Framework and it also support content-negotiation(it's about deciding the best response format data that could be acceptable by the client. it could be JSON,XML,ATOM or other formatted data), self hosting which are not in MVC.
  3. Web API also takes care of returning data in particular format like JSON,XML or any other based upon the Accept header in the request and you don't worry about that. MVC only return data in JSON format using JsonResult.
  4. In Web API the request are mapped to the actions based on HTTP verbs but in MVC it is mapped to actions name.
  5. Asp.Net Web API is new framework and part of the core ASP.NET framework. The model binding, filters, routing and others MVC features exist in Web API are different from MVC and exists in the new System.Web.Http assembly. In MVC, these featues exist with in System.Web.Mvc. Hence Web API can also be used with Asp.Net and as a stand alone service layer.
  6. You can mix Web API and MVC controller in a single project to handle advanced AJAX requests which may return data in JSON, XML or any others format and building a full blown HTTP service. Typically, this will be called Web API self hosting.
  7. When you have mixed MVC and Web API controller and you want to implement the authorization then you have to create two filters one for MVC and another for Web API since boths are different.
  8. Moreover, Web API is light weight architecture and except the web application it can also be used with smart phone apps.