Shadman Kudchikar

AngularJS Service

AngularJS Service

Contents

What are Services in Angularjs?

Angularjs Services are functions or objects that contains reusable code that can get consumed accross app by controllers, directives, filters and other services using Dependency Injection Mechanism of Angularjs.

These are also called as singletons, which are the objects that are instantiated only once per application.

Services provide a method for us to keep data around the lifetime of the app and communicate across controllers in a consistent manner.

Why use Services in Angularjs?

Writing your own services is a great way to implement reusable code and they’re the perfect place to capture the logic specific to your application.

Following are its uses:

Real World Example

The most simple example I could come up with is alert service or notifier service, consider you are using routing and ng view in your angular app and you want to send classic bootstrap alert box in your main index controller outside of your route controller, than creating a alert service that get consumed by both controller can solve this problem.

Below is the sample code.

angular.module('app')
    .factory('alertService', function ($interval) {

        return  {
            alerts: [], 

            addAlert: function addAlert(icon,type, title, message, timeout) {
                var alert = {
                    icon: icon,
                    type: type,
                    title: title,
                    message: message
                };
                this.alerts.push(alert);

                var serv = this;

                $interval(function () {
                    var alertIndex = serv.alerts.findIndex(function (a) { return a == alert });
                    if (alertIndex > -1) {
                        serv.alerts.splice(alertIndex, 1);
                    }                    
                }, timeout, 1);
            },

            addDanger: function addDanger(title, message, timeout = 3000) {
                this.addAlert("fa-ban","alert-danger", title, message, timeout);
            },
            addWarning: function addWarning(title, message, timeout = 3000) {
                this.addAlert("fa-warning","alert-warning", title, message, timeout);
            },
            addInfo: function addInfo(title, message, timeout = 3000) {
                this.addAlert("fa-info","alert-info", title, message, timeout);
            },
            addSuccess: function addSuccess(title, message, timeout = 3000) {
                this.addAlert("fa-check", "alert-success", title, message, timeout);
            },
        }

    });

Asp.NET MVC 5 Request Life Cycle and Application Events

Asp.NET MVC Request Life Cycle and Application Events

Contents

Introduction

From getting client request to sending a response, the Asp.NET MVC lifecycle is bit complex. This lifecycle is totally different from old Asp.NET Webforms. As the page in Webforms has page lifecycle many people compare this with Asp.NET MVC lifecycle which is totally a different thing.

The thing is Asp.NET MVC and Webforms are both implemented using HttpHandlers over Asp.NET and the way they respond to request is different based on their implementation. Usually in Webforms the url points to aspx page which get processed and generate response. However, MVC is bit indirect in this process. In MVC, url gets routed to specific controller and action methods to generate a response.

MVC Request Life Cycle

The module and handler are the entry points to the ASP.NET MVC framework. Requests to an ASP.NET MVC-based Web application first pass through the UrlRoutingModule object, which is an HTTP module. This module parses the request and performs route selection. From the selected Route object, the UrlRoutingModule object obtains the IRouteHandler object that is associated with the Route object. Typically, in an MVC application, this will be an instance of MvcRouteHandler. The IRouteHandler instance creates an IHttpHandler object and passes it the IHttpContext object. By default, the IHttpHandler instance for MVC is the MvcHandler object. The MvcHandler object then selects the controller that will ultimately handle the request.

Learn more about Asp.NET MVC Request Life Cycle conceptually from this well documented article.

You can download a PDF document from here that charts the lifecycle of every ASP.NET MVC 5 application, from receiving the HTTP request to sending the HTTP response back to the client.

Http Application Class

The MVCApplication class in Global.asax file inherits HttpApplication class.

public class MvcApplication : System.Web.HttpApplication

Http Application Class defines the methods, properties, and events that are common to all application objects in an ASP.NET application. This class is the base class for applications defined by the user in the Global.asax file.

HttpApplication class has number of application and request level events which you can override.

public class MvcApplication : System.Web.HttpApplication
{

    protected void Application_Start(object sender, EventArgs e)
    {
    }

    protected void Application_BeginRequest(object sender, EventArgs e)
    {        
    }

    protected void Application_EndRequest(Object sender, EventArgs e)
    {
    }

    protected void Application_Error(object sender, EventArgs e)
    {
    }

    protected void Application_End(object sender, EventArgs e)
    {
    }

}

You can get complete list of events you can override in HttpApplication class here. Refer this article by Scott Allen to know how to use this events.

MVC Request lifecycle contains events like Appliication Start and Application End which we can configure in Global.asax file. However, we sometimes need to execute some custom code before all this events take place in the first place, like registering a HttpModule. In that case we can use PreApplicationStart method to register this HttpModules.

The PreApplicationStart method is defined at the assembly level using an attribute. We can define the name of a type as well as a method on that type that we want to run before our application starts. Below is the example,

[assembly: PreApplicationStartMethod(typeof(PreApplicationStart), "Start")]

You can learn more about how this application events works here.

Working with Events Across Frameworks Using HttpModules

As I mentioned earlier both Webforms and MVC frameworks uses HttpModule and HttpHandler for their request and response pipeline. We are interested in HttpModule here. We can set any number of HttpModules in an ASP.NET Http request and response pipeline. One of the greatest feature of ASP.Net Application Life Cycle that its events can be accessed across frameworks. ASP.NET application whether it’s built on MVC or not. In fact, we can have two applications running side by side using different frameworks and still leverage the same life cycle events. For example, you could have a webforms application and an MVC application running side by side. You could then build an HttpModule to hook into the same life cycle events for both and perform some common tasks.

public class HelloWorldModule : IHttpModule
{
    public HelloWorldModule()
    {
    }

    // In the Init function, register for HttpApplication 
    // events by adding your handlers.
    public void Init(HttpApplication application)
    {
        application.BeginRequest += 
            (new EventHandler(this.Application_BeginRequest));
        application.EndRequest += 
            (new EventHandler(this.Application_EndRequest));
    }

    private void Application_BeginRequest(Object source, EventArgs e)
    {
   
    }

    private void Application_EndRequest(Object source, EventArgs e)
    {
        
    }
}

You can learn more about various events and their execution sequence in an ASP.NET application using HttpModule here.

References