473,396 Members | 2,039 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

File not uploading but not getting errors.

347 100+
I have a site that I've almost completed and while testing it today noticed that it's not uploading any files or doing the bulk insert in SQL that I need it to. Here is my codebehind:

Expand|Select|Wrap|Line Numbers
  1. Imports System.IO
  2. Imports System.Data   
  3. Imports System.Data.SqlClient
  4. Partial Class _Default
  5.     Inherits System.Web.UI.Page
  6.     Protected Sub Submit1_Click(ByVal sender As Object, ByVal e As EventArgs)
  7.  
  8.         If Not File1.PostedFile Is Nothing And File1.PostedFile.ContentLength > 0 Then
  9.             Dim fn As String = System.IO.Path.GetFileName(File1.PostedFile.FileName)
  10.             Dim SaveLocation As String = Server.MapPath("Data") & "\" & fn
  11.             Try
  12.                 File1.PostedFile.SaveAs(SaveLocation)
  13.                 Response.Write(<center>Thank you for your submission.</center>)
  14.  
  15.                 ' get the file that was submitted and check if it was .txt file   
  16.                 Dim theFile As FileInfo = New FileInfo(SaveLocation)
  17.                 If theFile.Extension <> ".txt" Then
  18.                     Response.Write(<center>Please submit a text file.</center>)
  19.                 End If
  20.  
  21.                 Dim importPath As String = Server.MapPath("Data") & "\upload.txt"
  22.                 If File.Exists(importPath) Then
  23.                     ' do something with existing upload.txt file, maybe archive?   
  24.                 End If
  25.  
  26.                 ' rename the uploaded file to upload.txt for importing   
  27.                 theFile.MoveTo(importPath)
  28.  
  29.                 ' and bulk import the data:   
  30.                 Dim connection As String = ConfigurationManager.ConnectionStrings("Dialerresults").ConnectionString
  31.                 Dim results As New DataTable
  32.  
  33.                 Using con As New SqlConnection(connection)
  34.                     con.Open()
  35.  
  36.                     ' execute the bulk import   
  37.                     Using cmd As SqlCommand = con.CreateCommand
  38.                         cmd.CommandText = "bulk insert dialerresults from '" & importPath & "' " & _
  39.                             " with ( fieldterminator = ',', rowterminator = '\n' )"
  40.                         cmd.ExecuteNonQuery()
  41.                     End Using
  42.                 End Using
  43.  
  44.             Catch Exc As Exception
  45.                 Response.Write("Error: " & Exc.Message)
  46.             End Try
  47.         Else
  48.             Response.Write(<center>Please select a file to upload.</center>)
  49.         End If
  50.  
  51.     End Sub
  52. End Class
Can anyone see why the file is not being uploaded? I'm sure its something simple but I've been working on this for a while and may have missed something. Any assistance would be welcome.

Thank you,

Doug
May 5 '10 #1
54 4153
Frinavale
9,735 Expert Mod 8TB
First thing that comes to mind is that you've placed your File1 in an UpdatePanel.
UpdatePanels do not support the upload of files...the files will simply not get to the server.

-Frinny
May 5 '10 #2
dougancil
347 100+
Frinny,

I'm sorry but I'm new to asp.net and know nothing of UpdatePanels. What would be a good workaround for this issue?

Thank you,

Doug
May 5 '10 #3
Frinavale
9,735 Expert Mod 8TB
Well if you don't know what an UpdatePanel is then it's very unlikely that you are using it. So just ignore my previous point.

To be quite honest, after skimming through your code right now, I'm not sure that your posted code would even compile. Line 18 is going to cause you problems.


Have you tried stepping through the application and watching what happens to see if you can figure out what's going on?

-Frinny
May 5 '10 #4
Frinavale
9,735 Expert Mod 8TB
You should probably check out this MSDN documentation on the FileUpload control. It has a working example that you could probably use to get you started.

-Frinny
May 5 '10 #5
dougancil
347 100+
Frinny,

This code is comprised of code I've written and something that someone else wrote. The code does compile and I have tried loading two different files (one a .txt file and one a .pdf file) and neither would show up in the destination folder. I've built the page, and debugged it with no errors. When I tried to upload the .pdf page, what should have happened, was that I should have received an error that that files of that format were not accepted and I didn't get that message either. Any ideas as to what may be causing that? Would those be symptoms of a UpdatePanel issue?
May 5 '10 #6
Frinavale
9,735 Expert Mod 8TB
If you had put your FileUpload control into an UpdatePanel then the FileUpload control's PostedFile will always be nothing.

If you have done this, take the FileUpload control out of the UpdatePanel.
May 5 '10 #7
dougancil
347 100+
Frinny,

Can you point out to me where the UpdatePanel is in my code? I'll gladly take the lines of code out once I can identify them.
May 5 '10 #8
Frinavale
9,735 Expert Mod 8TB
You would have to post the ASPX page "code" (look at the page and click "source" view button).

I can't tell unless you post that code.
May 5 '10 #9
dougancil
347 100+
Expand|Select|Wrap|Line Numbers
  1. <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
  2.  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4.  
  5. <html xmlns="http://www.w3.org/1999/xhtml">
  6. <head runat="server">
  7.     <title>Upload Page</title>
  8.     <style type="text/css">
  9.         #form1
  10.         {
  11.             height: 128px;
  12.         }
  13.         #File1
  14.         {
  15.             top: 66px;
  16.             }
  17.         #Submit1
  18.         {
  19.             top: 103px;
  20.             left: 591px;
  21.         }
  22.         #TextArea1
  23.         {
  24.             z-index: 1;
  25.             left: 303px;
  26.             top: 45px;
  27.             position: absolute;
  28.         }
  29.     </style>
  30. <script language="javascript" type="text/javascript">
  31. // <!CDATA[
  32.  
  33. function Submit1_onclick() {
  34.  
  35. }
  36.  
  37. // ]]>
  38. </script>
  39. </head>
  40. <body>
  41.     <form id="form1" enctype="multipart/form-data" runat="server">
  42.     <br />
  43.    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  44.     <br />
  45. <input type="File" id="File1" name="File1" runat="server" 
  46.         style="position: absolute; left: 512px;" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  47. <br />
  48. <input type="Submit" id="Submit1" value="Upload" runat="server" 
  49.         style="position: absolute; height: 30px;" 
  50.         onclick="return Submit1_onclick()" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  51.     </form>
  52. </body>
  53. </html>
  54.  
Frinny, there is my code for the page. As you can see, there's not much too it. I know that it's not really clean but I'll worry about cleaning it up later. Right now I'm just trying to get the "mechanics" of this working.

Thank you for taking a look at it,

Doug
May 5 '10 #10
Frinavale
9,735 Expert Mod 8TB
Oh....
Well you aren't using an UpdatePanel ;)
But you are using an HTML input element.

You should be using the ASP.NET FileUpload control control instead!!
May 5 '10 #11
Frinavale
9,735 Expert Mod 8TB
Oh wait there's another thing
You may not even be reaching the code that you have posted because you don't have an asp.net Button on the page either!

Change your submit HTML button into an ASP.NET button as well.
May 5 '10 #12
Frinavale
9,735 Expert Mod 8TB
Like this:
Expand|Select|Wrap|Line Numbers
  1. <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
  2.  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4.  
  5. <html xmlns="http://www.w3.org/1999/xhtml">
  6. <head runat="server">
  7.     <title>Upload Page</title>
  8.     <style type="text/css">
  9.         #form1
  10.         {
  11.             height: 128px;
  12.         }
  13.         #File1
  14.         {
  15.             top: 66px;
  16.             }
  17.         #Submit1
  18.         {
  19.             top: 103px;
  20.             left: 591px;
  21.         }
  22.         #TextArea1
  23.         {
  24.             z-index: 1;
  25.             left: 303px;
  26.             top: 45px;
  27.             position: absolute;
  28.         }
  29.     </style>
  30.  
  31. </head>
  32. <body>
  33.     <form id="form1" enctype="multipart/form-data" runat="server">
  34.     <br />
  35.  
  36.     <br />
  37. <asp:FileUpload ID="File1" runat="server" 
  38.         style="position: absolute; left: 512px;" />
  39. <br />
  40. <asp:Button id="Submit1"  runat="server" 
  41.         style="position: absolute; height: 30px;" 
  42.         onclick="Submit1_Click" />
  43. </body>
  44. </html>
May 5 '10 #13
dougancil
347 100+
Frinny,

So if I change the html button to an asp.net button will it automatically rewrite the codebehind to reflect the upload controls in Visual Studio?
May 5 '10 #14
Frinavale
9,735 Expert Mod 8TB
I'm not sure.

The C# IDE is different the the VB.NET IDE and I work with VB.NET most of the time.

But typically what happens is that when you change your HTML code into an ASP.NET control, that control is "registered" into the .designer.cs file so that it is accessable to work in both the ASPX code and your C# code.

ASP.NET controls have 2 aspects to them: client side and server side. In fact when your application has finished executing the server-side code it Renders the page's output which is sent to the browser. The only thing the browser understands is HTML (as you already know). So when the server-side code finishes executing it turns all of the ASP.NET controls into HTML.

The important thing is that the HTML is generated and maintained by ASP.NET

This means that if the user clicks an ASP.NET button on the page, you can handle the buttons Click Event in your C# server code.

If you use just regular HTML for the button then there is no Click Event generated because ASP.NET isn't in control of it.

So it's important that you use ASP.NET controls when developing ASP.NET applications/websites :)


Anyways,

You declare your button in the ASPX code as I have shown you...This will give you access events and properties (and a lot more) for the button in your C# code that you never had before.
May 5 '10 #15
dougancil
347 100+
Frinny,

So I changed the button to an asp.net button and now when I attempt to upload a file, I get the following on my page:

Thank you for your submission.
Error: Cannot create a file when that file already exists.
Thank you for your submission.
Error: Cannot create a file when that file already exists.

That was when I try to upload a .txt file, when I try to upload anything but that this is what I get:

Thank you for your submission.
Please submit a text file.
Error: Cannot create a file when that file already exists.
Thank you for your submission.
Please submit a text file.
Error: Cannot create a file when that file already exists.

So it's duplicating the error text and it's not aligning them to center as they should be. I realize that I should put a label to output the errors too but as I said, right now I just want to get the mechanics to work the way that they should. Any idea why it would duplicate the error responses?
May 5 '10 #16
Frinavale
9,735 Expert Mod 8TB
Well I kind of knew that was your next question.
You should never use Response.Write in your C# code.
If you do then the content that you're writing to the page will be placed somewhere invalid....mainly it's placed above the <html> element...which is clearly invalid

What I recommend is that you add an ASP.NET Label control to the page in the place where you want the error message to appear.

When you encounter an error set this Label's Text property to the text that you want to display.

The center tag has been obsolete for a very long time anyways.
You should use CSS instead ;)

-Frinny
May 6 '10 #17
dougancil
347 100+
Frinny,

Could that also be the reason why the file is not being uploaded?
May 6 '10 #18
Frinavale
9,735 Expert Mod 8TB
?? I thought the file is being uploaded ??
May 6 '10 #19
dougancil
347 100+
My apologies, yes in fact the file is being uploaded. I have tried to take the response.write element out and absolute position a label. The reason I wanted to do that is to drap and drop the response write label to beneath the upload button but found that I can't do that. How is the best way to accomplish positioning the label beneath the upload button without completely re-writing my page?
May 6 '10 #20
dougancil
347 100+
Also,. the file is being uploaded but the sql bulk insert isn't working. The error message I got is this:

Thank you for your submission.Error: Object reference not set to an instance of an object.Thank you for your submission.Error: Cannot create a file when that file already exists.
May 6 '10 #21
Frinavale
9,735 Expert Mod 8TB
First we'll address why you can't get your label in the correct spot.
Could you post your aspx code again?
May 6 '10 #22
dougancil
347 100+
Expand|Select|Wrap|Line Numbers
  1. <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
  2.  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4.  
  5. <html xmlns="http://www.w3.org/1999/xhtml">
  6. <head runat="server">
  7.     <title>Upload Page</title>
  8.     <style type="text/css">
  9.         #form1
  10.         {
  11.             height: 189px;
  12.             width: 919px;
  13.         }
  14.         #File1
  15.         {
  16.             top: 66px;
  17.             }
  18.         #Submit1
  19.         {
  20.             top: 103px;
  21.             left: 591px;
  22.         }
  23.         #TextArea1
  24.         {
  25.             z-index: 1;
  26.             left: 303px;
  27.             top: 45px;
  28.             position: absolute;
  29.         }
  30.     </style>
  31. <script language="javascript" type="text/javascript">
  32. // <!CDATA[
  33.  
  34. function Submit1_onclick() {
  35.  
  36. }
  37.  
  38. // ]]>
  39. </script>
  40. </head>
  41. <body>
  42.     <form id="form1" enctype="multipart/form-data" runat="server">
  43.     <br />
  44.  
  45.     <br />
  46. <asp:FileUpload ID="File1" runat="server" 
  47.         style="position: absolute; left: 512px;" />
  48. <br />
  49. <asp:Button id="Submit1"  runat="server" 
  50.         style="position: absolute; height: 30px; top: 101px; left: 572px;" 
  51.         onclick="Submit1_Click" Text="Upload" />
  52.         </form>
  53. </body>
  54. </html>
  55.  
May 6 '10 #23
Frinavale
9,735 Expert Mod 8TB
I don't see a Label at all on your page.
If you want it to appear right under the button then place on there:
Expand|Select|Wrap|Line Numbers
  1. <body>
  2.     <form id="form1" enctype="multipart/form-data" runat="server">
  3.     <br />
  4.  
  5.     <br />
  6. <asp:FileUpload ID="File1" runat="server" 
  7.         style="position: absolute; left: 512px;" />
  8. <br />
  9. <asp:Button id="Submit1"  runat="server" 
  10.         style="position: absolute; height: 30px; top: 101px; left: 572px;" 
  11.         onclick="Submit1_Click" Text="Upload" />
  12. <br />
  13. <asp:Label id="message" runat="server"></asp:Label>
  14.  
  15.         </form>
  16. </body>
  17. </html>
May 6 '10 #24
dougancil
347 100+
But when I show that in design mode, the label is on the far left hand side of the screen and not beneath the upload button. Secondly, with that, how do I get the error message to show there? I'm assuming at that point that I'm doing some sort of validator. What would be the best validation to use for that? Custom or RegularExpression?
May 6 '10 #25
Frinavale
9,735 Expert Mod 8TB
It's simple html/css stuff here.

I'm sorry I didn't realize your button was absolutely positioned (seems a bit odd to me)....I think you even mentioned it before.

Since the upload control, the button and the error message (the message label) belong to the same grouping they should be placed in the same block. You could either place them into a div element or you could place them into an asp.net Panel element (which renders as a div). I'd choose the panel element personally because it's assigned a unique ID by ASP.NET and you may want to be able to access it in your C# code.

You can set the style of a Panel the same way as you would set the style of a div. The only difference is that if you have a CSS class that you want to use for the Panel you would set the CssClass property (whereas you'd just set the class property of the div element).

So, the following should work for you:
Expand|Select|Wrap|Line Numbers
  1. <body>
  2.     <form id="form1" enctype="multipart/form-data" runat="server">
  3.       <asp:Panel ID="UploadControlsSection" runat="server" style="position: absolute; left: 512px;">
  4.         <asp:FileUpload ID="File1" runat="server"  />
  5.         <br />
  6.         <asp:Button id="Submit1"  runat="server" 
  7.             style="height: 30px; margn-left:60px;" 
  8.             onclick="Submit1_Click" Text="Upload" />
  9.         <br />
  10.         <asp:Label id="message" runat="server"></asp:Label>
  11.      </asp:Panel>
  12.    </form>
  13. </body>
  14. </html>

All of your validation is currently being done server side (in your C# code).
If you encounter an error you should set the message.Text = "error message" to display a message to the user.

You aren't using any custom validators (which run client side) or anything of the sort at this point.

I have a feeling that you are trying to do too many things at once.
First get this working...get your fie to upload, do your validation server side, get your sql update to work.


Then you can think about adding custom client side validation to your page.

-Frinny
May 6 '10 #26
dougancil
347 100+
Ok so the file is being uploaded but now I've noticed that there are two files that are being put in the data folder. One is whatever the document is called (in my case it was called test) and also the file that is being renamed. There should only be one file in the directory called "upload.txt." Secondly, I don't think that the SQL bulk insert command (at least from the code side) is working at all.
May 6 '10 #27
Frinavale
9,735 Expert Mod 8TB
dougancil:
There should only be one file in the directory called "upload.txt."
This doesn't make sense.

Say you have 2 users using the website at the same time and both users upload a file to the server at the same time...in this case one of the user's files will be over written with the other user's files.

Each user should be able to create a file of their own to avoid this problem.

dougancil:
Secondly, I don't think that the SQL bulk insert command (at least from the code side) is working at all.
Are you seeing the same error message as before?

-Frinny
May 6 '10 #28
dougancil
347 100+
Frinny,

The way that this is going to be organized is that one user per client will have access to upload pages to this server. They will be divided out by directories on the server so in theory, there should never be 2 users on this page from the same client at the same time trying to upload files.

Secondly, I am seeing this as an error:

Thank you for your submission.Error: Object reference not set to an instance of an object.Thank you for your submission.Error: Cannot create a file when that file already exists.

I can verify that there are two files in the remote directory (the "Data" directory) and the file is a comma delimited file which has been tested and will upload to the sql server with the command that I have in the codebehind.
May 6 '10 #29
Frinavale
9,735 Expert Mod 8TB
Could you please post your C# code so that I can see what you have?

Basically you're getting an error message stating that you cannot create a file with the same name...you should either overwrite the file or delete it and recreate when you save the file to the server.

You are also getting an "Object reference not set to an instance of an object" error which means you are trying to access something that doesn't exist yet (an object that hasn't been instantiated yet).

If you could point out which lines these errors are occurring on when you post your C# code that would be very helpful.
May 6 '10 #30
dougancil
347 100+
Frinny,

This is .vb code not .cs but here's the code. Also, the error I'm getting is when I press the upload button. It's not giving me a line number for the error.
Expand|Select|Wrap|Line Numbers
  1. Imports System.IO
  2. Imports System.Data   
  3. Imports System.Data.SqlClient
  4. Partial Class _Default
  5.     Inherits System.Web.UI.Page
  6.     Protected Sub Submit1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Submit1.Click
  7.  
  8.         If Not File1.PostedFile Is Nothing And File1.PostedFile.ContentLength > 0 Then
  9.             Dim fn As String = System.IO.Path.GetFileName(File1.PostedFile.FileName)
  10.             Dim SaveLocation As String = Server.MapPath("Data") & "\" & fn
  11.             Try
  12.                 File1.PostedFile.SaveAs(SaveLocation)
  13.                 Response.Write("Thank you for your submission.")
  14.  
  15.                 ' get the file that was submitted and check if it was .txt file   
  16.                 Dim theFile As FileInfo = New FileInfo(SaveLocation)
  17.                 If theFile.Extension <> ".txt" Then
  18.                     Response.Write("Please submit a text file.")
  19.                 End If
  20.  
  21.                 Dim importPath As String = Server.MapPath("Data") & "\upload.txt"
  22.                 If File.Exists(importPath) Then
  23.                     ' do something with existing upload.txt file, maybe archive?   
  24.                 End If
  25.  
  26.                 ' rename the uploaded file to upload.txt for importing   
  27.                 theFile.MoveTo(importPath)
  28.  
  29.                 ' and bulk import the data:   
  30.                 Dim connection As String = ConfigurationManager.ConnectionStrings("Dialerresults").ConnectionString
  31.                 Dim results As New DataTable
  32.  
  33.                 Using con As New SqlConnection(connection)
  34.                     con.Open()
  35.  
  36.                     ' execute the bulk import   
  37.                     Using cmd As SqlCommand = con.CreateCommand
  38.                         cmd.CommandText = "bulk insert dialerresults from '" & importPath & "' " & _
  39.                             " with ( fieldterminator = ',', rowterminator = '\n' )"
  40.                         cmd.ExecuteNonQuery()
  41.                     End Using
  42.                 End Using
  43.  
  44.             Catch Exc As Exception
  45.                 Response.Write("Error: " & Exc.Message)
  46.             End Try
  47.         Else
  48.             Response.Write("Please select a file to upload.")
  49.         End If
  50.  
  51.     End Sub
  52.  
  53.     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  54.  
  55.     End Sub
  56. End Class
May 6 '10 #31
Frinavale
9,735 Expert Mod 8TB
See the comments I've made in the code
Expand|Select|Wrap|Line Numbers
  1. Imports System.IO
  2. Imports System.Data   
  3. Imports System.Data.SqlClient
  4. Partial Class _Default
  5.     Inherits System.Web.UI.Page
  6.     Protected Sub Submit1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Submit1.Click
  7.  
  8.         If Not File1.PostedFile Is Nothing And File1.PostedFile.ContentLength > 0 Then
  9.             Dim fn As String = System.IO.Path.GetFileName(File1.PostedFile.FileName)
  10. 'The following SaveLocation is going to upload a file with the name of the original file uploaded.
  11. 'I thought that you were supposed to be saving the file as "upload.txt"??
  12. 'I've changed this so that it suits your requirements.
  13. '            Dim SaveLocation As String = Server.MapPath("Data") & "\" & fn
  14. Dim SaveLocation As String = Server.MapPath("Data") & "\upload.txt"
  15.  
  16. 'At this point I would check to see if the file exists already
  17. 'If it does exist Delete the existing one so that the new one can be created
  18. If IO.File.Exists(SaveLocation) Then
  19.   IO.File.Delete(SaveLocation)
  20. End If
  21.  
  22.             Try
  23.                 File1.PostedFile.SaveAs(SaveLocation)
  24. 'Remember how I warned you Not to use Response.Write?
  25. 'I know I said don't use it in your C# code....
  26. 'but the same thing applies to VB.NET code.
  27. 'I've removed this line and I am setting the text of the Message Label instead
  28. '                Response.Write("Thank you for your submission.")
  29. message.Text = "Thank you for your submission"
  30.  
  31.                 ' get the file that was submitted and check if it was .txt file   
  32.                 Dim theFile As FileInfo = New FileInfo(SaveLocation)
  33.                 If theFile.Extension <> ".txt" Then
  34. 'Again Response.Write is not good....Commenting it out
  35. '                    Response.Write("Please submit a text file.")
  36. 'In the following line I'm replacing the message Label's Text with the error mssage
  37. message.Text = "Please submit a text file."
  38.                 End If
  39.  
  40.  
  41. 'What are you doing Here?
  42. 'I'm commenting this whole block of logic out because it doesn't make sense
  43. '                Dim importPath As String = Server.MapPath("Data") & "\upload.txt"
  44. '                If File.Exists(importPath) Then
  45. '                    ' do something with existing upload.txt file, maybe archive?   
  46. '                End If
  47. '                ' rename the uploaded file to upload.txt for importing   
  48. '                theFile.MoveTo(importPath)
  49.  
  50.                 ' and bulk import the data:   
  51.                 Dim connection As String = ConfigurationManager.ConnectionStrings("Dialerresults").ConnectionString
  52.                 Dim results As New DataTable
  53.  
  54.                 Using con As New SqlConnection(connection)
  55.                     con.Open()
  56.  
  57.                     ' execute the bulk import   
  58.                     Using cmd As SqlCommand = con.CreateCommand
  59. 'I changed the command text......
  60. '                        cmd.CommandText = "bulk insert dialerresults from '" & importPath & "' " & _
  61. '                            " with ( fieldterminator = ',', rowterminator = '\n' )"
  62.  
  63.   cmd.CommandText = "bulk insert dialerresults from '" & SaveLocation & "' " & _
  64.   "with ( fieldterminator = ',', rowterminator = '\n' )"
  65.  
  66.                        cmd.ExecuteNonQuery()
  67.                     End Using
  68.                 End Using
  69.  
  70.             Catch Exc As Exception
  71. 'Again Response.Write is not good....Commenting it out
  72. '                Response.Write("Error: " & Exc.Message)
  73. 'You are not seeing a line number that the problem is occurring on
  74. 'because you aren't displaying the StackTrace....
  75. 'In the following line I'm replacing the message Label's Text with the StackTrace of the exception
  76.  
  77. message.Text = Exc.StackTrace
  78.  
  79.             End Try
  80.         Else
  81. 'Again Response.Write is not good....Commenting it out
  82. '            Response.Write("Please select a file to upload.")
  83. 'In the following line I'm replacing the message Label's Text with the error message
  84.  
  85. message.Text = "Please select a file to upload"
  86.         End If
  87.  
  88.     End Sub
  89.  
  90.     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  91.  
  92.     End Sub
  93. End Class
May 6 '10 #32
dougancil
347 100+
Frinny,

I've pasted your code and reloaded the web site. I get the following error:

at _Default.Submit1_Click(Object sender, EventArgs e) in C:\Inetpub\wwwroot\Webfile1\Default.aspx.vb:line 52
May 6 '10 #33
Frinavale
9,735 Expert Mod 8TB
What line is line 52 in the posted code?
May 6 '10 #34
dougancil
347 100+
here is line 52:

Dim connection As String = ConfigurationManager.ConnectionStrings("Dialerresu lts").ConnectionString
May 6 '10 #35
Frinavale
9,735 Expert Mod 8TB
Well I'm not seeing any blue underline squiggles when I take that code and past it into a temporary testing page....

Are you seeing this displayed in your message label when you try to upload the file then?

What is the error message?
May 6 '10 #36
dougancil
347 100+
I am seeing what I posted in the message label beneath the upload button ... but it's showing when I load the page. So the error is there before I even "post" a file.

Here's my connection string in the web.config file:

<add name="Dialeresults" connectionString="server=10.1.1.40;database=dialer results;uid=xxx;password=xxxx;" providerName="System.Data.SqlClient" />
</connectionStrings>
May 6 '10 #37
dougancil
347 100+
Sorry here's the proper post:

<connectionStrings>
<add name="Dialeresults" connectionString="server=10.1.1.40;database=dialer results;uid=xxxx;password=xxxxxxx;" providerName="System.Data.SqlClient" />
</connectionStrings>
May 6 '10 #38
Frinavale
9,735 Expert Mod 8TB
Do you have your connection string defined in your web.config file?
Is it defined with the key value you're using here?


This is probably where you're getting your "object not set to a reference" error.
If you can't see the message then change line 78 to:

message.Text =Exc.Message + " " + Exc.StackTrace
May 6 '10 #39
dougancil
347 100+
I changed line 78 and now get the following error:

Object reference not set to an instance of an object. at _Default.Submit1_Click(Object sender, EventArgs e) in C:\Inetpub\wwwroot\Webfile1\Default.aspx.vb:line 52
May 6 '10 #40
Frinavale
9,735 Expert Mod 8TB
Normally I don't create a test page to help people out but this time I did.

I copied the code we're working on into the test page and noticed a Lot of problems.

First of all you are uploading the file to the server before you are checking the file extension.

What if this file was a virus and all the end user wanted to do was get the virus to the server?

You can check to make sure the file extension is valid before saving it to the server!

In the code I'm posting now I've fixed this problem.
I've also broken the code up into 2 functions: one responsible for uploading the file....and the other is responsible for saving it to the database.

If the file does not upload...then I'm not calling the save-to-database function.

See below:

Expand|Select|Wrap|Line Numbers
  1. Imports System.IO
  2. Imports System.Data   
  3. Imports System.Data.SqlClient
  4. Partial Class _Default
  5.     Inherits System.Web.UI.Page
  6.     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  7.  
  8.     End Sub
  9.  
  10.     Private Sub Submit1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Submit1.Click
  11.         Dim SaveLocation As String = Server.MapPath("~/TempImages") & "\upload.txt"
  12.         If UploadFile(SaveLocation) Then
  13.             'the file was uploaded: now try saving it to the database
  14.             SaveToDatabase(SaveLocation)
  15.         End If
  16.     End Sub
  17.  
  18.     Private Function UploadFile(ByVal SavePath As String) As Boolean
  19.         Dim fileWasUploaded As Boolean = False 'indicates whether or not the file was uploaded
  20.  
  21.         'Checking if the file upload control contains a file
  22.         If Not File1.PostedFile Is Nothing And File1.PostedFile.ContentLength > 0 Then
  23.             Try
  24.                 'checking if it was .txt file BEFORE UPLOADING IT!
  25.                 'You used to upload it first...but the file could be a virus
  26.                 If File1.FileName.EndsWith(".txt") = False Then
  27.                     'The file is not the expected type...do not upload it
  28.                     'just post the validation message
  29.                     message.Text = "Please submit a text file."
  30.                 Else
  31.                     'The file is a .txt file
  32.                     'checking to see if the file exists already
  33.                     'If it does exist Deleting the existing one so that the new one can be created
  34.                     If IO.File.Exists(SavePath) Then
  35.                         IO.File.Delete(SavePath)
  36.                     End If
  37.  
  38.                     'Now upload the file (save it to your server)
  39.                     File1.PostedFile.SaveAs(SavePath)
  40.  
  41.                     'After saving it check to see if it exists
  42.                     If File.Exists(SavePath) Then
  43.                         'Upload was sucessful
  44.                         message.Text = "Thank you for your submission"
  45.                         fileWasUploaded = True
  46.                     Else
  47.                         'the file was not saved
  48.                         message.Text = "Unable to save the file"
  49.                     End If
  50.                 End If
  51.  
  52.             Catch Exc As Exception
  53.                 'We encountered a problem
  54.                 message.Text = Exc.Message + " " + Exc.StackTrace
  55.             End Try
  56.         Else
  57.             'No file was selected for uploading
  58.             message.Text = "Please select a file to upload"
  59.         End If
  60.         Return fileWasUploaded
  61.     End Function
  62.  
  63.     Private Sub SaveToDatabase(ByVal SavePath As String)
  64.         Try
  65.             ' and bulk import the data:   
  66.             If ConfigurationManager.ConnectionStrings("Dialerresults") IsNot Nothing Then
  67.             Dim connection As String = ConfigurationManager.ConnectionStrings("Dialerresults").ConnectionString
  68.             Dim results As New DataTable
  69.  
  70.             Using con As New SqlConnection(connection)
  71.                 con.Open()
  72.  
  73.                 ' execute the bulk import   
  74.                 Using cmd As SqlCommand = con.CreateCommand
  75.  
  76.                     cmd.CommandText = "bulk insert dialerresults from '" & SavePath & "' " & _
  77.                     "with ( fieldterminator = ',', rowterminator = '\n' )"
  78.  
  79.                     cmd.ExecuteNonQuery()
  80.                 End Using
  81.             End Using
  82.           Else
  83.             message.Text="ConfigurationManager.ConnectionStrings('Dialerresults') is Nothing!"
  84.           End If
  85.         Catch ex As Exception
  86.             message.Text = ex.Message + ex.StackTrace
  87.         End Try
  88.     End Sub
  89. End Class

At this time I'm not sure why you're getting an object not set to a reference
May 6 '10 #41
Frinavale
9,735 Expert Mod 8TB
Change line 11 in my posted code to be the URL to the of the folder where you're uploading the files.
May 6 '10 #42
dougancil
347 100+
Frinny,

I also had to change line 10 to Protected Sub not Private Sub but now when I hit submit I get the following error:

ConfigurationManager.ConnectionStrings('Dialerresu lts') is Nothing!
May 6 '10 #43
Frinavale
9,735 Expert Mod 8TB
Are you still getting the error message on page load?
May 6 '10 #44
dougancil
347 100+
I'm not getting that error anymore no. Now I'm just getting the
ConfigurationManager.ConnectionStrings('Dialerresu lts') is Nothing! error and no data is being posted to the database.
May 6 '10 #45
Frinavale
9,735 Expert Mod 8TB
Is that message displayed without clicking the button?
May 6 '10 #46
Frinavale
9,735 Expert Mod 8TB
Double check that your web.config <conectionStrings> section is correct.

It should be something like:
Expand|Select|Wrap|Line Numbers
  1. <configuration>
  2.     <connectionStrings>
  3.         <add name="Dialerresults" connectionString="data source=src;initial catalog=tbl;user id=userID;password=passwordValue" providerName="System.Data.SqlClient"/>
  4.     </connectionStrings>
  5.  
  6. </configuration>
May 6 '10 #47
dougancil
347 100+
I didnt have the initial catalog in there but here's the connection string now:

<add name="Dialeresults" connectionString="server=10.2.1.40;data source=IVRDialer;initial catalog=dialerresults;uid=xxxx;password=xxxxxx;" providerName="System.Data.SqlClient" />
</connectionStrings>

This error is only happening after the upload button is pressed.
May 6 '10 #48
Frinavale
9,735 Expert Mod 8TB
I don't know why you're getting this error message...it sounds like your application isn't configured properly.

For now try using a hard coded connection string (this is not a good idea to use when you release your code though).

I'm suggesting the following:
Expand|Select|Wrap|Line Numbers
  1. Private Sub SaveToDatabase(ByVal SavePath As String)
  2.         Try
  3.             ' and bulk import the data:   
  4.             'If ConfigurationManager.ConnectionStrings("Dialerresults") IsNot Nothing Then
  5.             'Dim connection As String = ConfigurationManager.ConnectionStrings("Dialerresults").ConnectionString
  6. Dim connection As String = "server=10.2.1.40;data source=IVRDialer;initial catalog=dialerresults;uid=xxxx;password=xxxxxx;"
  7.             Dim results As New DataTable
  8.  
  9.             Using con As New SqlConnection(connection)
  10.                 con.Open()
  11.  
  12.                 ' execute the bulk import   
  13.                 Using cmd As SqlCommand = con.CreateCommand
  14.  
  15.                     cmd.CommandText = "bulk insert dialerresults from '" & SavePath & "' " & _
  16.                     "with ( fieldterminator = ',', rowterminator = '\n' )"
  17.  
  18.                     cmd.ExecuteNonQuery()
  19.                 End Using
  20.             End Using
  21.           'Else
  22.             'message.Text="ConfigurationManager.ConnectionStrings('Dialerresults') is Nothing!"
  23.           'End If
  24.         Catch ex As Exception
  25.             message.Text = ex.Message + ex.StackTrace
  26.         End Try
  27.     End Sub
May 6 '10 #49
dougancil
347 100+
Ok so I changed the connection string so that now it's trying to upload a file and can see it but evidently, the page can't open the file because I get the following message:

Could not bulk insert because file 'C:\Inetpub\wwwroot\Webfile1\Data\upload.txt' could not be opened. Operating system error code 3(The system cannot find the path specified.). at System.Data.SqlClient.SqlConnection.OnError(SqlExc eption exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnErro r(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndW arning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlCommand.RunExecuteNonQuer yTds(String methodName, Boolean async) at System.Data.SqlClient.SqlCommand.InternalExecuteNo nQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at _Default.SaveToDatabase(String SavePath) in C:\Inetpub\wwwroot\Webfile1\Default.aspx.vb:line 78
May 6 '10 #50

Sign in to post your reply or Sign up for a free account.

Similar topics

9
by: R. Rajesh Jeba Anbiah | last post by:
Q: How should I handle file upload? A: File uploading requires HTML form of content type "multipart/form-data". The file content has to be POSTed/submitted via the form and once the file is...
0
by: ¦è»P¦èµ^ | last post by:
Any homepage is for teaching file uploading in JAVA, JSP and TOMCAT, such as JSPSmartUpload? thx very much ~ ªÑ²¼»ù®æ¦³¤É¦³¶^, ¶R½æ­n¯à©Ó¾á­·ÀI ~ ~ Samba, more than a low cost File and...
0
by: praba kar | last post by:
Dear All, I have doubt regarding file uploading. When we upload a file to the remote server we can get file type through file extentions. How we can find out file type if a file doesn't have...
1
by: psb | last post by:
WHO HAS THE BEST COMPONENT FOR FILE UPLOAD? HELP!? has anyone achieved 100% success with HTTP uploading with Mac clients??? I thought the whole <input type="file" .../> was a w3c standard that...
4
by: Mukesh | last post by:
Hi all I am trying to upload and save as a picture to "root/Photos" folder in my web application. I am using this code to perform this task DirectoryInfo strFolder = new...
1
by: ali | last post by:
I am writing a script which uploads file to a specific directory; I am using javascript to handle client side exceptions and php script which actually performs file uploading. Php scripts gets...
7
by: yatin.smile | last post by:
I am a fresher in php and java script. that's wy i join a group for do a discussion on different concepts of php and java scripts. now i m working on file uploading.So i need a discussion on this...
3
ganesanji
by: ganesanji | last post by:
hi all, I have written a php coding for uploading a file to a specific folder or location in server which is a Linux server. I think the coding for file uploaing is correct. But it does not...
0
by: Raj | last post by:
Hello, I am planning to provide the Pause/Resume while uploading files. Our site is using both java applet and activex to do this. The list of selected files will be stored in an encrypted...
5
by: dmj07 | last post by:
Can anybody help me with a simple file uploading and retrieving idea? What I need is a simple system that uploads the files to be stored in a SQL database which are then shown on the front end in...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.