Master Page, User Control, Custom Control and Content page : Order of page life cycle event

As we all know that while serving an asp.net request goes through many stages before it gets served. One of the important stages is, going through the page life cycle events. As a page can contain many other controls like User Control, Custom control etc and it can be a combination of master and content pages as well. As each control has its own life cycle so if they are inter weaved then it becomes very important to understand that how each event fits in complete lifecycle . Also this is one of the most asked question in asp.net interviews so I thought of explaining it.

Technically, Master page is nothing but a normal user control so you can treat it as user control used on a page and we will consider it same in our post. So we can say that there are two type of controls – User Control and Custom Control in a page. Content page is also nothing but a normal aspx page. Now to understand the order of events where all of these controls are available, lets first understand of the life cycle of each components individually.

OrderNote- I have not included all the events of life cycle only those are relevant at important to explain the topic.

We can see that Pre_init is available in only in Page life cycle but not in the other controls and rest are same. Let’s see some example with various combination of these controls.

So in our next example, I am using a page which contains a master page and a user control (user control 1) on content page. I have implemented all the events that we discussed in the life cycle of the controls (Master page, content page, user control) and in each event I am writing in a log file when event is fired, to depict the proper flow of the page. So let’s see the flow of the page when it runs

firstHere, we see that it starts from Page_PreInit which is page life cycle’s first event then we see the next three events numbered 2,3,4 (first red encircled) then here first user control’s init gets called then comes master page and last one is Page_Init. After that we see the Load events of the components. For Load, the flow is different and starts from the page, master page and at last user control. Similar is also followed for PreRender and SaveViewState events. But again if we see the last three Unload events then we find it again fired in reversed order (same as Init events). So the key observations here that Init and Unload events get fired in reverse order and rest in normal as they put in the page. Other key item is that master page events gets fired just after ( or before for Init and Unload events) after the page events.

Now lets take another scenario. Here I am adding two more components – one more user control (user control -2 ) and a custom control. The custom control is placed in user control 2 and it is placed in user control 1 itself. Now I am going to run the application and show you the order of events

secondso here again if we closely see then we find that Init and Unload events are fired in reverse (inner most to outer most) order and rest are called from (outer to inner). For other events, master is always second and others outer to inner. If there are two controls are at same level ( like there are two controls on a page) then which appear first, gets called first.

So we now understand the ordering logic of life cycle events but now the question arises why the order of the Init and Unload are called in opposite order? Let’s try to understand

Why Init and Unload called in reverse order?

In simple words, we access the controls of the page many times in our page like in second example, I can find the instance of custom control in Page_Load event or in any other event of the page ( here we know the custom control is part of the user control 2 which itself is in user control 1) so if we try to find the custom control in Page_Init (and if it is fired first) the we wont be able to find because it is not initialized which will be an issue because we wont be able to make any change while page initialization. Similarly, Unload events start from the innermost control and it is also desirable because we might want to unload or want to dispose some items which are part of user control so we can do the same from Page_Unload and say if Page itself first gets unload then it may happen that other control might not be disposed properly.

We also know that controls are property of Page class so once a request enters to page life cycle then page structure gets created  (In Pre_Init) and some basic structural initialization occurs for the page then actual initialization starts which starts from the inner most control. After initialization only the controls can be used properly. Similarly in case unload first the property of the page i e control gets unloaded then Page itself.

I hope you know the ordering of the events and the logic behind it. Thanks for reading this post and please share your feedback or if any specific items you wan to see.

Cheers
Brij

Concurrency vs Multi-threading vs Asynchronous Programming : Explained

Recently, I was speaking in an event and I asked a question to the audience in between my talk about Asynchronous programming , I found that some of the people were confused between multi-threading and asynchronous programming and some were saying that both are same. So I thought of explaining these terms and add one more term Concurrency. Here there are two concepts involved and both are completely different, First – Synchronous and  Asynchronous programming and second – Single threaded and multi-threaded applications. Each programming model (Synchronous and Asynchronous ) can run in single threaded and multi-threaded environment. Let’s discuss these in detail.

Synchronous Programming model – In this programming model, when a thread assigned to one task and start executing. Then completes the executing task then able to take up another task. In this model, it can not leave the executing task in between to take up some another task. Lte’s discuss how this model works in single and multi-threaded scenario.

Single Threaded – If we have couple of tasks to be worked on and the current system provides a single thread which can work all those, then it takes one by one and process as

singlethreadedHere we can see that we have a thread (Thread 1 ) and four tasks to be completed. Thread starts processing one by one and completes all. (The order in which tasks will be taken up, does not affect the execution, we can have different algorithm which can define the priorities of tasks)

Multi-Threaded – In this scenario, we used to have multiple threads which can take up the tasks and start working on that. It mans we have pools of threads (new threads also created based on the requirement and available resources) and bunch of tasks. So these thread can work on it as

multithreadedHere we can see that we have four threads and same number of tasks to complete and each thread start working on that This is ideal scenario but in normal cases, we used to have more number of tasks then number of available threads so whichever thread gets free takes up another task. As already said that spawning new thread is not an option every time because it requires system resources like CPU, memory and based on that number of threads should be decided.

Now Let’s talk about Asynchronous model and how does it behave in single and multi-threaded environment.

Asynchronous Programming Model – In contrary to Synchronous programming model, here a thread once start executing a task it can hold it in between and save the current state and start executing another task.

async-singleHere we can see that a single thread is responsible to complete all the tasks and tasks are interleaved to each other.

If our system is capable of having multiple threads then all the threads can work in asynchronous model as well a below

Async-mutlithreadedHere we can see that same task say T4, T5, T6.. are handled by multiple thread. This is the beauty of this scenario. As you can see that T4 was started first Thread 1 and completed by Thread 2. Similarly T6 is completed by Thread 2, Thread 3 and Thread 4.It shows the maximum utilization of the threads.

So till now we have discussed four scenarios –

  1. Synchronous Single Threaded
  2. Synchronous Multi-Threaded
  3. Asynchronous Single Threaded
  4. Asynchronous Multi-Threaded

Let’s discuss one more term – Concurrency.

Concurrency

In simple terms, concurrency means processing multiple requests at a time. As we have discussed two scenarios where multiple requests were getting processed, Multi-threaded programming and asynchronous model ( single and multi-threaded both). In case of asynchronous model whether single or multi-threaded at a time multiple tasks are in progress, some are in hold state and some is getting executed.There are many flavors of it bt that is beyond the scope of this post.

As discussed earlier, the new age is of asynchronous programming. Why is it so important?

Benefits of Asynchronous Programming

There are two things are very important for any application – Usability and Performance. Usability because say an user clicked on button to save some data as it requires multiple tasks like reading and populating data in internal object, establishing connection with SQL and saving it there etc. As SQL runs on another machine in network and runs under different process, it could be time consuming may take bit long. So If the request is handled by single thread then the screen will be in hanged state till the process completes. That’s why now a days many application and new framework completely rely asynchronous model.

Performance of application and system is also very important. It has been seen that while executing a request, around 70-80% of the the gets wasted in while waiting the dependent tasks. So this can be maximum utilized by asynchronous programming where once once the task is passed to another process (say SQL) current thread save the state and available to take another process and when the sql task completes any thread which is free can take up the task.

Asynchrony in ASP.NET

Async in ASP.NET can be a major boost in the throughput of your application. Lets how IIS processes a request.

CLRWhen a request is received by IIS, it takes a thread from CLR thread pool (IIS does not own any thread-pool itself instead uses CLR thread pool) and assigns to it which further processes the request. As number of threads are limited and new ones can be created at a certain limit then if the thread wastes most of the time in waiting state then it is going to hit hard your server or you can assume it is reality. But if you write asynchronous code (which now become very easy and can be written almost similar to synchronous using the new keywords async/await) then it will way faster for you and throughput of your server will increase significantly because instead of waiting something to complete, it will be available to thread pool to take new request. If the application has a lots of dependency and long running process then for those application, async programming will be bot less than a boon

So now we have understood the difference in multi-threading, asynchronous programming and the kind f benefit we can get using asynchronous programming model.

Cheers
Brij

How to test email functionality using Smtp Client

Writing code for sending mail is one of the common tasks that we need to work every now and again. Sometimes it is one of the requirements in our application and some time we develop to send alerts to all when application looses its control on production :).

.NET made it very simple to send the mail which normally looks a complicated task. We can easily write 4-5 lines of the code to send the mail. Lets just have a look on a sample code

Continue reading

Dependency Injection Annotation Process in {{AngularJS}} – Part 18

Hello All,

In last two post, we discussed about DI, various types available in AngularJS and some insights around it. It is going to be another post on DI itself but here we’ll talk about annotations.I would recommend to go through last two posts before going further.

  1. Dependency Injection (DI) in {{AngularJS}} – Part 16
  2. Dependency Injection (DI) in {{AngularJS}} Contd.– Part 17

Note – This post is a part of series of posts on AngularJS and it is 18th one. Click here to view all the post. Apart from that you can also use the navigation links for next and previous post in each post at the bottom to check all.

In our previous posts, we have seen that services are passed as a parameter with same name  which was used defining like Circle and this is crucial because Angular internally locate the services using the name itself. So if the name does not match then dependencies won’t be resolved. As the name should be same so minifying the script would break the application which cannot be accepted. So let’s first see that the number of options provided by AngularJS.

AngularAnnSo as we have seen, we have three ways to inject the dependencies. Lets discuss one by one

Implicit parameter

This is the way that we have used in our last two post, where we use the same name in parameter which we defined while creating. This is most vulnerable as discussed in the first paragraph as well in case we minify our script files. As we used in one of our example

var myangularapp = angular.module('myangularapp', []);
myangularapp.service('Circle', function () {

    var pi = 3.14;
    this.Area = function (r) {
        return pi * r * r;
    }
    this.Circuimference = function (r) {
        return 2 * pi * r;
    }
});

myangularapp.controller("mycontroller", function ($scope, Circle) {
    $scope.AreaofCircle = Circle.Area(5);
    $scope.CircuimferenceOfCircle = Circle.Circuimference(5);
})

Here we are using Circle as parameter as Circle was used while creating the service. As discussed in the previous post, while resolving the dependencies injector comes into picture and as here there there are two parameters passed $scope and Circle services, injector uses the names  and creates the instance using the provider.

This is simplest way to resolve the dependencies but it breaks if minifiers or obfuscators are used as we know these changes the name of parameters based on there algorithm which later does not match with the providers. But if you are sure that minifiers/obfuscators are not going to be used on production then you can happily use this.

$inject property

This is another way to pass the dependency which does not break in case of minification. In this case even if the name of the parameters gets changed still all the dependencies correctly get resolved. Let’s see how

var myangularapp = angular.module('myangularapp', []);

myangularapp.service('Circle', function () {

    var pi = 3.14;
    this.Area = function (r) {
        return pi * r * r;
    }
    this.Circuimference = function (r) {
        return 2 * pi * r;
    }
});

var mycontroller = function ($scope, customCircle) {
    $scope.AreaofCircle = customCircle.Area(5);
    $scope.CircuimferenceOfCircle = customCircle.Circuimference(5);
};

mycontroller.$inject = ['$scope', 'Circle'];
myangularapp.controller('mycontroller', mycontroller);

Here we can see that we annotate $inject property of the function, here we provide the right name of the services in an array. In controller function we have chosen an arbitrary name (customCircle here) but code still runs fine.

As provider names are assigned as values in the array, no minifier or obfuscator changes the values so it works perfectly fine.

Using Inline Array

This approach is preferable way to resolve the dependencies in the Angular. It is just another way of using array values to provide the service names to appropriate functions but much simpler than above. Let’s take the similar example as above and implement it using inline array

var myangularapp = angular.module('myangularapp', []);

myangularapp.service('Circle', function () {

    var pi = 3.14;
    this.Area = function (r) {
        return pi * r * r;
    }
    this.Circuimference = function (r) {
        return 2 * pi * r;
    }
});

myangularapp.controller("mycontroller", ['$scope','Circle', function ($scope, customCircle) {
    $scope.AreaofCircle = customCircle.Area(5);
    $scope.CircuimferenceOfCircle = customCircle.Circuimference(5);
}]);

Here we can see that we create an inline array then we pass all the dependencies in the array and at end we pass the function where the dependencies need to be passed. Here function takes the input parameter which gets resolved to the dependencies based on the values passed in the inline array. We can pass all the services in similar way. This trick requires less code and easily understandable than the previous one.

Here the key thing to be noted that it orderof the values in the array and parameter name is very important if that gets changed then the right dependencies be initialized to right parameters. Same holds true for second option as well.

Important Note – As it is a common practice to use minifier while putting the code at production and somehow the dependency got resolved via first way then it could be disastrous for your application. In case of big application, where many developers working on same application everybody may use its own choice which could lead issues at production. So to avoid this, Angular provide us a way which makes sure that no body uses implicit injection and that is called Strict Dependency Injection. For this we need add one directive ng-strict-di where we provide ng-app as

<div ng-app=”myangularapp” ng-strict-di>

Hope you all have enjoyed this post including two earlier posts on dependency injection in AngularJS. Do share your feedback.

Cheers
Brij

Next Post ==>

Presented on ASP.NET performance tuning in C# Corner Hyd Chapter Event : 12th July 15

11753645_10153514597568086_9069014579518330181_nHello All,

This was the first when I presented at a community event in Hyderabad. I was pretty excited for the day as I started hearing about this city since my college days due to its significance in IT. And yeah Microsoft’s develop center is also in this city. The day arrived and when I reached the venue, I found that most of the seats were full very early and we had some time to start the event as per schedule. Many kept standing throughout the event as the seats were already occupied completely. Here one point to be noted that we organized this event after long in this city and managed to get a venue which was not very known, also not easily accessible. I wasted more than an hour even when somebody was guiding me for the place on phone. Continue reading

Dependency Injection (DI) in {{AngularJS}} Contd.– Part 17

This post is in continuation of my last post DI on AngularJS. In previous post, we first discussed about DI in details with an example of implementing it in JavaScript. Then we discussed the way AngularJS provides us the opportunity to implement DI  and various options available with it.  We discussed two types Value and Factory in detail. In this post, we will be discussing rest three types and will see how DI takes place behind the scene. I would suggest you to go through the previous post (Dependency Injection (DI) in {{AngularJS}} – Part 16) before continuing further.

Note – This post is a part of series of posts on AngularJS and it is 17th one. Click here to view all the post. Apart from that you can also use the navigation links for next and previous post in each post at the bottom to check all.

Continue reading

Dependency Injection (DI) in {{AngularJS}} – Part 16

Dependency Injection (DI) is one of the hottest terms being used in software development nowadays. Most of the application developers talking about this and try using it in their application. One of the key reasons Agile methodology, as it is used in almost every project in one or other way and DI easily fits into this model and help in achieving its goal. I have been getting many request to write about DI in AngularJS so let’s start exploring that.

Note – This post is a part of series of posts on AngularJS and it is 16th one. Click here to view all the post. Apart from that you can also use the navigation links for next and previous post in each post at the bottom to check all. Continue reading