Solved

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

Posted on 2006-10-26
7
157 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
  • 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 125 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
A company’s greatest vulnerability is their email. CEO fraud, ransomware and spear phishing attacks are the no1 threat to a company’s security. Cybercrime is responsible for the largest loss of money to companies today with losses projected to r…

948 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now