Wednesday, April 29, 2015

Centralize client side exception handling mechanism in AngularJS

Exception handling feature is common in all web application. If you are ASP.NET developer then probably you have used some kind of filter in Global or Controller level to implement centralize exception handling mechanism. It’s fine when we want to handle exception in server.

But let’s think one situation where some kind of framework (read AngularJS) has used to make http call (ajax) and we have to handle server exception in client side.

Now, let me explain real problem, which I face few days ago. I used Authorizatin filter to check authorization of user and my client code was based on AJAX call, so there was no post back at all. When session was time out IIS simply throws 401(unauthorized) exception and I started to capture this in each and every AJAX call and I did not accept this practice from my heart.

So, started to think to implement something using AngularJS where I can handle all exception in one place.  Here is the solution for it.

var myApp = angular.module("myApp", []);

This is definition of module and now we will use interceptors to capture response from server in AJAX call and from here we will return promise.

myApp.config(['$httpProvider', function ( $httpProvider) {


            $httpProvider.interceptors.push(function ($q, $rootScope) {
                return {
                    'responseError': function (rejection) {
                        var status = rejection.status;
                        var config = rejection.config;
                        var method = config.method;
                        var url = config.url;

                        if (status == 401) {
                            //Handle unauthorize error
                            alert('Unauthorize');
                        } else {
                            //Handle other errors
                        }

                        return $q.reject(rejection);
                    }
                };
            });
}]);

This is pretty simple and clean . Now, we will implement one simple controller to perform AJAX call. Here is sample code.

myApp.controller('myController', function ($scope, $http, $q) {

            $http({ method: 'GET', url: '../Home/Process', cache: 'true' }).
                then(function (data) {
            });
           
        });


And here is action within Home Controller.

public class HomeController : Controller
    {
       [Authorize]
        public string Process()
        {
            throw new Exception("Error");
        }
}


Just have a look on Process() action and we will see that it has decorated with Authorize action filter that mean if the user is not authorize then server will throw 401 error.


Most likely, you may redirect user to login page in this situation or some other generic page in case of other error.

Tuesday, April 28, 2015

Auto mapper to map domain object gracefully in .NET


In application development, we often implementing mapping between DTO object and ViewModel object if it is MVC application. We know that DTO model is very similar to table stricture where ViewModel is very much similar to user interface.

Now, Question is that how we can map two different objects. The straightforward way to implement mapping is just to map property to property. Using AutoMapper we can make it little bit smart.
To use auto mapper we have to get reference of AutoMapper.NET4 assembly which we can get from NuGet package manager.
So, let’s implement AutoMapper in one sample application. Here is the implementation of person and Address class.

class person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public Address Address { get; set; }
    }

    class Address
    {
        public string State { get; set; }
        public string Cuntry { get; set; }
    }

Please have a look that “Address” member of person class is type of Address class. Now, the simplest view model to get full information of person is like this.

class personViewModel
    {
        public string FullName { get; set; }
        public Address Address { get; set; }
    }

Here, we will write few lines of code to map two objects.

public ActionResult Index()
        {
            var person = new person { FirstName = "Sourav", LastName = "Kayal", Address = new Address { State = "WB", Cuntry = "IN" } };
            personViewModel personVM = new personViewModel();

            Mapper.CreateMap<person,personViewModel>();
           
            Mapper.CreateMap<person,personViewModel>().
                ForMember(f=>f.FullName , f=>f.MapFrom(a=>a.FirstName + a.LastName));


            var data = Mapper.Map<person, personViewModel>(person);


            return View();
        }



Here we are seeing that Full name is the combination of both FirstName and LastName. 


And Address property has mapped automatically.




Monday, April 20, 2015

Find Who am I ? By Drg Dresya Viveka- Shankaracharya



We materialistic people works whole day to make our life easy and smooth. The lesion has taught to us from day 1 of our academic education and by parents at home (at least in INDIAN middle class family). However, the question is what is purpose of life?



Let us discuss the purpose of life in the light of Indian Vedanta and scriptures. Vedanta is saying that there are four purposes of human life. So, life seeks those four things. We will define those four purposes in Vedic view and we will try to understand the literal meaning of those.

   1) Kama - The word literally mean “Desire”. It may bring pleasure in life immediately. Say for example, my aim is to get good job in good MNC and when I get it, I am very happy. I have fulfilled my Kama. However, keep in mind that, this kind of enjoyment last least in life. Once my kama finished the happiness goes off. It bases on intension and closer to personal need.

  2) Artha – Literal meaning of Artha is “Engagement”. The job/work which you really love to do it. It’s not important that it will give you pleasure immediately but surely at certain time. The profound example of Artha might goes like this , You like to help people or like to teach poor children in your free time. It may not give in time pleasure during your job but you will feel happiness when you will think about it, after many days. So may bring certain meaning in your life. You will feel more happiness than “kama”

   3) Dharma – This is very much closure to meaningful life. It teaches the meaning of life. Now people may think this in different prospective. Someone may think that I will dedicate my entire life for because of other’s goodness, where someone may not.

Now, the point to say in this context is that, all those three are for your happiness. When I get something you fulfill your desire(Kama), you are happy for some moment. When you find Artha in your life you are more happier than the first one, I mean happiness will last longer than “Kama”. When you find meaning f your life (Dharma) ,you are even more happy than “Artha”.

   4) Moksha – To know “Who am I?” and by knowing this you happy entire your life.
In this article we will try to understand the concept of who am I by going through a sloka of Sankaracharya who is famous commentator of Advaita Vedanta. The title of the sloka is “Drg Dresya Viveka”. Let’s understand the title at first, the meaning of those 3 Sanskrit words are.

Drg : Witness/Viewer or one who seen

Drisya : Form/View/ Scenario / Known

Viveka: Separation / Discrimination

To understand the real meaning of this sloka, you have to follow it by only reading it’s not possible. You have to practice this.
Ok, here is very very important point to remember before going to sloka.

  1) Viewer and View must be different: It is in obvious reason. Say for example, I am seeing one car in street. So, car and I am separate.

  2) View might be in different form but viewer is one. Again, this is very simple to follow. There might be 10 different cars in road but I am the same.  
So, we will keep those points in mind during our journey. Here is the sloka in Sanskrit. The first line is

Rupam Drisham , lochonom drk

 Meaning of this line is : Rupam, means Forms or objects. Drisham ,means scenario. So the meaning of “Rupam Drisham” is objects are making scenario. Meaning of “lochonom” is eye and meaning of “drk” is witness. So the meaning of whole line is : Objects are forming scenario and my eyes are witness of this.
Now, apply the first rule on this. Viewer and view must be different. Ok, the objects are different from my eyes. Therefore, my eyes are the knower and forms are known. Here is next line.

Tad Drishram Driktumanasam

Meaning of this line is : “Tad” means That. Meaning is “Drishram” is view. The word “Driktumanasam” implies your mind. So, meaning of whole line is “Your mind is witness of your eyes”. And the discussion is very simple and easy to follow. When we see very nice sight, we became happy I mean our mind became happy. When we watch something sorrowful, we feel sad in our mind. That is why it’s saying that our mind is witness of our eyes.
And again , here is first principal holds. Viewer and view must be different. Therefore, our mind is different from our eyes.

Drishodhibrittoyo sakshi

Meaning of “Drishodhibrittoyo” is Changing of mind and the meaning of “sakshi” is Viewer. So, something is there who is seeing my mind.
We have to understand this section pretty well. Something/someone is there who is (sakshi) seeing my mind ! Who is seeing my mind? Who is “Sakshi”? I am seeing my mind. Because I know when my mind is happy, I know when my mind is unhappy; I know when my mind is in stress.
 So, I am the witness of my mind and by applying first rule I and my mind are different. If I, and my mind are different. Then where is “I” in my body?
So, the Idea at the end of this line is , You are not Forms, you are not objects, you are not eyes , you are not mind but you are something who is seeing your mind and you physically detached to your mind.
Now, Idea comes like this. If you think, “I am happy” then you are not happy! You are the viewer of your happy mind. If you think that you are in sorrow, then you are not in sorrow! You are the viewer of your sorrowful mind.
And the sloka ends like this.

Dreg e banatu drishotte

Meaning of this whole line is “The sakshi is never known”. So, there is nothing which is seeing You. The complete darkness.
So, whole process culminates that there is one sub-conscious mind which is viewing your mind and that is who you are!
  


Friday, April 10, 2015

Various Extension points of ASP.NET MVC with real time example

Current software industry has adapted MVC pattern hugely, not only in Microsoft’s stack but also in Other like PHP ,ruby on Rails etc.















Let’s stick on MVC on top of Microsoft’s platform as I am .NET developer and love Microsoft’s technology to develop application. We all know, ASP.NET MVC has many advantages which made this booming technology in market. As per my view the first and most strongest point of MVC is it’s architecture, yes the decouple architecture.

The Idea behind the decouple architecture is to make it flexible in extreme level. If we see the complete flow of request in MVC pipeline, we will see that the request is going through various modules and the modules are independent.

I mean we can easily detach/attach any module in pipeline. Now, question is what is my profit by attaching or detaching module?
  • If we detach any module, the execution flow may speed up because the path will      decrease.
  • We can attach our own module to implement our custom behavior which will override the normal flow of execution.  

The last point is very important, In MVC we can easily inject our own logic in middle of execution and the concept of extensibility comes here.

Being a software developer, we believe and follow one guideline that is “Module is open for extension but close for modification”. It means we can extend the functionality of a module but should not modify functionality of module. So that we will find various extension point of MVC and implement out custom logic there.

Now, let us try to analyze MVC pipeline to detect various extensibility point and we will relate some real time scenario to understand the need of extensibility.
At a very high level, the lifecycle of a request in ASP.NET MVC is:

  •      The browser sends the GET or POST HTTP request to application;


  • The request is inspected and routed to the right controller and the right action;


  • The action collects or creates the data that needs to be returned to the browser very often from DB or other sources;

  • This data is passed to the view that renders the response, which is sent back to the browser.


In time of Routing

This is one good extension point where we can implement our own custom logic. There is once default routing pattern, which is given by Microsoft, but in need we can implement our own custom routing mechanism.

Once the Route has been selected, the corresponding IRouteHandler is called. The default one calls the MvcHandler, which starts the real processing inside ASP.NET MVC. Obviously, if you replace the default handler with something completely different, you also take over the processing of the request, and so all the steps that follow might not apply anymore.

Real time Example: Say for example we want to set route constraint in url path , then we can implement our custom logic to get it done. Another example is to implement dynamic routing which will get generate from Database or some other data source.

Delegating handler

If you are experienced with HttpHandler and HttpModule then probably you know how to inject your code in this section. This is MVC pipeline which executes after route initialization/selection. This is one good place to implement security in application.

Real time scenario: If you want to implement our own piece of code to implement authentication or authorization then this is the best place to do. You can sniff header of HTTP request and based on that you can make decision whether you will allow the request to next level or not?

Controller selection
Rather I would say before selection of controller. Based on route pattern and parameter IControllerFactory creates an instance of a controller and in this point, we can inject our IoC container to solve the dependency of controller

Real time scenario : For example ,we want to inject the dependency of controller in our application and for that we have adapted constructor injection pattern. For that we can create one dependency repository using any IoC container and can inject this in time of controller instantiation. The IoC container module is smart enough to handle this automatically.  

In time of Action execution
Once the controller has been instantiated, the specified action has to be executed, and this is handled by the IActionInvoker. As with the IRouteHandler, in theory you could completely replace this component with your own implementation, but then you will be developing 
against your own conventions. So, there is scope to inject our own logic before and after of action execution in technical tern which is called Action Filter.

There are 5 types of Action filters and those are
  • ·         Authentication (added in MVC 5)
  • ·         Authorization
  • ·         Action Filter
  • ·         Result Filter
  • ·         Exception Filter

 In need can extend each and every filter and implement our custom action filter
 Real time scenario: For example, you want to implement global error handling mechanism in your application. For same you can create one action filter and can decorate your controller with the filter.

Implement your Own view Engine
There are many action results: one simply returns a text string, another returns a binary file or a Json formatted result. Yet the most important Action Result is the ViewResult, which renders and returns an HTML page to the browser.

We know that the HTML processing happens in view engine and if you want you can create your own View engine to render HTML page

Real time scenario: There are many third party view engine in market other than ASPX and Razor view engine. They has their own mechanism to render view, In need you too can create your own view engine with your own HTML tag set.

So, those are few very important and popular extensibility point of ASP.NET MVC where you can get your magic done!