Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Upload XML file to server, read, display selected contents?

Posted on 2006-10-26
7
Medium Priority
?
164 Views
Last Modified: 2010-04-23
Hi,

I'm attempting to create a web site using VS 2005 and VB.NET that allows the user to select an XML file on their local machine (using FileUpload control), upload it where my default.aspx.vb page loads it into a newly created variable which can then interrogate the contents and process as it sees fit.

I'm trying to do this in the most simplest way possible and without having the file actually saved on the server anywhere.

Below is my code so far, but when i host the site and access from another machine, the upload part doesn't seem to work. I can only access files on the machine hosting the site.

[code]
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If IsPostBack Then
            Dim fileOK As Boolean = False
            If FileUpload1.HasFile Then
                Dim fileExtension As String
                fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower()
                Dim allowedExtensions As String() = {".xml"}
                For i As Integer = 0 To allowedExtensions.Length - 1
                    If fileExtension = allowedExtensions(i) Then
                        fileOK = True
                    End If
                Next
                If fileOK Then
                    Try
                        Dim FileLen As Integer
                        Dim MyStream As System.IO.Stream
                        FileLen = FileUpload1.PostedFile.ContentLength
                        Dim Input(FileLen) As Byte
                        MyStream = FileUpload1.FileContent

                        Dim newXML As DataSet = New DataSet()
                        newXML.ReadXml(MyStream, XmlReadMode.Auto)
                        For Loop1 = 0 To newXML.Tables.Count - 1
                            MyString += newXML.Tables(Loop1).TableName & ", "
                        Next
                        Label2.Text = MyString
                        Label1.Text = "File uploaded!"
                    Catch ex As Exception
                        Label1.Text = "File could not be uploaded. Error:" & ex.Message
                    End Try
                Else
                    Label1.Text = "Cannot accept files of this type."
                End If
            Else
                Label1.Text = "No file"
            End If
        End If
    End Sub
[/code]


Could someone please assist in this problem of mine and suggest where I'm going wrong and how to overcome my problems?

Thank you very much!
0
Comment
Question by:craigewens
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 2
7 Comments
 
LVL 2

Author Comment

by:craigewens
ID: 17813561
I have managed to achieve the desired result by storing the file on the server, accessing it then deleting it as you can see from the code below... it's not really what i was after though :(

Any suggestions?

[code]
        If IsPostBack Then
            Dim path As String = Server.MapPath("~/Uploaded/")
            Dim fileOK As Boolean = False
            If FileUpload1.HasFile Then
                Dim fileExtension As String
                fileExtension = System.IO.Path. _
                    GetExtension(FileUpload1.FileName).ToLower()
                Dim allowedExtensions As String() = {".xml"}
                For i As Integer = 0 To allowedExtensions.Length - 1
                    If fileExtension = allowedExtensions(i) Then
                        fileOK = True
                    End If
                Next
                If fileOK Then
                    Try
                        Randomize()
                        Dim Rnd1 As String = Rnd().ToString
                        Randomize()
                        Dim Rnd2 As String = Rnd().ToString
                        Dim FullFile As String = path & Rnd1 & Rnd2 & FileUpload1.FileName
                        FileUpload1.PostedFile.SaveAs(FullFile)
                        Label1.Text = "File uploaded!"

                        Dim newXML As DataSet = New DataSet()
                        newXML.ReadXml(FullFile, XmlReadMode.Auto)
                        For Loop1 = 0 To newXML.Tables.Count - 1
                            MyString += newXML.Tables(Loop1).TableName & ", "
                        Next
                        Label2.Text = MyString
                        File.Delete(FullFile)
                    Catch ex As Exception
                        Label1.Text = ex.Message
                    End Try
                Else
                    Label1.Text = "Cannot accept files of this type."
                End If
            Else
                Label1.Text = "No file selected"
            End If
        End If
[/code]
0
 
LVL 11

Accepted Solution

by:
LordWabbit earned 500 total points
ID: 17814516
obviously leaving your other validation in place you can do the following to stream the upload directly into an xmldocument

    Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
        Dim myStream As System.IO.MemoryStream = New System.IO.MemoryStream(uploadFile.FileBytes)
        Dim myDocument As System.Xml.XmlDocument = New System.Xml.XmlDocument()
        myDocument.Load(myStream)
        ' do stuff

    End Sub

oh yeah i would suggest not putting the code into the load event, if for whatever reason you need to add other functionality to the website which causes postbacks this would become an issue (which might be why you check for HasFile???) I suggest placing a submit button on the page instead and hook into the click event for that (with required field validators etc. as required).
0
 
LVL 11

Expert Comment

by:LordWabbit
ID: 17814547
oops sorry didn't check all the code, though you were loading the xml into an xml document, but the theory is basically the same

        Dim myDataSet As System.Data.DataSet = New System.Data.DataSet()
        myDataSet.ReadXml(myStream)
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 11

Expert Comment

by:LordWabbit
ID: 17814600
also have to mention something (cos it took me 6 friggin hours) is that it's impossible to change the look and feel of an upload file control, you have to make it transparent and place quasi controls over the top using absolute positioning, this will make an error summary control impossible to use since it will change the absolute position of the webpage (if it's above the file upload dialogue) and break things, rather use a bullet list and do validation on the submit callback adding errors (if found) to the bullet list, then when the page gets rerendered on return everything will be in the right position.  i have written a user control to falicitate this, if you need it let me know and I will post it.
0
 
LVL 2

Author Comment

by:craigewens
ID: 17814773
Thank you for your comments LordWabbit.
I can see that the missing link for me was the System.IO.MemoryStream instead of System.IO.Stream?
I'm not in a position to test this now (at home) but will check first thing tomorrow morning that it works (fingers crossed).

I'm happy with the looks of the FileUpload control (for now) so only post your user controls if you're happy to do so.

One sub question; your initial code loaded the XML file into an XML Document, would you rate this for ease/speed over the method i had originally coded? Just curious that's all.

Thanks again and i'll post my findings first thing tomorrow.
0
 
LVL 11

Expert Comment

by:LordWabbit
ID: 17815697
ummm, not too sure about speed, would have to write some tests to check, but as far as ease of use is concerned loading the xml into a dataset if you are simply trying to iterate through the list of tables would be much simpler than loading into an xml dom and using xpath etc. to retrieve the same info, so personally in this situation i would go for the dataset myself.  ultimately it would depend on what ELSE you plan on doing with the xml.  but i say if it came from a dataset, well, put i back in.

btw System.IO.Stream is marked must inherit and cannot be instantiated, it's basically a base stream class for all the other stream classes, you will probably only use it when passing unknown streams between tiers (although I cant see why overloading would not suffice since you would probably treat each stream differently)
0
 
LVL 11

Expert Comment

by:LordWabbit
ID: 17815715
my bad, it's not marked must inherited, sometimes i wish my wife wouldn't correct my posts ;-)
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: jpaulino
XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String (http://msdn.microsoft.com/en-us/library/system.string.aspx) Literal, only instead of starting and ending with w…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…

618 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question