Can somebody give me an example of getting the content of a page from a URL in vb.net for windows 8? - vb.net

I am very new to vb/.net and I'm trying to do something that I can do easily in classic vb. I want to get the source html for a webpage from the URL.
I'm using vb.net in Visual Studio Express for Windows 8.
I've read loads of stuff that talk about HttpWebRequest, but I can't get it to work properly.
I did at one point have it returning the html header, but I want to content of the page. Now, I can't even get it back to giving me the header. Ultimately, I want to process the html returned which I'll do (to begin with) the old-fashioned way and process the returned html as a string, but for now I'd like to just get the page.
The code I've got is:
Dim URL As String = "http://www.crayola.com/"
Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(New Uri(URL))
txtHTML.Text = request.GetRequestStreamAsync().ToString()
Can anyone help me with an example to get me going please?

You're trying to use an Async method in a synchronous way, which won't make any sense. If you're using .NET 4.5, you can try marking the calling method with Async and then using the Await keyword when calling GetRequestStreamAsync.
Public Sub MyDownloaderMethod()
Dim URL As String = "http://www.crayola.com/"
Dim request As System.Net.HttpWebRequest
= System.Net.HttpWebRequest.Create(New Uri(URL))
' Use the Await keyword wait for the async task to complete.
Dim response = request.GetResponseAsync()
txtHTML.Text = response.GetResponseStream().ToString()
End Function
See the following MSDN article for more information on async programming with the Await keyword: http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx
Edit
You are receiving your error because you're trying to get the Request stream (what you send the server), and what you really want is the Response stream (what the server sends back to you). I've updated my code to get the WebResponse from your WebRequest and then retrieve the stream from that.

Public Shared Function GetWebPageString(ByVal address As Uri) As String
Using client As New Net.WebClient()
Return client.DownloadString(address)
End Using
End Function
There is also DownloadStringAsync if you don't want to block

request.GetRequestStreamAsync() is probably not a method. I think you're cribbing code from a site where someone wrote their own add-on methods to HttpWebRequest. Try request.GetResponse() to return a response object, then in the response object you can inspect the stream and convert it to text if you need to.

This worked for me in VB.Net 4.5
Public Async Sub GetHTML()
Dim PageHTML as string
Dim client As New HttpClient
Dim getStringTask As Task(Of String) = client.GetStringAsync(PageURL)
PageHTML = Await getStringTask
MsgBox(PageHTML)
End Sub

Related

How to get the loading time of a web page in Windows Service Application using HttpWebRequest

I'm looking for code that will help me get the loading time of a web page without Using WebBrowser() in a Windows Service Application.
I run through different methods, but I don't quite get it.
Please help me solve this problem.
This function should do the trick:
Public Function WebpageResponseTime(ByVal URL As String) As TimeSpan
Dim sw As New System.Diagnostics.Stopwatch
sw.Start()
Dim wRequest As WebRequest = HttpWebRequest.Create(URL)
Using httpResponse As HttpWebResponse = DirectCast(wRequest.GetResponse(), HttpWebResponse)
If httpResponse.StatusCode = HttpStatusCode.OK Then
sw.Stop()
Return sw.Elapsed
End If
End Using
End Function
This will only take the downloading of the source code into account. If you want to calculate how long time it takes to download the source code AND render the page you'd have to use the WebBrowser class.
How it works:
The function declares and starts a Stopwatch which will be used for calculating how long the operation took, then it creates a web request to the specified URL. It downloads the entire page's source code (via the HttpWebResponse) and after that checks the response's StatusCode.
StatusCode.OK (which is HTTP status code 200) means that the request succeeded and that the requested information (the web page's source code) is in the response, but as we're not gonna use the source code for anything we let the response get disposed later by the Using/End Using block.
And lastly the function stops the Stopwatch and returns the elapsed time (how long it took to download the web page's source) to you.
Example use:
Dim PageLoadTime As TimeSpan = WebpageResponseTime("http://www.microsoft.com/")
MessageBox.Show("Response took: " & PageLoadTime.ToString())

twilio nuget package not sending SMS message in vb.net

Does the twilio asp.net helper library package NOT work in vb.net? I can get it to work in c# web app but not vb.net web app.
In a vb.net web application project the following code doesnt send an sms message and when stepping through with the debugger, errs on the send message line and brings up a file dialog asking for access to core.cs. The twilio library's were installed via nuget.
Public Shared Sub SendAuthCodeViaSms(ByVal number As String)
Dim twilioAccountInfo As Dictionary(Of String, String) = XmlParse.GetAccountInfoFromXmlFile("twilio")
Dim accountSid As String = twilioAccountInfo("username")
Dim authToken As String = twilioAccountInfo("password")
If (Not String.IsNullOrEmpty(accountSid) AndAlso Not String.IsNullOrEmpty(authToken)) Then
Dim client = New TwilioRestClient(accountSid, authToken)
client.SendMessage(TwilioSendNumber, ToNumber, "Testmessage from My Twilio number")
Else
'log error and alert developer
End If
End Sub
But in a C# web API project the same code sends the message as expected.
protected void Page_Load(object sender, EventArgs e)
{
const string AccountSid = "mysid";
const string AuthToken = "mytoken";
var twilio = new TwilioRestClient(AccountSid, AuthToken);
var message = twilio.SendMessage(TwilioSendNumber,ToNumber,"text message from twilio");
}
and all the sid's and tokens and phone number formats are correct, otherwise the c# one wouldnt send and I wouldnt get to the client.SendMessage part of vb.net version (client.SendSMSMessage produces the same result)
Twilio evangelist here.
I tried our your code by creating a simple VB console app and it worked for me.
The only thing I can think of is that either you are not getting your Twilio credentials correctly when parsing the XML, or the phone number you are passing into the function is not formatted correctly.
I'd suggest putting the result of call to SendMessage() into a variable and checking to see if RestException property is null:
Dim result = client.SendMessage(TwilioSendNumber, ToNumber, "Testmessage from My Twilio number")
If (Not IsNothing(result.RestException)) Then
' Something bad happened
Endif
If Twilio returns a status code greater than 400, then that will show up as an exception in the RestException property and will give you a clue as to whats going on.
If that does not work, you can always break out a tool like Fiddler to watch and see if the library is making the property HTTP request and Twilio is returning the proper result.
Hope that helps.

Web API2 read request body

I have a web API2 item that I need to read the 'body' of the incoming request. The client is sending information (via 'PUT') in the body opposed to parameters in the URL. I have been searching for a solution but keep hitting a wall. Can anyone advise how I can get this body text?
Thanks
<HttpOptions>
<Route("v1/cth/test"), AcceptVerbs("PUT", "POST", "OPTIONS")>
Public Function CTHInterface(ByVal passedjson As Object) As String
Return "Hello"
End Function
FYI, I finally managed to get to the body. Hope this helps someone else.
<HttpOptions>
<Route("v1/cth/dev"), AcceptVerbs("PUT", "POST", "OPTIONS")>
Public Function CTHInterfaceDev() As String
Dim CTHStream As New StreamReader(HttpContext.Current.Request.InputStream)
Dim CTHBody As String = CTHStream.ReadToEnd
Return "Hello"
End Function

.Net 4.5 Await Breakpoints

I couldn't find a full example for PostAsync so I had to piece one together. Therefore, I am not sure if what I am viewing is a limitation with the debugger or I simply did it wrong.
This is what I am trying to do:
I have to go through a list and make a web service call for each item on the list. My thought is that I could use the new 4.5 async stuff to keep it flowing without blocking during each call to the web service.
I've done a tone of research and watched Jon Skeet's video on TekPub, but I'm still not sure if I am doing this correctly. That is, when I set break points my async method never returns control to the caller. It basically seems to go along exactly as my synchronous version.
Question:
Is it normal for the debugger to appear synchronous or does that indicate my code is not implemented correctly?
Here is my Post method:
Public Async Function PostSecureXMLAsync(ByVal username As String, ByVal password As String, ByVal XMLtoSend As String) As Task(Of String)
Dim content = New StringContent(XMLtoSend, Encoding.UTF8, "text/xml")
Dim credentials = New NetworkCredential(username, password)
Dim handler = New HttpClientHandler() With {.Credentials = credentials}
Using client = New HttpClient(handler)
Using response = client.PostAsync(APIurl, content).Result
Return Await response.Content.ReadAsStringAsync()
End Using
End Using
End Function
This is how it is being used:
For Each ListItem In ListObj
...
Result = XMLExchangeObj.PostSecureXMLAsync(Username, Password, Payload).Result
...
Next
I was expecting control to return to the For Each loop while it was waiting for replies from the Web Service, but based on my break points it seems to be running synchronously.
When you're working with Async, you don't want to call Wait or Result. Instead, you should use Await. I see one Result in PostSecureXMLAsync:
Using client = New HttpClient(handler)
Using response = Await client.PostAsync(APIurl, content) ' Changed to Await
Return Await response.Content.ReadAsStringAsync()
End Using
End Using
And there's another one when you call your Async method:
Result = Await XMLExchangeObj.PostSecureXMLAsync(Username, Password, Payload)
This does mean that your calling method must also be Async, which means any methods that call that method should use Await, and must also be Async, etc. This "growth" through your code is perfectly normal. Just allow Async to grow until you reach a natural stopping point (usually an event handler, which you can make Async Sub).

Windows Phone VB Web Request

does anybody has an idea how I can perform an asynchronus Post Request in VB.Net for Windows Phone 8?
I tried a lot but nothing worked... also this http://msdn.microsoft.com/de-de/library/system.net.httpwebrequest.begingetrequeststream.aspx didn't work.
Thanks a lot.
I had to figure this out for myself a while ago. Let me see what I can do to help.
Posting a web request is actually simpler than that link shows. Here's what I do.
First, I create a MultipartFormDataContent:
Dim form as New MultipartFormDataContent()
Next, I add each string I want to send like this:
form.Add(New StringContent("String to sent"), "name of the string you are sending")
Next, create a HttpClient:
Dim httpClient as HttpClient = new HttpClient()
Next, we'll create a HttpResponseMessage and post your information to the url of your choice:
Dim response as HttpResponseMessage = Await httpClient.PostAsync("www.yoururl.com/wherever", form)
Then, I usually need the response as a string, so I read the response to a string:
Dim responseString as String = Await response.Content.ReadAsStringAsync()
This will give you the response you wanted, if that's what you wanted.
Here's an example of a method I use:
Public Async Function GetItems() As Task
Dim getUrl As String = "https://myapiurl.com/v3/get"
Dim responseText As String = String.Empty
Dim detailType As String = "complete"
Try
Dim httpClient As HttpClient = New HttpClient()
Dim form As New MultipartFormDataContent()
form.Add(New StringContent(roamingSettings.Values("ConsumerKey").ToString()), "consumer_key")
form.Add(New StringContent(roamingSettings.Values("access_token").ToString()), "access_token")
form.Add(New StringContent(detailType.ToString()), "detailType")
Dim response As HttpResponseMessage = Await httpClient.PostAsync(getUrl, form)
responseText = Await response.Content.ReadAsStringAsync()
Catch ex As Exception
End Try
End Function
If you aren't using the Http client libraries, you need to install them like this:
What you need to do to use the HttpClient, is to navigate in Visual Studio, go to Tools->Library Package Manager->Manage Nuget Packages for this solution. When there, search the online section for HttpClient and make sure you have "Include Prerelease" selected in the listbox above the results. (Default is set to "Stable Only")
Then install the package with the ID of Microsoft.Net.Http
Then you'll need to add an Import statement at the beginning of the document you are using it in.
Let me know if this is what you were looking for.
Thanks,
SonofNun