Solved

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

Posted on 2006-10-26
7
154 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 11

Expert Comment

by:LordWabbit
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
my bad, it's not marked must inherited, sometimes i wish my wife wouldn't correct my posts ;-)
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
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…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

772 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

10 Experts available now in Live!

Get 1:1 Help Now