Thursday, January 22, 2009

Bug in .NET FileUpload control

I discovered a bug in the .NET FileUpload control yesterday. I found that when I select a file and click on the Upload button, the "Click" event would fire TWICE. This issue was not easily identifiable until I added some additional code that called a SQL Job after the file was uploaded. I was getting the following SQL Server Agent Warning in the Event Viewer:

Exception information: Exception type: SqlException Exception message: SQLServerAgent Error: Request to run job (from User ) refused because the job already has a pending request from User .

I found out that the SQL Job was being called twice and therefore causing the above error. I then added lots of debugging statements in my code and found that "Click" event was firing two times. And I did not have any looping constructs in my code. As a result my file was being uploaded TWICE, and the SQL Job was also being called TWICE. Uploading the file twice was not an issue in my case, as the goal was to overwrite if the file exists already. But calling the SQL Job twice was an issue.

Turns out that you DON'T NEED to specify the OnClick event in the button code like this. Having the OnClick event in the button code will cause the event to fire twice.

<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />

To prevent the Click event from firing twice, DO NOT specify the OnClick event. The updated code is shown below. This will cause the Click event to fire once.

<asp:Button ID="btnUpload" runat="server" Text="Upload" />

Happy Uploading!