|
-
Sep 7th, 2011, 10:11 PM
#1
Thread Starter
Junior Member
Help from a VBS to VB (noob)
First off I apologize for not being the expert in VB. I download VB and created a form with a webbrowser component. So, now my question comes down to the code being used.
Here is my .vbs, is there an easy way to place this code but in VB. I'm assuming something in the web browser component code field?
Set objIE = CreateObject("InternetExplorer.Application")
Dim http: set http= CreateObject("MSXML2.XMLHTTP")
http.open "GET", "http://www.thisisatestandwillfail2.co", false
http.send
If http.status = 200 then
' if return code equals something else, launch IE and point to another url
Wscript.Quit ' I would like it to load a local html file instead of quiting.
Else
objIE.Visible = True ' Set browser object visible
objIE.Navigate "http://www.thisisworking.com"
Wscript.Sleep(60000) ' Sleep for 60 seconds
objIE.Quit
End If
Any help is appreciated!
-
Sep 8th, 2011, 11:02 AM
#2
Thread Starter
Junior Member
Re: Help from a VBS to VB (noob)
Instead of doing the above, could I just do a webbrowser.navigate to the URL and track the title bar? If the title bar is not equal to a certain string sleep for a few seconds and quit?
I'm just confused on how to track the title bar?
-
Sep 8th, 2011, 11:26 AM
#3
Hyperactive Member
Re: Help from a VBS to VB (noob)
Assuming you are using VB.NET then here is an example of navigating to a URL and displaying the title:
VB.NET Code:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'This is how you can navigate to a URL within the WebBrowser control
WebBrowser1.Navigate("www.your-url.co.uk")
End Sub
'This event will run when the WebPage has finished navigating.
Private Sub WebBrowser1_Navigated(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserNavigatedEventArgs) Handles WebBrowser1.Navigated
'This would display the Title of the loaded document in a Message box.
MessageBox.Show(WebBrowser1.DocumentTitle)
End Sub
End Class
Hope this helps
-
Sep 9th, 2011, 09:04 AM
#4
Thread Starter
Junior Member
Re: Help from a VBS to VB (noob)
Thanks that worked!
Should I start a new thread or does anyone know the best way for .net repeat command? I'm trying to do this command every five seconds.
webbrowser3.url = new uri("http://www.goodsite.com")
if webbrowser3.DocumentTitle = ("good title bar")
Do something
Basically, I just need to repeat the command until I receive a good response. Once I receive a good response I will act upon it.
Any help is appreciated! Thanks again.
-
Sep 9th, 2011, 03:39 PM
#5
Hyperactive Member
Re: Help from a VBS to VB (noob)
Perhaps it would be best to use the WebClient class while you look for a Website with a "Good Title Bar". The WebClient runs 'behind the scenes' and can retrieve the WebPage Source Code.
Because it can take a while to load a webpage you can retrieve the WebSite Source in a BackGroundWorker to prevent the form from locking up. Here is an example that demonstrates how it could work:
VB.NET Code:
Option Strict On
Imports System.ComponentModel
Imports System.Net
Imports System.IO
Public Class Form1
'Create a BackGroundWorker
Private WithEvents BackGroundWorker1 As New BackgroundWorker
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Create a list of links you want to check
Dim LinksToLoop As New List(Of String)
'Add links to the list
LinksToLoop.Add("http://www.goodsite1.com")
LinksToLoop.Add("http://www.goodsite2.com")
LinksToLoop.Add("http://www.goodsite3.com")
'Create a WebClient
Dim wwwClient As New WebClient
'Loop through your links
For Each Link As String In LinksToLoop
'Pass the link and the webclient into the BackGroundWorker as object arguments
BackGroundWorker1.RunWorkerAsync(New Object() {wwwClient, Link})
'This will stop the form from locking up while the BackGroundWorker is running
Do While BackGroundWorker1.IsBusy
Application.DoEvents()
Loop
Next Link
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackGroundWorker1.DoWork
Try
'Get the arguments (the URL and WebClient control)
Dim Arguments() As Object = CType(e.Argument, Object())
'Cast the URL back to a string from an object
Dim URL As String = DirectCast(Arguments(1), String)
'Check that a URL was provided
If Not String.IsNullOrEmpty(URL) Then
'Cast the WebClient back from an Object
Dim wwwClient As WebClient = DirectCast(Arguments(0), WebClient)
'Navigate the WebClient to the URL and Read the HTML Source from the WebClient
Dim HTMLStream As Stream = wwwClient.OpenRead(URL)
Dim SR As New StreamReader(HTMLStream)
Dim HTML As String = SR.ReadToEnd
'Retrieve the text within the <title></title> tags
Dim TitleStartIndex As Integer = HTML.IndexOf("<title")
TitleStartIndex = HTML.IndexOf(">"c, TitleStartIndex) + ">".Length 'This line will help in cases where an element is found in the <title> tag e.g. <title id="someID"> (It happens)
Dim TitleEndIndex As Integer = HTML.IndexOf("</title>")
Dim PageTitle As String = HTML.Substring(TitleStartIndex, TitleEndIndex - TitleStartIndex)
'Pass the Page Title to the Result property
e.Result = PageTitle
Else
'If an empty URL was entered then set the result to nothing
e.Result = Nothing
End If
Catch ex As Exception
'If there were any errors then set the result to nothing
e.Result = Nothing
End Try
End Sub
'This event will occur once the code in a BackGroundWorker has completed
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackGroundWorker1.RunWorkerCompleted
'If the result is nothing then there was an error
If Not (e.Result) Is Nothing Then
'The Page title can be found in e.Result e.g.
MessageBox.Show(e.Result.ToString)
'You can perform your extra logic here e.g.
If e.Result.ToString = "Good Title Bar" Then
'Do something
End If
End If
End Sub
End Class
Hope this helps
-
Sep 10th, 2011, 07:49 PM
#6
Thread Starter
Junior Member
Re: Help from a VBS to VB (noob)
Thanks again, I have it working. I was unaware of the background worker.
-
Sep 12th, 2011, 02:00 PM
#7
Thread Starter
Junior Member
Re: Help from a VBS to VB (noob)
I decided to loop the process so it will continue to look for the site until it comes back ok. It's using quite a bit of CPU. Is that normal? Any possible way to force it to only use a certain % of CPU?
Do Until BackGroundWorker1.CancellationPending
'Making the links into string.
Dim LinksToLoop As New List(Of String)
'Add links to be checked.
LinksToLoop.Add("http://www.goodsite.com")
'Create a WebClient. This is opening up goodsite website.
Dim wwwClient As New WebClient
'Loop through your links. You can add more than one link if we so desire.
For Each Link As String In LinksToLoop
'Pass the link and the webclient into the BackGroundWorker as object arguments
BackGroundWorker1.RunWorkerAsync(New Object() {wwwClient, Link})
'This will stop the form from locking up while the BackGroundWorker is running
Do While BackGroundWorker1.IsBusy
Application.DoEvents()
Loop
'Will loop into the next link if we add one.
Next Link
-
Sep 12th, 2011, 02:05 PM
#8
Re: Help from a VBS to VB (noob)
What you have is a busy wait, which is horribly inefficient, as you have found.
The thing to do is to add a timer component onto the form. Set the timer interval to whatever you feel is a reasonable waiting period (you suggested 5s, which means you would set the interval to 5000), and in the timer Tick event, that is where you perform your actions. The timer Tick event will be raised every time the interval elapses. Therefore, if the interval is 5000 (which is in milliseconds, so that would be 5 seconds), the Tick event will be raised every 5 seconds until you disable the timer. The only concern would be that you want the interval to be longer than the work you are doing. Therefore, if you think that the operation might take longer than 5s, use a longer interval.
My usual boring signature: Nothing
 
-
Sep 13th, 2011, 04:32 AM
#9
Hyperactive Member
Re: Help from a VBS to VB (noob)
I just tested the code in a loop and get the same effect. If you also make use of the System.Threading.Thread.Sleep method where I originally used Application.DoEvents to prevent the UI locking up, then the CPU usage will improve.
Here is how the updated code would look:
VB.NET Code:
'This will stop the form from locking up while the BackGroundWorker is running
Do While BackGroundWorker1.IsBusy
Application.DoEvents()
System.Threading.Thread.Sleep(250)
Loop
I will let you know if I come accross a better way to wait for a thread to finish. Or as Shaggy Hiker pointed out you can use a Timer function.
-
Sep 13th, 2011, 05:45 AM
#10
Hyperactive Member
Re: Help from a VBS to VB (noob)
Here is a better approach than my first example. It uses a System.Threading.Thread instead of the BackGroundWorker. You can use the AutoResetEvent class to wait for threads to finish before continuing with code execution.
VB.NET Code:
Option Strict On
Imports System.Net
Imports System.IO
Imports System.Threading
Public Class Form1
'Create a Shared string that can be accessed from another thread
Private Shared WebsiteTitle As String = Nothing
'The AutoResetEvent Class contains methods to wait for an event to finish
Dim WaitEvent As AutoResetEvent = New AutoResetEvent(False)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Create a list of links you want to check
Dim LinksToLoop As New List(Of String)
'Add links to the list
LinksToLoop.Add("http://www.Link1.co.uk")
LinksToLoop.Add("http://www.Link2.com")
LinksToLoop.Add("http://www.Link3.com")
LinksToLoop.Add("http://www.Link4.co.uk")
'Create a WebClient
Dim wwwClient As New WebClient
'Loop through your links
For Each Link As String In LinksToLoop
'Create a new thread to run the Retrieve_WebSource sub in the background
Dim WebBrowserThread As New Thread(AddressOf Retrieve_WebTitle)
'Start the thread and pass in the WebClient and Link as object arguments
WebBrowserThread.Start(New Object() {wwwClient, Link})
'Wait for the Thread to finish
WaitEvent.WaitOne()
'Check if a WebSite Title was found
If Not (WebsiteTitle) = Nothing Then
'You can perform your extra logic here e.g.
If WebsiteTitle = "Good Title Bar" Then
MessageBox.Show(WebsiteTitle)
End If
End If
Next Link
End Sub
Private Sub Retrieve_WebTitle(ByVal Arguments As Object)
Try
'Get the arguments (the URL and WebClient control)
Dim Args() As Object = CType(Arguments, Object())
'Cast the URL back to a string from an object
Dim URL As String = DirectCast(Args(1), String)
'Check that a URL was provided
If Not String.IsNullOrEmpty(URL) Then
'Cast the WebClient back from an Object
Dim wwwClient As WebClient = DirectCast(Args(0), WebClient)
'Navigate the WebClient to the URL and Read the HTML Source from the WebClient
Dim HTMLStream As Stream = wwwClient.OpenRead(URL)
Dim SR As New StreamReader(HTMLStream)
Dim HTML As String = SR.ReadToEnd
'Retrieve the text within the <title></title> tags
Dim TitleStartIndex As Integer = HTML.IndexOf("<title")
TitleStartIndex = HTML.IndexOf(">"c, TitleStartIndex) + ">".Length 'This line will help in cases where an element is found in the <title> tag e.g. <title id="someID"> (It happens)
Dim TitleEndIndex As Integer = HTML.IndexOf("</title>")
Dim PageTitle As String = HTML.Substring(TitleStartIndex, TitleEndIndex - TitleStartIndex)
'Update the Shared WebSiteTitle variable with the result
WebsiteTitle = PageTitle
Else
'If an empty URL was entered then the WebSiteTitle variable should be set to nothing
WebsiteTitle = Nothing
End If
'Changes the state of the event to signaled (meaning waiting threads can proceed)
WaitEvent.Set()
Catch ex As Exception
'If there were any errors then then the WebSiteTitle variable should be set to nothing
WebsiteTitle = Nothing
WaitEvent.Set()
End Try
End Sub
End Class
Last edited by JayJayson; Sep 13th, 2011 at 05:52 AM.
-
Sep 13th, 2011, 01:42 PM
#11
Thread Starter
Junior Member
Re: Help from a VBS to VB (noob)
Yep, I went ahead with the timer.
I apologize for this stupid question but a little confused. Why would the case of the <title> matter when scrubbing the data? If the html document is labeled TITLE or Title it fails. I thought converting it to string like
Dim PageTitle As String = HTML.Substring(TitleStartIndex, TitleEndIndex - TitleStartIndex)
would help but I guess not.
Last edited by titanmifi; Sep 13th, 2011 at 01:52 PM.
-
Sep 14th, 2011, 04:26 AM
#12
Hyperactive Member
Re: Help from a VBS to VB (noob)
Try this instead:
Add the following statement to the top of your form (outside the Class tags):
VB.NET Code:
Imports System.Globalization
And replace the previous code with this:
VB.NET Code:
'Retrieve the text within the <title></title> tags
Dim GoCompare As CompareInfo = CultureInfo.InvariantCulture.CompareInfo
Dim TitleStartIndex As Integer = GoCompare.IndexOf(HTML, "<title", CompareOptions.IgnoreCase)
TitleStartIndex = HTML.IndexOf(">"c, TitleStartIndex) + ">".Length 'This line will help in cases where an element is found in the <title> tag e.g. <title id="someID"> (It happens)
Dim TitleEndIndex As Integer = GoCompare.IndexOf(HTML, "</title>", CompareOptions.IgnoreCase)
Dim PageTitle As String = HTML.Substring(TitleStartIndex, TitleEndIndex - TitleStartIndex)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|