Monday, 18 May 2015

AngularJS Service / Factory With Example

1. Introduction to AngularJS Services

In AngularJS world, the services are singleton objects or functions that carry out specific tasks. It holds some business logic. Separation of concern is at the heart while designing an AngularJS application. Your controller must be responsible for binding model data to views using $scope. It does not contain logic to fetch the data or manipulating it.
For that we must create singleton objects called services. AngularJS can manage these service objects. Wherever we want to use the service, we just have to specify its name and AngularJS auto-magically inject these objects (more on this later).
Thus service is a stateless object that contains some useful functions. These functions can be called from anywhere; Controllers, Directive, Filters etc. Thus we can divide our application in logical units. The business logic or logic to call HTTP url to fetch data from server can be put within a service object.
Putting business and other logic within services has many advantages. First it fulfills the principle of separation of concern or segregation of duties. Each component is responsible for its own work making application more manageable. Second this way each component can be more testable. AngularJS provides first class support for unit testing. Thus we can quickly write tests for our services making them robust and less error prone.

Consider above diagram. Here we divide our application in two controllers: 1. Profile and 2. Dashboard. Each of these controllers require certain user data from server. Thus instead of repeating the logic to fetch data from server in each controller, we create a User service which hides the complexity. AngularJS automatically inject User service in both Profile and Dashboard controller. Thus our application becomes for modular and testable.

2. AngularJS internal services
AngularJS internally provides many services that we can use in our application. $http is one example (Note: All angularjs internal services starts with $ sign). There are other useful services such as $route,$window, $location etc.
These services can be used within any Controller by just declaring them as dependencies. For example:
module.controller('FooController', function($http){
    //...
});
module.controller('BarController', function($window){
    //...
});

3. AngularJS custom services
We can define our own custom services in angular js app and use them wherever required.
There are several ways to declare angularjs service within application. Following are two simple ways:
var module = angular.module('myapp', []);
module.service('userService', function(){
    this.users = ['John', 'James', 'Jake'];
});
or we can use factory method
module.factory('userService', function(){
     
    var fac = {};
     
    fac.users = ['John', 'James', 'Jake'];
     
    return fac;
});
Both of the ways of defining a service function/object are valid. We will shortly see the difference between factory() and service() method. For now just keep in mind that both these apis defines a singleton service object that can be used within any controller, filter, directive etc.
4. AngularJS Service vs Factory
AngularJS services as already seen earlier are singleton objects. These objects are application wide. Thus a service object once created can be used within any other services or controllers etc.
We saw there are two ways (actually four, but for sake of simplicity lets focus on 2 ways that are widely used) of defining an angularjs service. Using module.factory and module.service.
module.service( 'serviceName', function );
module.factory( 'factoryName', function );
When declaring serviceName as an injectable argument you will be provided with an instance of the function. In other words new FunctionYouPassedToService(). This object instance becomes the service object that AngularJS registers and injects later to other services / controllers if required.
When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.
In below example we define MyService in two different ways. Note how in .service we create service methods using this.methodname. In .factory we created a factory object and assigned the methods to it.

AngularJS .service

module.service('MyService', function() {
    this.method1 = function() {
            //..
        }
    this.method2 = function() {
            //..
        }
});

AngularJS .factory

module.factory('MyService', function() {
     
    var factory = {};
    factory.method1 = function() {
            //..
        }
    factory.method2 = function() {
            //..
        }
    return factory;
});
5. Injecting dependencies in services

Angularjs provides out of the box support for dependency management.
In general the wikipedia definition of dependency injection is:
Dependency injection is a software design pattern that allows the removal of hard-coded dependencies and makes it possible to change them, whether at run-time or compile-time. …
We already saw in previous tutorials how to use angularjs dependency management and inject dependencies in controllers. We injected $scope object in our controller class.
Dependency injection mainly reduces the tight coupling of code and create modular code that is more maintainable and testable. AngularJS services are the objects that can be injected in any other Angular construct (like controller, filter, directive etc). You can define a service which does certain tasks and inject it wherever you want. In that way you are sure your tested service code works without any glitch.
Like it is possible to inject service object into other angular constructs, you can also inject other objects into service object. One service might be dependence on another.
Let us consider an example where we use dependency injection between different services and controller. For this demo let us create a small calculator app that does two things: squares and cubes. We will create following entities in AngularJS:
  1. MathService – A simple custom angular service that has 4 methods: add, subtract, multiply and divide. We will only use multiply in our example.
  2. CalculatorService – A simple custom angular service that has 2 methods: square and cube. This service has dependency on MathService and it uses MathService.multiply method to do its work.
  3. CalculatorController – This is a simple controller that handler user interactions. For UI we have one textbox to take a number from user and two buttons; one to square another to multiply.
Below is the code:

5.1 The HTML

<div ng-app="app">
    <div ng-controller="CalculatorController">
        Enter a number:
        <input type="number" ng-model="number">
        <button ng-click="doSquare()">X<sup>2</sup></button>
        <button ng-click="doCube()">X<sup>3</sup></button>
         
        <div>Answer: {{answer}}</div>
    </div>
</div>

5.2 The JavaScript

var app = angular.module('app', []);
app.service('MathService', function() {
    this.add = function(a, b) { return a + b };
     
    this.subtract = function(a, b) { return a - b };
     
    this.multiply = function(a, b) { return a * b };
     
    this.divide = function(a, b) { return a / b };
});
app.service('CalculatorService', function(MathService){
     
    this.square = function(a) { return MathService.multiply(a,a); };
    this.cube = function(a) { return MathService.multiply(a,
    MathService.multiply(a,a));};
});
app.controller('CalculatorController', function($scope, CalculatorService) {
    $scope.doSquare = function() {
        $scope.answer = CalculatorService.square($scope.number);
    }
    $scope.doCube = function() {
        $scope.answer = CalculatorService.cube($scope.number);
    }
});

Reference: Click here
Continue Reading →

Friday, 15 May 2015

Custom Forms Authentication and Authorization in ASP.NET MVC Application

Introduction
In this we will discuss about the ASP.NET Roles and Membership API from MVC perspective. We will see how we can implement custom forms authentication in an ASP.NET MVC application. 

Authentication and Authorization
Authentication means validating users. In this step, we verify user credentials to check whether the person tying to log in is the right one or not. Authorization on the other hand is keeping track of what the current user is allowed to see and what should be hidden from him. It is more like keeping a register to what to show and what not to show to the user.

Whenever a user logs in, he will have to authenticate himself with his credentials. Once he is authenticated, he will be authorized to see resources/pages of the website. Mostly these two concepts go together.

Type of Authentications
Before moving ahead, let us first see the two main type of authentications that are used mostly in ASP.NET applications.

Windows authentication: In this mode, the users are authenticated on their Windows username and password. This method is least recommended in an internet scenario. In an internet scenario, we should always use "Forms based authentication".
Forms based authentication: In this type of authentication, the user will explicitly have to provide his credentials and these credentials, once verified by the server, will let the user to log in.

We will be discussing the form authentication in details in the rest of the article.

Forms Authentication
To enable forms authentication we need to perform following steps in our application.
Configure the application to use Forms Authentication.
Create a login page.
Whenever a user tries to access the restricted area, push him to the Login page.
When the user tries to login, verify his credentials using the database.
If the login is successful, keep the username and his Roles in a Session variable to use it further.
Create an authentication ticket for the user (an encrypted cookie). We can have this persistent or non persistent.

Facilitate the User/Roles extraction using the authentication ticket.
Custom Forms Authentication:

To implement our own authentication and authorization mechanism we will have take care of implementing all the steps required for forms authentication that we discussed earlier in the article. So let us create an empty MVC4 application and see how we can implement custom forms authentication.

Configuring Forms Authentication

Now the first thing that we need to do is to configure the application to use the Forms authentication. This can be done in the web.config file.

<authentication mode="Forms">
      <forms loginUrl="~/Login/Index" timeout="2880" />

</authentication>

Preparing the user Database
Let us now create a small database that we will use to perform authentication. 



Now to perform data access let us use entity framework so that we don't have to write all the boilerplate code required to create our model and data access logic. The generated entity for our database will look like:

Creating the Controllers and Views
let us now go ahead and create a controller that will take care of the authentication logic. We will create the functionality for Login and Logout but other functionality are user creation and password change can be easily implemented on same lines(its the matter of validating the user Model and performing CRUD operations on the table after encryption or hashing and salting).

Here is our controller with login and logout action:
public ActionResult Index()
{
    ViewBag.Title = "Login";
    return View();
}

[HttpPost]
public ActionResult Index(User model, string returnUrl)
{
    // Lets first check if the Model is valid or not
    if (ModelState.IsValid)
    {
        using (SampleDbEntities entities = new SampleDbEntities())
        {
            string username = model.UserName;
            string password = model.Password;

            // Now if our password was enctypted or hashed we would have done the
            // same operation on the user entered password here, But for now
            // since the password is in plain text lets just authenticate directly

bool userValid = entities.Users.Any(user => user.UserName == username && 
user.Password == password);

            // User found in the database
            if (userValid)
            {
                FormsAuthentication.SetAuthCookie(username, false);
                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && 
returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") &&
!returnUrl.StartsWith("/\\"))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
     ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

public ActionResult LogOff()
{
    FormsAuthentication.SignOut();
    return RedirectToAction("Index", "Login");
}

Now in the above code when the user tries to login we will check if the user with the given user credentials exist in the user database or not. If it exist we set the authentication ticket and move forward. Now if our password was encrypted or hashed we would have done the same operation on the user entered password before checking in database, but since the password is in plain text lets just authenticate directly.

Now before moving ahead let us look at the view that will take the user credentials and perform the authentication.



Let us now create a simple Controller which will contain actions which can be accessed by specified Roles and Users.

Facilitating Roles extraction using the authentication ticket
Now to use the roles specified in our database, there is one thing to understand. When Forms authentication is being used, whenever the need for authentication arises, the ASP.NET framework checks with the current IPrinciple type object. The user ID and Role contained in this IPrinciple type object will determine whether the user is allowed access or not.

So far we have not written code to push our user's Role details in this principle object. To do that we need to override a method called FormsAuthentication_OnAuthenticate in global.asax. This method is called each time ASP.NET framework tries to check authentication and authorization with respect to the current Principle.

What we need to do now is to override this method. Check for the authentication ticket (since the user has already been validated and the ticket was created) and then supply this User/Role information in the IPrinciple type object. We can implement our custom Principle type too but to keep it simple, we will simply create a GenericPriciple object and set our user specific details into it

 Now we have all the steps required to implement the custom forms authentication in place. We have successfully implemented custom forms authentication in an ASP.NET MVC application.
   Now run your Application . without login click on About or Click on Contact Link , it will redirect you to the Login Page. Login with admin, you can not access About and Contact Page because I have'nt Provided Access to Admin for these Pages. now login with user or guest you can access About Page but not Contact Page. Login with hr you can not access About and Contact Page. now Login with hr2 now you can access Contact Page because I have Provided Access to only hr2 with HR Role.

Note: This article contains code snippets that are only for demonstration of concepts of the article and it does not follow any best practices .

Click here to Download Project
 This article has been written from a beginner's perspective. hope this has been informative. leave a comment if you liked it.
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