0

Visiting this url: "https://api.randomsite.com/api1/1/auth.asp?username=x&password=x"

Should generate this xml if the username and password are correct

<?xml version="1.0" encoding="ISO-8859-1" ?> 
<auth>
    <authentication>successful</authentication> 
    <token>{3FE7472B-E43C-442A-BE6D-2643239F3204}</token> 
    <expires>20110307</expires> 
</auth>

I am trying to access this in VB.Net with this code:

Dim Login As XDocument = XDocument.Load("https://api.randomsite.com/api1/1/auth.asp?username=" + Username.Text + "&password=" + Password.Text)
    Dim ResultofAuth As XElement = Login...<authentication>
    If ResultofAuth = "successful" Then
        Look Happy
    Else
        Look Sad because password probably incorrect!
    End If

But I am generating an error with this:

 Dim Login As XDocument = XDocument.Load("https://api.randomsite.com/api1/1/auth.asp?username=" + Username.Text + "&password=" + Password.Text)

The error says that XDocument.Load cannot be for external xml files. Is there a workaround to use an xml file from the web?

JBithell
  • 627
  • 2
  • 11
  • 27
  • 1
    Use `WebRequest` to fetch content from web, and then `XDocument.Parse` to parse it as XML. – MarcinJuraszek Mar 27 '14 at 21:05
  • Maybe [this answer](http://stackoverflow.com/a/4003055/2681948) would help you - like Marcin had said - using `WebClient`. – Romasz Mar 27 '14 at 21:08
  • I like to use the Dataset.ReadXML() method and work with it in a datatable. Very easy and works with rest-enabled, password protected sites directly. – Steve Mar 27 '14 at 21:32

1 Answers1

1

Use a web client to download the stream to the document, then parse the stream into the XDocument class

Dim client As New WebClient()
AddHandler client.OpenReadCompleted,
    Sub(s As Object, e As OpenReadCompletedEventArgs)
        If e.Error Is Nothing Then
            Dim doc = XDocument.Load(e.Result)
            ''TODO: Parse document
        End If
    End Sub
client.OpenReadAsync(New Uri("https://api.randomsite.com/api1/1/auth.asp?username=x&password=x", UriKind.Absolute))
dotMorten
  • 1,953
  • 1
  • 14
  • 10
  • How do I get the if statement to work?( Dim ResultofAuth As XElement = Login... If ResultofAuth = "successful" Then Look Happy Else Look Sad because password probably incorrect! End If) – JBithell Mar 28 '14 at 13:12
  • What does e.Error contain? – dotMorten Mar 31 '14 at 14:20
  • Sorry - My poor explanation. How do I dim the contents of the tag of the XML file for use later? – JBithell Apr 03 '14 at 10:40
  • I am now getting this error: Lambda parameter e hides a variable in an enclosing block, a previously defined range variable, or an implicitly declared variable in a query expression – JBithell Apr 04 '14 at 16:25