Tuesday, February 23, 2010

Response.Redirect(url) ThreadAbortException Solution

Response.Redirect(url) ThreadAbortException Solution

by John S. Reid

Since the advent of Server.Transfer(url) I've used Response.Redirect(url) less and less, but for those times when you want the client to know of the location from where information will be retrieved it's still your best option. So you use it, never expecting that the simple call you've used for years with ASP would throw an exception in ASP.NET.

The ThreadAbortException is thrown when you make a call to Response.Redirect(url) because the system aborts processing of the current web page thread after it sends the redirect to the response stream. Response.Redirect(url) actually makes a call to Response.End() internally, and it's Response.End() that calls Thread.Abort() which bubbles up the stack to end the thread. Under rare circumstances the call to Response.End() actually doesn't call Thread.Abort(), but instead calls HttpApplication.CompleteRequest(). (See this Microsoft Support article for details and a hint at the solution.)

Though one could argue the logic behind throwing this exception in the first place, there are a couple of ways to get around this.

The try-catch block



catch (ThreadAbortException ex)

The first solution, and the most common one found in an internet search, is to simply wrap the call to Response.Redirect in a try-catch block. Although it appears to work I don't like it for two reasons:

  1. Processing an exception can be costly and messy
  2. The rest of the page and event chain continues to execute

Since the exception is caught the page continues to execute through it's event chain which takes up unnecessary CPU resources and potentially sends unwanted data to the client (which will be ignored since the client received a redirect).

A better way.

Since the real culprit is the call to Thread.Abort(), how can we Redirect the page without making that call? We would have to tell the client to redirect without calling Response.End() of course, and it turns out that there is an overload method of Response.Redirect() that will do exactly that.

Response.Redirect(string url, bool endResponse);

In this overload the second parameter tells the system whether to make the internal call to Response.End() or not. When this parameter is false the client is sent the redirect url, but the internal call to Response.End is skipped. This completely avoids the code that would throw the exception, but the cost is that this thread doesn't stop executing the Application events! Thankfully we can solve that problem also by duplicating the step that Response.End() takes under those rare circumstances, namely calling the HttpApplication.CompleteRequest() method.

HttpApplication.CompleteRequest() sets a variable that causes the thread to skip past most of the events in the HttpApplication event pipeline and go straight to the final event, named HttpApplication.EventEndRequest. This gracefully ends execution of the thread with a minumum of server resources.

Alain Renon pointed out to me on Gabriel Lozano-MorĂ¡n's blog that the page still sends the rendered HTML to the client. He's absolutely right. In fact, Page events still execute and the Page still processes postback events too. The event pipeline that I am talking about short circuiting with the call to HttpApplication.CompleteRequest() is not the Page event chain but the Application event chain. The Application event chain currently consists of the following events as of .NET 2.0:


I've bolded CallHandlerExecutionStep because that is the step where all of the Page events take place. If you make a call to HttpApplication.CompleteRequest() from a Page event such as Page_Load then the Page events still process to completion, but all the Application events between CallHandlerExecutionStep and EventEndRequest are skipped and the thread ends gracefully.

One could argue that it doesn't matter so much that the page is still rendered since the client ignores it anyway, but Alain is correct that it does render, and that's not as efficient as we could make it. Also, if you have any PostBack processing (such as OnCommand Page event handlers) those will process and you may not want that either, but never fear there is an easy solution to both of those problems as well.

PostBack and Render Solutions? Overrides.

The idea is to create a class level variable that flags if the Page should terminate and then check the variable prior to processing your events or rendering your page. This flag should be set after the call to HttpApplication.CompleteRequest(). You can place the check for this value in every PostBack event or rendering block but that can be tedious and prone to errors, so I would recommend just overriding the RaisePostBackEvent and Render methods as in the code sample below:

private bool m_bIsTerminating = false;

protected void Page_Load(object sender, EventArgs e)

if (WeNeedToRedirect == true)

Response.Redirect(url, false);
m_bIsTerminating = true;
// remember to end the method here if
// there is more code in it




protected override void RaisePostBackEvent(IPostBackEventHandler sourceControl, string eventArgument)

if (m_bIsTerminating == false)

base.RaisePostBackEvent(sourceControl, eventArgument);


protected override void Render(HtmlTextWriter writer)

if (m_bIsTerminating == false)



The Final Analysis

Initially I had recommended that you should simply replace all of your calls to Response.Redirect(url) with the Response.Redirect(url, false) and CompleteRequest() calls, but if you want to avoid postback processing and html rendering you'll need to add the overrides as well. From my recent in depth analysis of the code I can see that the most efficient way to redirect and end processing is to use the Response.Redirect(url) method and let the thread be aborted all the way up the stack, but if this exception is causing you grief as it does in many circumstances then the solution here is the next best thing.

It should also be noted that the Server.Transfer() method suffers from the same issue since it calls Response.End() internally. The good news is that it can be solved in the same way by using the solution above and replacing the call to Response.Redirect() with Server.Execute().







Monday, February 22, 2010

How to imitate 56 modem environment while creating on fast networks


“Sloppy belongs in the ‘essentials’ toolbox of every web developer”



Charles is an HTTP proxy / HTTP monitor / Reverse Proxy that enables a developer to view all of the HTTP and SSL / HTTPS traffic between their machine and the Internet. This includes requests, responses and the HTTP headers (which contain the cookies and caching information).



Sunday, February 21, 2010

Fixing "Padding is invalid and cannot be removed" when requesting WebResource.axd

Fixing “Padding is invalid and cannot be removed” when requesting WebResource.axd

If you are using ASP.NET in your website and have a look at your Application EventLog you will probably see warning entries like this:

CryptographicException: Padding is invalid and cannot be removed.

Event Type: Warning
Event Source: ASP.NET 2.0.50727.0
Event Category: Web Event
Event ID: 1309
Date:  21/08/2009
Time:  13:08:48
User:  N/A
  Event code: 3005
  Event message: An unhandled exception has occurred.
  Event time: 21/08/2009 13:08:48
  Event time (UTC): 21/08/2009 11:08:48
  Event ID: 1cc59501bae34562a1e486c16f2e799f
  Event sequence: 11912
  Event occurrence: 1
  Event detail code: 0
  Application information:
    Application domain: /LM/W3SVC/1/ROOT-1-128952696565995867
    Trust level: Full
    Application Virtual Path: /
    Application Path: C:\Inetpub\webs\www.test-domain.com\
   Machine name: WEBSERVER
  Process information:
    Process ID: 3920
    Process name: w3wp.exe
  Exception information:
    Exception type: CryptographicException
    Exception message: Padding is invalid and cannot be removed.
  Request information:
    Request URL: http://www.test-domain.com/WebResource.axd?d=pFeBotgPWN6u7M4UfAnWTw2&t=633687432177195930
    Request path: /WebResource.axd
    User host address:
     Is authenticated: False
    Authentication Type:
     Thread account name: TEST-DOMAIN\IWAM_WEBSERVER
  Thread information:
    Thread ID: 12
    Thread account name: TEST-DOMAIN\IWAM_WEBSERVER
    Is impersonating: False
    Stack trace:
       at System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast)
       at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
       at System.Security.Cryptography.CryptoStream.FlushFinalBlock()
       at System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start, Int32 length, IVType ivType, Boolean useValidationSymAlgo)
       at System.Web.UI.Page.DecryptStringWithIV(String s, IVType ivType)
       at System.Web.Handlers.AssemblyResourceLoader.System.Web.IHttpHandler.ProcessRequest(HttpContext context)
       at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
       at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Custom event details:
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

Depending on how busy is your web server you can see them appear from time to time or up to every few minutes, thus filling your EventLog and being from a light annoyance up to a real problem (depending on how hypochondriac you are).

In fact, they are just warnings that can be ignored on most of the cases, but they can be a real problem when they bury other events and the forest do not let you see the trees. If there are many of them and you want to get rid of them (or most of them at least), keep on reading.

You might check your IIS Log by the times when the warnings appear and (if you also log user-agent) you will probably see that most of the time the URL is NOT requested by a real user, but a spider engine doing its crawl (googlebot, msnbot, yahoo, tahoma, or any other). You can double check doing a reverse dns check for the offending IP address doing a ping –a aaa.bbb.ccc.ddd and you will also see the IP resolves to something like *.googlebot.com, *.search.msn.com, *.crawl.yahoo.net or *.ask.com. This should give you a hint on what to do…

WebResource.axd is just an httpHandler that wraps several resources within the same DLL. It is in charge of returning from little .gif files for serving the arrows of the ASP:Menu control, to .js files governing the behavior of the menu itself. Even though your website do not use ASP:Menu control, you probably will be using WebResource.axd for javascript dealing the post back of your form or any other thing.

Why does this exception happen?

If you see in detail the parameters following the WebResource.axd request you will notice two of them. The first one d refers to a particular resource embedded in the httpHandler DLL. It is a fixed value as long as the source DLL is not updated or recompiled. The second t parameter is a timestamp parameter that changes whenever the web application (AppPool) is recompiled (a changed/updated DLL, an update to web.config, and so) and depends on the machineKey of the web site. If web.config does not explicitly declare a fixed machineKey, the t parameter will change from time to time (restarts, job recycles, etc).

In fact these CryptographicException warnings are well known in web farms configurations. In that case, all the servers belonging to the same farm must have the same machineKey because if a served page (.aspx container page) by a particular server of the farm includes a value of t parameter and the subsequent request for that URL resource is handled by other server of the farm, the exception would arise and the user could not download the resource. And, in this case we would be talking about real browsers with real users behind them, not spider engines.

Furthermore, if you have implemented a conditional GET in your webserver, this exception is more likely to happen, since a user can come back to your site, do a request for a page that has not changed, being returned a 304 Not Modified, and still request the resources included in that page, that might be invalid due to the change of t.

The solution: two steps.

As you can imagine, the first thing that you can do is setting a fixed machineKey in your web.config file. Even though you are not running a cluster, nor a web farm, it will help you to minimize the occurrences of the warning Padding is invalid and cannot be removed.

For this you can use a machineKey generator or generate your own if you know how to do it (random chars will not work).


The second (and easier) step to follow is to prevent WebResource.axd URLs from being requested as much as possible. In particular by search engines crawlers or bots, since those resources should not be indexed nor cached in any way by them. Those URLs are not real content to be indexed. If you only add the following lines to your robots.txt you will see how the frequency of CryptographicException is reduced drastically. If you also change the machineKey to a static value, you will get rid of them almost completely.

User-agent: *
Disallow: /WebResource.axd

As I said, you will get rid of this warning almost completely. There might be search engines not following your robots.txt policies, users visiting you from a Google cached page version, etc. so you cannot get rid of this warning messages for good, but yet enough for not being a problem anymore.


Summing up, this event appears when there is a big time difference (lap time) between the page that contains the resource and the resource itself being requested. During that lapse, the application pool might have been recycled, recompiled, the server restarted, etc, thus changing the value of t and thus, rendering the older t value useless (the cryptographic checks fail).

Above article is taken from the following link:-



Friday, February 19, 2010

Essential tools for Website speed benchmarking

1.       Page Speed is an open-source Firefox/Firebug Add-on. Webmasters and web developers can use Page Speed to evaluate the performance of their web pages and to get suggestions on how to improve them. http://code.google.com/speed/page-speed/download.html

2.       YSlow analyzes web pages and suggests ways to improve their performance based on a set of rules for high performance web pages. YSlow is a Firefox add-on integrated with the Firebug web development tool http://developer.yahoo.com/yslow/

3.       A plug-in HTTP viewer for Internet Explorer and Mozilla Firefox http://www.httpwatch.com/


21 Tips To Find A Good Shared Web Hosting Company

21 Tips To Find A Good Shared Web Hosting Company

Hello there! If you are new here, you might want to subscribe to the RSS feed for updates on this topic.

Powered by WP Greet Box WordPress Plugin

Recently I was looking for a local shared web hosting company to move my new project from my current host to a local one. Similarly like everyone in the world who wished to look for new things, they would research and so did I. And because of my previous experience on finding my current US web hosting company, hostgator, which is a long and tiring journey due to many fake and incorrect information that people (i can’t really really say company) made online for monetary purposes. It’s always easy to fall prey into all these online marketing tricks. So I decided to list down all the tips I used to find a good web shared hosting company in the case where I need to change to a new hosting company (hopefully not).

Shared web hosting

Like everyone would have known the fact that a shared web hosting means there are a lot of people sharing a single server with you. Sharing doesn’t mean that your website will run slower or it will be worst than a dedicated server. It really depends on your website needs. Your website might be a static page that only needs less than 0.1% (or even lesser) on a full dedicated server so putting your site in a shared environment will be the best in terms of cost and efficient. However, there are cases where people abuse the resources in a shared environment which is also why many web hosting company have turned to restrict the amount of resources one can utilize which is a good move in a shared environment. Hence, your only concern on a shared hosting service is whether people in your server is behaving properly or utilize minimum server resources. (so that there is enough for everyone)

Shared web hosting company

Now let’s talk about shared hosting company. There are tons of them. Majority is overselling. These are the facts and most of us know it once we read their shared web hosting plan. Especially in US where majority company is telling you the word UNLIMITED. And DAMN that’s a very VERY attractive word that ALL people love. (human have unlimited wants but there are limited resources, e.g. we want unlimited beautiful woman but there are only limited beauties) And usually a novice who read the first site that offered UNLIMITED hosting plan will most likely fall into their marketing scheme (ITS YOU RIGHT?! haha..). But it’s pretty common nowadays especially people who are just stepping into the world of spammers, opps, i mean world of web hosting services. Everyone wants to earn some money and this doesn’t exclude shared web hosting company. New or existing shared web hosting company, they all are staring at your pocket. The key is not to show them the money quickly. I talked as if they are all spammers. Definitely, there are ones that provides you with excellent services but out of so many shared web hosting company, who do you choose? :(

Tips To Find Good Hosting Company

After the long read of crap and nonsense, i’m finally getting back to what i aim to write, My Tips. Some are obvious, some are not. Just take those you want :)

Your Needs. Don’t be greedy

I’m greedy. And this is where i always paid more for something i might not EVEN need. It’s like when you hungry and order tons of food but couldn’t finish them in the end. The same things applied on web hosting service. The trick is to estimate how much you need for both bandwidth and space. For an image gallery where there are few thousands visitors a day. You will need quite a lot of bandwidths while a normal website that doesn’t serve as much images won’t need that much of space and bandwidths. Hence, look at what you are serving and determine which plan suit you the best. (unlimited packages usually disappoint you more than satisfy you. Depending on the size of the company,  they might not have the resources to provide unlimited package)

Number of Website Hosted in a server

You need to know how much website is hosted in a particular server. If one server hosted more than a thousand websites, the probability of your site getting your resources will be very limited. Imagine more than one thousand website fighting that limited resources in a server. Hence, look for some company that do not over host their server and cause headache for you in the near future.

Number of Account in a server

You might probability be aware that there are a lot of web hosting that claims unlimited web site on a domain. This is great news for everyone but each account with unlimited website will means MANY MANY website on a single server. Therefore, its wise to know more about your web hosting company setting on the number of account allowed per server.

Server Location

Depending who your audiences are, your server should be close or near them. This benefits both you and your target audiences of your website because there are less expensive routing towards your website which makes your website more accessible. On the other hand, you can monitor or manage your website faster than a web hosting companies that is across your region.

Any Database Size Limitation

Know your web hosting company well. Some web hosting company (most) do not tell you the limitation they impose on the database size. Once, you reach that limit that database can no longer place more data into it. This is bad for you and you should be aware of it before signing up with them.

CPU and Memory Limitation

CPU and memory limitation is a common knowledge in shared web hosting nowadays. As long as you are using a shared web hosting service, you should be aware of this limitation. Knowing this help you to find the least restrictive web hosting company with the best value.

Server Specification

In a shared environment where everyone uses the same resources, one must know that the server is powerful enough to serve the amount of website limited by the company in the server. Some still uses their old server to host the same amount of website as a latest server. You might want to avoid those server to avoid unnecessary problem.


Knowing when and what they backup is important for you in case anything went wrong with their server. Especially the information on the limitation impose when they stop automatic backup for you. There are many cases where they will stop their automatic backup system for your account due to various reasons. And these reasons might make you avoid the company.

Time of Establishment

A reputational web hosting company means you are safer with them. This means that you can have more confident that they won’t suddenly bankrupt and went missing (something you see in my country) and your data won’t be stolen because your website did great and many ridiculous problem you might face with a untrusted hosting company (To began with, they do not have any reputation to spoil).

Any limitation on the number of domain/subdomain

If you like to have one hosting plan with multiple domain. You should aware of the number of domain/subdomain the plan offer you to prevent any unnecessary regrets.

Any limitation on each email account size

Some web hosting company impose a maximum email account size limit to prevent spam from over flooding their web server. If you are a person who dislike such restriction be sure to look properly before signing up with any company.


Another way to know whether they are good is to ask lots of questions and determine their responsiveness and correctness. A responsive and knowledgable support team will most likely make you more happy than angry in the future. Email different section to enquire anything from heaven to earth especially when you are sure ITS THAT COMPANY you want.

Maximum number of database connection

Some company restrict the number of database connection or users you can have. Having unlimited addon domain without having different database user or connection is like cutting your leg off while giving you sticks to walk. Without knowing such limitation and bang into a web hosting services will not do you any good.

Other Service Fees

Some company charge you service fees for some technician assistance. This is an information you should know to help yourself cut down some heavy addon fees on your web hosting when support become chargable. Ask your web hosting services what are chargeable and determine whether its reasonable before joining the club.


Another interesting thing you should be aware of is the connection speed use to power their web hosting service. Connection is also one of the important thing you would like to compare against different web hosting company.

Technical support, not so technically skill

This is a common scenario where their technical support give you stupid answer or incorrect one. Some even give you those default answers that was given by the company. Finding a good support will take you a long way in the future.

Talk to people

Find out from people who are currently using the company web hosting service. I’m sure they will share with you their experiences with them and you can better determine whether they are the one for you.

Use tool to verify

After you have enquire. You can further verify some of the information given by using some of those free web based tool. I personally used yougetsignal.com where it can tell me the number of website hosted in an IP address, location of the server, etc. This help you ensure that you are not being marketed and they are honest with their words.

Server hosting company

Another thing you might want to check with your web hosting company is their server hosting company. Their downtime depends greatly on them.

Check IP

Check their IP in one of those spam ip checker online. Determine whether their IP is considered as spam is important as many internet provider would block these ip to protect their users. This will also means your website will be considered as spam site.

Other tips

Other tips can be found on my review page on hostgator.


The trick here is to always ask for information not available on their website. These are most likely the information they wish to hide. But they can always trick you when you ask and that is why money back guarantee is so important to us.

The Above article have been take from following URL:-