Tuesday, August 31, 2010

Why Breakpoint does not hit in Visual Studio?


DARE TO SHARE?

Sometimes while you try to debug a problem in Visual Studio, breakpoints might not hit, and that's annoying. I've prepared a check list that you can follow to make the breakpoints hit when you encounter such situation:
 
1. Make sure that the Solution/Project is in Debug Mode and not in Release mode. 

2. Set a break point at the first line of Page_Load() method within the target page (If you are working with an Asp.net application) and see if that break point hits. If yes, proceed from that break point one by one line by pressing F10 or F11(Where necessary) to make sure that, your all conditions are correctly met before executing your target line of code. 

3. Make sure that, your target code actually builds when you build your solution/project. To do that, go to Build->Configuration Manager and make sure the corresponding project is checked (In the rightmost column). 

4. Make sure that your code is actually getting executing when you hit a page URL in the browser. If you debug by running the application under IIS, then try to debug using Debug->Attach to process->w3wp.exe. Also make sure that, you are hitting the correct page in correct way that could in turn executes your target code. 

5.If your break point is within a class library code, make sure that, your web site has a "Project reference" to that library, instead of a "dll reference"

6. Sometimes, some installed software in your OS might not allow you to debug by pressing F10 or F11 in your keyboard. In this case, try to debug by clicking the Debug->Step Into or Debug->Step over in the Visual Studio. 

7. Try with a System.Diagnostics.Debugger.Break() to see whether the system actually breaks. 

8. If nothing works, try to Clean the solution (Right click on the project/web site in the Solution explorer->Clean), then Rebuild or perhaps close the solution and restart it before clean and rebuild. 

Happy debugging :)

Friday, August 27, 2010

Exception handling best practices in Asp.net Web service


DARE TO SHARE?

In Asp.net, Exception thrown from a Web Service method are wrapped inside a SOAP message, and, sent to web service client. Within the SOAP message, there is a SOAP fault element (Fault), which contains the exception information. Now, if an exception is thrown from the web service, be it a SoapException or any kind of specific exception (Say, IndexOutOfBoundException), the Asp.net runtime will serialize it into the SOAP Fault element within the SOAP message. At the client-end, you will get the SOAP Fault de-serialized already and you will get the SoapException, always. 

Within the Message property (string) of the SoapException you will get the detailed serialized message of the original exception that actually occurred at the Web Service-end. So, ultimately, you have no way but to rely on the string Message property of the SoapException. At the client-end, you can parse this message to retrieve exception details, but, parsing the detailed message to retrieve the exception information may sometimes be unreliable, as this is merely a string message. 

Fortunately, there is a smarter way to handle it. There is a "Detail" property within the SoapException, which is nothing but an XmlNode type. You can use this property to send exception details information in semi-strongly typed fashion to the client. 

So, what you do is as follows: 

1. When an exception occurs at the web service-end, you build the XML node with the specific exception detail information. Please see http://msdn.microsoft.com/en-us/library/system.web.services.protocols.soapexception.detail.aspx to see how to do this. 

3. You create a SoapException object and set to the Detail property with the XmlNode just prepared. 

4. You throw the SoapException object from the Web Service. 

5. At the client-end, you catch the SoapException and parse the "Detail" property of the exception object (XmlNode) and retrieve the specific exception information that occurred at the server end (You can use Linq to XML to do this parsing easily). 

6. You display a desired friendly message at client application :)

Tuesday, August 24, 2010

What is Interface? Why should you use Interface?


DARE TO SHARE?
A few days ago, there was a question in a programming forum. The question was very common though. A newbie wanted to know what is interface and why should it be used?

My answer was something like below:


"See, in real life, when you interact with some objects, you don't really care about the internal implementation or complexity of that object. For example, when you use your computer, all you care about is how to power on or off by switching the button, how to input data (Using keyboard or mouse) and operate it. As a user, you really don't care about how the computer is internally operating by processing your inputs using complex logic and show the output in the screen.


So, the computer has not exposed the internal complexities to you, or, to the outside world. All it provides is an "Interface" to the outside world with the information that the outside world needs to know to use and operate the computer. As a user, you are happy to know about the "Interface" only, rather then the Internal implementation and complexity


In the programming world also, when you need to develop a class (Which may do many complex things), you need to expose the capabilities and operation of the class to other applications or class libraries (That may use this class) so that they can understand and use your class accordingly. What you do is, you create an Interface that contains the method signatures and you implement those methods in your class. So, the client applications and libraries can develop their codes based upon the Interface you defined, and while at runtime, the method invocation on the interface actually turns out to be a method invocation on the object of the class that implements the Interface.


Use of interface gives you extreme flexibility. For example, suppose you have an interface (IComputer) that exposes the functionality to the outside world and you have a class (WindowsPC) that implements the Interface method. Now, based upon some requirement, you can develop another class (MacPC) that implements the interface methods in a different way (Because, a MAC pc is basically a Computer, that roughly has the same kind of features, but, internally operates diffrently). Now, if the client application codes are developed based upon the Interface (IComputer)and, not based upon the implementation classes (WindowsPC or MacPC), there is very little chance that, they would need to change their code when the internal implementation of WindowsPC or MacPC might need to be changed.

WindowsPC and MacPC both implements the IComputer interface. So, if your client codes are developed using the IComputer interface and they accept an object of type IComputer as parameters in their methods, you can send them an WindowsPC object instead of a MacPC object any time and the client code will run perfectly without any problem (As long as your implementation classes are implemented correctly).


So, use of Interface this gives you lots flexibility to your code that you can manage easily and you can extend it without much change.


Basically, use if interface is part of the basic Object Oriented Principles. You may take a look at this article
How I explained OOD to my wife[^] to learn these principles."

Sunday, August 22, 2010

I won the Code Project Best overall article of July 2010


DARE TO SHARE?
Today I was notified by CodeProject about being awarded with the Best overall article of July 2010. This was the first article written by me at CodeProject in the year 2010. Earlier I had 3 best article awards last year and this is the 4th. A good comeback I guess :)

These are my CodeProject articles : http://www.codeproject.com/script/Articles/MemberArticles.aspx?amid=4950215


And, last week I've also achieved 10000th points as a CodeProject article author  and that gives me a Platinum membership there (The highest ranked membership in CodeProject), along with an MVP status for year 2010 that I already got earlier this year. I hope I would be able to retain the MVP status for year 2011. Thank you CodeProject.

This is the letter that I got today morning:

Hi Al-Farooque Shubho,

Congratulations! You have won The Code Project Best overall article of July 2010 .
Type: Article
Location: How I explained OOD to my wife

Prizes:
A Code Project T-shirt from The Code Project. Value: $1
FPS Maps for WPF from Oleh Mykhaylovych. Value: $199.99
DXperience™ Enterprise Subscription from Developer Express. Value: $1,299.99
In total you have won $1,500.98 in prizes. Well done!
The companies donating the prizes have been notified and will be in contact you soon.
Again - thanks for your contribution to The Code Project community.

Sean Ewington
The Code Project
http://www.codeproject.com

Thursday, August 19, 2010

Cross domain communication between IFrame page and parent page : A simple workaround


DARE TO SHARE?
This is a classic issue.

Suppose you have an IFrame in a page, where the IFrame loads a document from a domain (Say, www.domain1.com) that is different from the domain of the the IFrame's container page (Say, www.domain2.com).

Now, if for some reason you need to access the Document Object Model (DOM) of the parent page from within the child page inside the IFrame (Using javascirpt), you can't do that. Why? because this is a security restriction that prevents access to a document's content from a document that is originated form a different domain. The vice verse is also true. That is, you cannot access the DOM of the child page (Inside the IFrame) from the parent page using javascript, for the same very reason.

However, I found a cool idea that utilizes a trick. Despite the fact that parent and child pages are form different domain, they can access each other's URL (location.href). So, when the child want to do something on the parent page, it does as follows:

1. Child page modifies the location.href of the parent page by appending a fragment identifier (The hash part of the URl, such as:

http://www.mysite.com/default.aspx#introduction 

here #introduction is the fragment identifier). The fragment identifier value should usually be the parameter value that the child page wants to send to the parent page.

2. The parent page continuously polls it's URL value at a certain time interval and whenever it detects a change in its URL value (location.href), it splits the fragment identifier value and updates its own DOM.

Using the same technique, the parent page also can trigger some change in the child page within an IFrame.

I know you loved it. You can see a demo here : http://ajaxify.com/run/crossframe



Enjoy!

Tuesday, August 17, 2010

Asp.net TreeView control that expands from right side!


DARE TO SHARE?
Suppose you have a TreeView control in your Aspx page, which is as follows:

<asp:TreeView ID="TreeView1" ExpandDepth="1" runat="server">
    <Nodes>
        <asp:TreeNode Text="Department">
            <asp:TreeNode Text="HR" Value="D1">
                <asp:TreeNode Text="Employees">
                    <asp:TreeNode Text="Bradley" Value="E1" />
                    <asp:TreeNode Text="Whitney" Value="E2" />
                    <asp:TreeNode Text="Barbara" Value="E3" />
                </asp:TreeNode>
            </asp:TreeNode>
            <asp:TreeNode Text="Accounting" Value="D2">
                <asp:TreeNode Text="Employees">
                    <asp:TreeNode Text="John" Value="E4" />
                    <asp:TreeNode Text="Tomas" Value="ID-5678" />
                </asp:TreeNode>
            </asp:TreeNode>
        </asp:TreeNode>
    </Nodes>
</asp:TreeView>

When viewed in the browser, the TreeView control's output will be shown as follows:


Now, what if you want the TreeView output to be displayed like this?

You may wonder, why would on earth such a requirement could exist! But, this is a very common requirement for sites that uses Arabic language (Because, Arabic language starts from right to left, unlike English).

So, here is how to do it. Pretty simple. You just need to add this piece of line in the CodeBehind:

TreeView1.Attributes["dir"] = "rtl";

Enjoy!

Monday, August 16, 2010

Interesting behaviour with RequredFieldValidator with Display="Dynamic"


DARE TO SHARE?
There is an interesting issue with the RequiredFieldValidator control when the Display="Dynamic" is set. Suppose you have the following piece of code in your Aspx page:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1"
Display="Dynamic" ErrorMessage="Input is required."></asp:RequiredFieldValidator>

<asp:Button ID="Button1" runat="server" Text="Click Me" />

Now, the following series of activity will cause an interesting situation:
  • 1. Browse the page. You will see a Text box and a button.
  • 2. Click on the Button without providing any value in the text box. A validation message will be shown.
  • 3. Now, type some text within the text box and click on the button again.
  • 4. The button click won't do any server postback. Rather, the validation message will be disappear and the button will jump from it's position to left.
  • 5. Click on the button again and this time postback will occur.
Is this a bug with the Validation Control?

I wouldn't call it a bug. We need to understand what really is happening under the hood.

When you set Display="Dynamic" , the Validator controls style property is actually set as "display:none" and hence, it does not retain any space when the validator is now shown.

If you use firebug, you will see that, the Validator control will render the following HTML:
 
<span style=" display: none;" id="RequiredFieldValidator1">RequiredFieldValidator</span>

And, when you set Display="Static", the Validator control's style  property is actually set  as
"visibility:hidden", which actually retains space in the UI when the validator is not shown.
If you use firebug, you will see that, the Validator control will now render the following HTML:

<span style=" visibility: hidden;" id="RequiredFieldValidator1">RequiredFieldValidator</span>
Now, let me explain what happens when the Display="Dynamic" is set.
  • You browse the page and click the button without placing any text in the text box. The validation error message is being shown.
  • You put some text in the text box and tries to click the button. This results in the "onmouseout" javascript event firing on the text box control (Before firing the "onclick" event on the button), which results in the validator to validate the text box again, no error is found and the validator control's style property is set to "display:none".
  • This causes the validator control's corresponding HTML element (span) to give up it's space in the UI and hence the whole UI is repainted in the browser. So, the button finds it's new place and occupies the space that was retained by the validator control's space (span).
  • The while UI is repainted before your click event is executed on the button. So, in reality, your click event on the browser is not executed at all. So, nothing happens and you need to click again on the button.
To verify the above explanation, you can do a quick test as follows:
  • Refresh the browser again.
  • Click the button without placing any text in the text box. The validation error message will be shown.
  • Write some text in the text box and click on any where on the browser (not on the button).
  • This will cause the "onmouseout" event of the text box, validator will be fired, the error message will be gone, and the button will replace the validation message's place. Same result.
So, its not actually a bug. Rather, its just that we have to understand what happens under the hood when we are setting Display="Dynamic" and this we need to adjust our codes/implementation accordingly.

Interesting, no?

Path related issues with Server controls in Code behind


DARE TO SHARE?
In previous two posts we had seen how the Asp.net runtime resolves relative paths for HTML elements and Server controls and what are the best practices for setting paths appropriately. In all cases, we've discussed setting appropriate paths in the XHTML markups, rather then the CodeBehind files.

In this post we will explore the path resolving issues in the CodeBehind and other areas (Not in the Markups).

Control.ResolveUrl(string path)

We can of course set path/urls at the XHTML markups if the paths/urls are well known in design time. But, if for any reason if the path/url is not known in advance (Say, the path/url will var based upon some condition) or simply you are more interested to set the paths/urls in the back-end, yo need to know a programmatic way for resolving correct relative paths.

At the most basic level, each Server control has a ResolveUrl() method (Inherited from the base Control class), that accepts a string path/url value. So, if you have a Server control as follows:

<asp:Image ID="Image1" runat="server" />

You can set the ImageUrl property in the CodeBehind as follows:

Image1.ImageUrl = Image1.ResolveUrl("~/images/action.jpg");

This assumes that the action.jpg is available in this relative path : /images/action.jpg. Note that, you have to supply a "root relative" path that starts with the Tilde ("~"), to get the correct relative path.

I explored the HTML markup using FireBug, that is rendered for setting the markup <asp:Image>, and found that, the HTML is a little difference with the HTML that is rendered for setting ImageUrl in the markup, which is interesting. Here is the difference:

HTML generated for setting ImageUrl at Markup:

<img style="border-width: 0px;" src="../images/action.jpg" id="Image1">

HTML Markup generated for setting ImageUrl at CodeBehind:

<img style="border-width: 0px;" src="/WebSite3/images/action.jpg" id="Image1">

Note that, the two URLs are little bit different. First one is relative in terms of current page location within /Pages/Default.aspx and Second one is relative in terms of web application's root folder. But, in either case, the request image will be rendered from correct location in the browser.

As a Page or a User control is also a control, that means, you can also call the ResolveUrl() in the following way:

Image1.ImageUrl = this.ResolveUrl("~/images/action.jpg");

VirtualPathUtility.ToAbsolute(string path)

As each control has the ResolveUrl() method, it is easily possible to invoke it and get the correct relative path for any server control (By supplying the root-relative path that starts with the Tilde "~" ). But, what if you have to resolve a relative path from within the HttpHandler or a HttpModule, or even, from within a class library?

Fortunately, there is an easy way. You can use the following method that accepts the same parameter argument (Like ResolveUrl()).

VirtualPathUtility.ToAbsolute(string path)

The VirtualPathUtility has many other utility methods that aids in calculation of various path related logic, that will make our life easier.

Saturday, August 14, 2010

Path related issues with Asp.net Server controls


DARE TO SHARE?
In the last post, I had some discussions on path related issues for HTML elements. The purpose was to make a ground work for better-understanding Asp.net Server control's path related issues.

Almost for all HTML element, there is a corresponding Asp.net Server control. For HTML img element, we use the following server control:

<asp:image id="Image1" ImageUrl="~/image/action.png" runat="server"/>

Note that, the ImageUrl's value is usually set by using "Pick URL" tool from the visual studio intellisence.



And, if the path is set by clicking the "Pick URL" for any server control, the path starts with the character "~".

What is "~"?

"~" (Tilde) is a special character that instructs the Asp.net run time to resolve the relative path that is required to navigate to the web application's root folder, from the current directory of the current page, which contains this character.

Let us see some examples:

Example1:

Say, we have an web page in the following URL :

http://www.mysite.com/pages/default.aspx

Which contains an <asp:Image /> element with the ImageUrl value set as :

</asp:Image ImageUrl="~/image/action.png" id="Image1" runat="server"/>

So, the Asp.net runtime will replace the "~" with the relative path that navigates the runtime from the current folder (
http://www.mysite.com/pages/) to the web application's root folder (http://www.mysite.com/). That is, one folder up ( "../" ).

And hence, the full relative URL be resolved as : "../image/action.jpg"

And, the absolute URL will be resolved as : http://www.mysite.com/images/action.jpg

Example2:

Say, we have an web page in the following URL :

http://www.mysite.com/default.aspx

Which contains an element with the ImageUrl value set as :

ImageUrl="~/image/action.png"

So, the Asp.net runtime will replace the "~" with the relative path that navigates the runtime from the current folder (http://www.mysite.com/) to the web application's root folder (http://www.mysite.com/). That is, with a blank ( "" ) as both paths are same

And hence, the full relative URL be resolved as : "/image/action.jpg"

And, the absolute URL will be resolved as : http://www.mysite.com/images/action.jpg

User control related path issues:

Suppose our Asp.net web application has an organized folder structure for aspx pages and user controls (ascx) within the root folder for laying out the pages and controls in a logical structure. Let us assume, we have a following scenario:

A user control is located at : /UserControls/Products/UCProductDetails.ascx
the user control has an img element : <img src=""..> (The src is not set yet)
A page is located at :/Pages/Products/ProductDetails.aspx, which uses this user control.
Another page is located at : /Pages/Home.aspx, which also uses this user control.

Note that, the img element is within the user control. So, no matter what the user control's location is within the folder structure, the runtime will try to determine the relative path of the image based upon the current location of the page, that contains the user control.

So, if the currently browsed page is http://www.mysite.com/Pages/Products/ProductDetails.aspx,

The src value of the img element should be set as:

src = "../../images/details.jpg"

But, if the currently browsed page is http://www.mysite.com/Pages/Home.aspx,

The src value of the img element should be set as:

src = "../images/details.jpg"

We have a problem :(

To solve this, we need to replace the HTML img control with an Server control and set the ImageUrl property using the "~" (Tilde) that is:

ImageUrl = "~/images/details.jpg"

Or, modify the img element as follows:

<img runat="server" id="imgDetails" src="http://www.blogger.com/images/details.jpg" />

This will instruct the Asp.net runtime to calculate the correct relative URL of the image based upon the currently browsed page's folder location, no matter where the page or user control is within the folder structure of the web application.

What about other elements?

There are other HTML elements and Asp.net Server controls that have the same path related issues when used within the user controls and, the same logic should be applied to them to solve the issues. For examples, a User control can have the following HTML elements:

<script src="../js/common.js" type="text/javascript" language="javascript"/>
<link rel="Stylesheet" href="../style/common.css" type="text/css" />

As this user control could be used from any web page within the web application, there will be path related issues with this user control and to solve this issue, the above elements should be modifled as follows:

<script runat="server" src="~/js/common.js" type="text/javascript" language="javascript"/>
<link runat="server" rel="Stylesheet" href="~/style/common.css" type="text/css" />


And, if the user control have any other HTML element or server control that has the src, or, href, or, ImageUrl property, these should all be set with a path that starts with the "~" (Tilde) so that, the asp.net runtime is able to calculate the correct relative path for the corresponding element no matter where the element is used.

To summarize:

If any user control has an HTML element or Asp.net server control that has any kind of path property (src or href or ImageUrl), the path value should be started with the "~/" (Tilde)

If any page has an HTML element that has any kind of path property, the path values should be started with a relative path "/" or "../" (Given that, the correct relative path is set). And, for any server control, the property values should be start with the "~/"(Tilde).

Happy path finding :)

Friday, August 13, 2010

Path related issues with HTML elements


DARE TO SHARE?
In my early days in Asp.net applications, I can remember I had troubles with setting appropriate paths for different resources (Images/documents/videos etc) in Asp.net applications. That happened due to unclear understanding of paths and I wanted to address this issue in this post today.

In an Asp.net applications, we either use HTML elements or a Server controls for adding resource (Such as, an image) in the page. There are path issues for both HTML elements and Server controls, and, understanding the basic path issues for HTML elements will let us clearly understand the Server control's path issues later.

Let us assume we have an img element in one of the pages with the src property set to the actual image's relative path as follows:

src = "/images/action.jpg"

Based upon this relative path, browser calculates an absolute path and sends a request to the server to obtain the actual image and render in the browser. Now, if for any reason the src value is set inappropriately, the image will not be appearing in the page.

So, let us try to understand how browser actually determines the absolute image url based upon the relative url set to the src attribute.

Path calculation basic rule:

In general, images and other resources are mostly kept within the web application's root folder, in a designated directory. We usually provide a relative path of the images (And other resources) and browser calculates the absolute image URL using the provided relative path at the src attribute. We can of course set absolute URLs for all images and resources in our application, but, this is highly discouraged because in case the site URL is changed later for some reason, all of the src attribute values will needed to be changed. That would be horrible.

OK, let us start discussing the path issues. let us assume the following scenario:

The currently browsed page is : http://www.mysite.com/default.aspx
An img src in the page is set as : src = "/images/action.jpg"

So, the absolute URL determined by the browser will be http://www.mysite.com/images/action.jpg, and if the action.jpg is available within the "images" folder of the web root, the image will be displayed in the browser.

A little complexity:

Not all pages are implemented directly within the web application's root folder and its pretty common to implement pages under some folder structure. So, let us assume we have a following situation now:

The currently browsed page is : http://www.mysite.com/pages/default.aspx,
The img src in the page is set as : src = "/images/action.jpg"

This will fail to load the image and show in the browser. Why? well, its because, the browser now calculates the absolute image path as follows:

http://www.mysite.com/pages/images/action.jpg

And, the image is not available in the above URL.

So, how to fix this path?

You can fix it in two approaches, one is using relative path based upon the current directory and another is using relative path based upon the site URL.

Relative path based on current directory:

Let us assume the following scenario:

Current directory of your page is : http://www.mysite.com/pages/
And, your current image path is : http://www.mysite.com/images/

So, for calculating the correct absolute path, you should go one level up (by using "..") from the "pages" directory and then add the imge's relative path by adding "/images/action.jpg". So, the corrected src should be set as follows this time:

src = "../images/action.jpg"

And, based upon the above path, browser will be able to determine the correct absolute image URL as follows:

http://www.mysite.com/images/action.jpg

Relative path based on Site URL:

Alternatively, you can use an image path that would let the browser calculate the absolute url based upon the web site's base URL. For this, you have to set the src value as follows:

src = "images/action.jpg" (Note that, the path does not starts with a "/" this time)

This will result in the browser calculating the absolute path as follows, no matter in what folder structure your page is under the web root folder.

http://www.mysite.com/images/action.jpg

So, the browser will be able to display the image successfully in the browser.

CAUTION!

The 2nd strategy should be used only if the web application is deployed under a web site, rather than a virtual directly in the IIS. The reason is, browser calculates the full URL path based upon the web site's root URL (Not the virtual directory's root url) plus the relative url.

So, if we had a web application deployed under a virtual directory as follows:

http://www.mysite.com/app/pages/default.aspx

And, if we set the src attribute of an image element in this page as follows:

src = "images/action.jpg"

Browser will calculate the absolute URL as follows:

http://www.mysite.com/images/action.jpg

And, the above URL request will fail this time because, the correct image URL is actually as follows:

http://www.mysite.com/app/images/action.jpg

Hope to discuss the path issues for Server controls in the next post. Cheers!

System.Web.HttpException: The remote host closed the connection. The error code is 0x80072746


DARE TO SHARE?
Today we got an error mail from one of our production sites, where we had configured to send the exception details to an email address so that we can troubleshoot. Following was the error message:

System.Web.HttpException: The remote host closed the connection. The error code is 0x80072746

I was assigned to troubleshoot this issue and found that, this exception generally happens when you have download functionality in your Asp.net applications and when user starts the download process, but, the download process does not complete for one of the following reasons:
  • User cancels the download
  • User navigates to another page
  • User closes the page
  • The connection closes
We have a file download page that allows the user to download files. This page internally hits another page that actually writes the file content to the browser. From the exception detailed message, I got to know that, the exception was taking place while executing the following URL:

/Pages/DocumentDownload.aspx?documentID=101

Detailed reason:

By default, Response.BufferOutput property is set to "true" and hence the Asp.net process writes data/output to the buffer, instead of the output stream. When the page is finished processing, the buffered output is flushed to the output stream and hence, sent to the browser. This is usually done to avoid multiple data transfer process over the network and hence optimize performance by sending the overall page output in a single Response.

But, when a page writes a file content (Or, a file) in the Response, usually, we used to flush the buffer immediately after we write the file content in the output stream, so that, the file content is sent to browser immediately, instead of waiting for the page to complete its' execution process process. In general, following is the code that we usually use.

Response.WriteFile("A File"); //Or, //Response.BinaryWrite(FileContent)
Response.Flush();
Response.End();

Now, imagine the following scenario:
  • User started to download the file from the download prompt (As a result of the Response.WriteFile()), data is stored in buffer and the buffer is overflown and a stream of binary data started to flow from server to client.
  • For some reason, the download process is cancelled (For one of the above mentioned reasons)
  • Meanwhile, the Asp.net process tries to Flush() the buffer content to the output stream, that is already closed by the client.
  • Exception occurs.
Probable solution:

Despite the fact that, this exception is not a very important one and can be ignored, but, we can have a try to solve this issue.Trying to avoid the Response.Flush() may result in not occurring the exception and the File download codes could be written as follows:


Response.Buffer = false;
//Disabling buffering so that, the file content is immediately written to output stream

Response.Clear();
Response.ContentType = projectDocument.MimeType;
Response.AppendHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(projectDocument.FileName));
Response.BinaryWrite(projectDocument.FileContent);

//Response.Flush();
//Response.End();
//No need to Flush() and End() the response as the output stream is not buffered
I didn't test it yet in the production server, but, hopefully this would stop the exception from being generated.