How to write code in C#, Asp.Net, Php, Javascript, C. On this blog you will find example codes that will help you to understand concepts of programming.

Saturday, January 21, 2012

How to shut down an application in Asp.Net?

Often when you are updating your website you would not be able to overwrite files, operate in database.
That is why you can do the following.
Create a file called app_offline.html. In this file you can insert content to show as long time as your application is down for maintenance.
You can look here form my application offline page:

The way app_offline.htm works is that you place this file in the root of your application. When ASP.NET sees it, it will shut-down the app-domain for the application (and not restart it for requests) and instead send back the contents of the app_offline.htm file in response to all new dynamic requests for the application. When you are done updating the site, just delete the file and it will come back online or rename to _app_offline(for example) and you will have the file there for use next time you need it.

Also have in mind that by adding the app_offline.htm the application sends the Application_End and after this function return the rest of the threads of the program are killed. The maximum time of wait for theApplication_End to return is set on the pool settings.

If you stop the full pool then all the sites that under this pool follow the same procedure. If you only open the app_offline.htm then only this site is affected.

To avoid your threads to kill by this shutdown, set a wait state on the Application_End

void Application_End(object sender, EventArgs e)
{
// This is a custom function that you must make and
// check your threads in the program
MyTheadClass.WaitForAllMyThreadsToExist();
// after this function exit the rest of the threads are killed.
}

If you use the app_offline.htm feature, you should make sure you have at least 512 bytes of content within it to make sure that your HTML (instead of IE's friendly status message) shows up to your users. If you don't want to have a lot of text show-up on the page, one trick you can use is to just add an html client-side comment with some extra content to push it over 512 bytes. You can insert html comments just to make your file bigger.