ThreadAbortException ― This behavior is by design

If you are coding in .NET and want to transfer a web request from one page to another then you don’t have many options in terms of API to does that for you. You will either use Server.Redirect or Server.Transfer . The former does the client side redirection and later is responsible for server side. The problem with both of them is their dependency on Response.End which in turn calls Thread.Abort that causes ThreadAbortException (Reference: MSDN). To work around this problem Microsoft suggests the followings alternatives:

  1. Using Server.Execute instead of Server.Transfer
  2. Supplying endResponse parameter to Response.Redirect method to suppress the internal call to Resonse.End

In case of not implementing the above will result in showing output of 2 different web pages (caller and callee) in the same web browser window. These alternatives are most likely to work 99% of the time as in general in everyday programming they are not followed by any other statement. And rightly so, why would one write something which is not meant to be executed. This implies that you are completely safe even if:

1. Control comes back from Server.Execute and continues execution on the current page.
2. Response.Redirect transfers control to the other page and due to the presence of endResponse=true parameter, it continues execution on the current page.

just because we don't write any database processing, file processing or any other code logic that follows Server.Execute or Server.Execute. However, in a situation where you must directly use Response.End, you can call HttpContext.Current.ApplicationInstance.CompleteRequest method in lieu of Response.End which bypasses the code execution of Application_EndReqeust event (Reference: MSDN).

If you are thinking as I was thinking that it's a bug in .NET, then you are wrong. MSDN explains that this is not a bug but a behavior by design. However, I would really love to see that real world usage of this behavior in everyday programming that could justify this design decision.

References:

IIF(A,B,C) -- Beware it is a function not a statement!!

Learning how to write neat and clean is something many people wish to achieve. I believe it's an art which can be mastered with practice. I myself have this habit of keeping things brief and to the point, and I always tend to apply the same theory to my coding as well. However, today while writing a small piece of code in the similar consise manner for a small module, I found something interesting that made me realize the importance of understanding the difference between different programming constructs. I am talking about IIF(A,B,C) function and IF ELSE statement in particular here.

I had a situation where I was getting some value from the database and there was a fair chance of that value being NULL. I preferred IIF over IF ELSE to save 3 lines of code.

Dim lCVCount As Integer = IIf(IsDBNull(DataBinder.Eval(e.Item.DataItem, "IsCV")), 0, CInt(DataBinder.Eval(e.Item.DataItem, "IsCV")))

Mucy to my surprise, it didn't work and threw me exception. I kept wondering for a few minutes what is wrong with this. You know it is generally said that not knowing something is acceptable but forgetting something which you know is completely unacceptable and I agree with this. How can I forget that a function behaves differently than a statement. It passes parameter values to calle which means it must execute those parameters first, if they are found to be compund in order to get their value. This explains it all that why the third parameter in above statement is throwing exception. I thought I am better off using IF ELSE here in order to keep .NET runtime happy.

Sometimes It is good to get these kinds of errors which reinforces the fact that we should always be careful in what we write and specially when it comes to writing code!!

HTH,

File "Save As" issue while downloading with Content-Disposition: inline

It has been a long a time since I wrote anything on the blog. I was on a long holiday and (honestly speaking) wanted to stay away from the technology. But now, since life is back on rails, let's start with the very first issue I faced after I joined my workplace a couple of days ago. It is about an issue with the file name not being considered when using "inline" as HTTP response Content-Disposition header.

Downloading a file using Content-Disposition: attachment as HTTP response header displays a "File Download" dialog box asking the user whether to "Open", "Save" or "Cancel" the document. In certain scenarios this dialog box can be really painful specially when user has to repeatedly do this exercise for multiple links available on our website. In order to avoid this we use Content-Disposition: inline which opens the document without asking by using appropriate software like MS Word, Adobe Acrobat Reader etc. installed on the user's machine. This document can be saved later on using "Save As" option.

Before I move on, let's have a look on the following statement that shows the way to add Content-Disposition header to Response stream:

context.Response.AddHeader("Content-Disposition", "inline; filename=resume.doc")

The problem with the Content-Disposition: inline is that it doesn't pick the file name from filename attribute we use in AddHeader function rather, it always takes the name of web page from the URL while saving the document. Content-Disposition: attachment seems to be working fine even with the "Save As" command, but this is something I didn't want to use. I spent some time researching on this issue and couldn't found a workable solution. In order to workaround I came up with the below solution that seems to be doing the job.

I actually decided to use a URL for the document link that reflects the name of the document being downloaded. For example for the document "MyResume.doc", the URL I have used looks something like this:

<a href="Default/FileName/882bd3e9-5035-4946-8c2a-98ef0eccc6e0/uploads/MyResume.doc.aspx">Download File</a>

Did you notice ".aspx" at the end of the URL? It is very important to append it in the end in order to send the request back to server whenever user clicks on the link. On the server, I have created an HTTPHandler to catch this sort of request that contains "*.doc.aspx". Without appending ".aspx", browser will server your document directly without changing the URL in the browser. But, we want to change the URL which means request has to go to the server.

The rest of the solution is very easy as I have written below code under the body of ProcessRequest function in my HTTPHanlder which helps dump file contents into response stream. It is also important to note that URL of the document must be relative and not absolute. The reason being, it's a dummy URL which doesn't exist at all. Relative URL guarantees that request will come to the same web site/application where we can catch it before it goes to ASP.NET engine. QueryString data can be made part of the URL as in my case GUID is the piece of information which is part of the URL and I receive it on the server.


Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest

'Context.RewritePath("Test-Page.aspx")
context.Response.ContentType = "application/msword"
context.Response.AddHeader("Content-Disposition", "inline; filename=adeel.doc")
context.Response.TransmitFile("C:\inetpub\wwwroot\Uploads\882bd3e9-5035-4946-8c2a-98ef0eccc6e0.doc")
context.Response.Flush()
context.Response.End()

End Sub


The last bit is to add the below statement in web.config to enable HTTPHandler to catch "*.*.aspx" so that it will serve for all kinds of file type extensions.

<add verb="*" path="/uploads/*.*.aspx" type="Test.HttpHandler, Test"/>