Getting text using span id error - vb.net

I want to grab the text from the span id "hkoTemp"
and here is the code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim wb As WebBrowser = New WebBrowser
wb.Navigate(New Uri("http://www.hko.gov.hk/contentc.htm"))
Dim temp = wb.Document.GetElementById("hkoTemp").GetAttribute("innerText")
MsgBox(temp)
End Sub
When i try to run it, it will have a error on
Dim temp = wb.Document.GetElementById("hkoTemp").GetAttribute("innerText")
how can i fix it?

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim wb As WebBrowser = New WebBrowser()
wb.AllowNavigation = True
AddHandler wb.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf wb_DocumentCompleted)
wb.Navigate(New Uri("http://www.hko.gov.hk/contentc.htm"))
End Sub
Private Sub wb_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs)
' wb.Document is not null at this point
Dim wb As WebBrowser = sender
Dim temp = wb.Document.GetElementById("hkoTemp").GetAttribute("innerText")
MsgBox(temp)
End Sub

Related

Directory.GetFiles Method Not Working In VB

I have created software with Visual Builder that cleans up your desktop. I have used the Directory.GetFiles method to move file types into certain directories. When I first coded it worked fine although I then got an error saying System.IO.IOException: 'Cannot create a file when that file already exists. Which I am not sure how to fix as I create the directory for the files with separate buttons as seen in the code.
I am also having issues with the other buttons which may be a result of the other error. When I go to clean the shortcuts which I programmed to move .lnk files into a Shortcuts folder none of them move into that folder unless they have previously been in that folder.
Full Code
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs)
MessageBox.Show("Desktop Cleaned")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim filePaths = IO.Directory.GetFiles("C:\Users\bj\Desktop\", "*.png")
For Each filePath In filePaths
Dim filename = IO.Path.GetFileName(filePath)
Dim newPath = IO.Path.Combine("C:\Users\bj\Desktop\Pictures", filename)
IO.File.Move(filePath, newPath)
Next filePath
Dim filePaths2 = IO.Directory.GetFiles("C:\Users\bj\Desktop\", "*.jpg")
For Each filePath2 In filePaths2
Dim filename2 = IO.Path.GetFileName(filePath2)
Dim newPath2 = IO.Path.Combine("C:\Users\bj\Desktop\Pictures", filename2)
IO.File.Move(filePath2, newPath2)
Next filePath2
MessageBox.Show("Pictures Compiled And Cleaned")
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim filePaths3 = IO.Directory.GetFiles("C:\Users\bj\Desktop\", "*.lnk")
For Each filePath3 In filePaths3
Dim filename3 = IO.Path.GetFileName(filePath3)
Dim newPath3 = IO.Path.Combine("C:\Users\bj\Desktop\Shortcuts", filename3)
IO.File.Move(filePath3, newPath3)
Next filePath3
Dim filePaths6 = IO.Directory.GetFiles("C:\Users\bj\Desktop\", "*.url")
For Each filePath6 In filePaths6
Dim filename6 = IO.Path.GetFileName(filePath6)
Dim newPath6 = IO.Path.Combine("C:\Users\bj\Desktop\Shortcuts", filename6)
IO.File.Move(filePath6, newPath6)
Next filePath6
MessageBox.Show("Shortcuts Compiled And Cleaned")
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim filePaths4 = IO.Directory.GetFiles("C:\Users\bj\Desktop\", "*.mp4")
For Each filePath4 In filePaths4
Dim filename4 = IO.Path.GetFileName(filePath4)
Dim newPath4 = IO.Path.Combine("C:\Users\bj\Desktop\Videos", filename4)
IO.File.Move(filePath4, newPath4)
Next filePath4
Dim filePaths5 = IO.Directory.GetFiles("C:\Users\bj\Desktop\", "*.avi")
For Each filePath5 In filePaths5
Dim filename5 = IO.Path.GetFileName(filePath5)
Dim newPath5 = IO.Path.Combine("C:\Users\bj\Desktop\Videos", filename5)
IO.File.Move(filePath5, newPath5)
Next filePath5
MessageBox.Show("Videos Compiled And Cleaned")
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
My.Computer.FileSystem.CreateDirectory(
"C:\Users\bj\Desktop\Shortcuts")
End Sub
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
My.Computer.FileSystem.CreateDirectory(
"C:\Users\bj\Desktop\Videos")
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
My.Computer.FileSystem.CreateDirectory(
"C:\Users\bj\Desktop\Pictures")
End Sub
End Class
Error Code
IO.File.Move(filePath, newPath) Returns The Error,
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim filePaths = IO.Directory.GetFiles("C:\Users\bj\Desktop\", "*.png")
For Each filePath In filePaths
Dim filename = IO.Path.GetFileName(filePath)
Dim newPath = IO.Path.Combine("C:\Users\bj\Desktop\Pictures", filename)
IO.File.Move(filePath, newPath)
Next filePath
Error Message : System.IO.IOException: 'Cannot create a file when that file already exists.
Take a look at the documentation for File.Move - the example code checks if the file exists first and deletes it
Wa can extend this logic to maybe make for a nicer experience.
If IO.File.Exists(newPath) Then
Dim dr = MessageBox.Show($"File {newPath} exists, do you want to keep both files? The recently moved file will have a number added to its name", "", MessageBoxButtons.YesNoCancel)
Select dr
Case DialogResult.Cancel
Continue 'go to next loop iteration
Case DialogResult.No
IO.File.Delete(newPath)
Case DialogResult.Yes 'keep both
'Make the path eg kitten.1.jpg, kitten.2.jpg until we find a free name
Dim x = 0
Do
x += 1
newPath = IO.Path.ChangeExtension(newPath, i & IO.Path.GetExtension(newPath))
While IO.File.Exists(newPath)
End Select
End If

How to save an image from Picturebox that load from camera?

I create a simple program that getting image from camera and display it in picturebox using a Aforge library. However, when I try to save the image from picture box. It prompt an error like this " 'System.Runtime.InteropServices.ExternalException' in System.Drawing.dll. A generic error occurred in GDI+. "
I did some research but not found any helpful solution.
Below are my following code use to save the image:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
PictureBox1.Image.Save("C:\a.jpeg", ImageFormat.Jpeg)
End Sub
Updated Code :
Imports AForge
Imports AForge.Video
Imports AForge.Video.DirectShow
Imports AForge.Imaging.Filters
Imports AForge.Imaging
Imports System.Drawing.Imaging
Public Class Form1
Dim Filter As FilterInfoCollection
Dim Camera As VideoCaptureDevice
Dim MINR As Integer = 0
Dim MING As Integer = 0
Dim MINB As Integer = 0
Dim MAXR As Integer = 255
Dim MAXG As Integer = 255
Dim MAXB As Integer = 255
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Filter = New FilterInfoCollection(FilterCategory.VideoInputDevice)
If Filter.Count > 0 Then
For Each ITEM In Filter
ComboBox1.Items.Add(ITEM.Name.ToString())
Next
CheckForIllegalCrossThreadCalls = False
Me.Location = New System.Drawing.Point(Me.Location.X, 0)
Else
MsgBox("NO Camera Found")
End If
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Camera = New VideoCaptureDevice(Filter(ComboBox1.SelectedIndex).MonikerString)
AddHandler Camera.NewFrame, New NewFrameEventHandler(AddressOf Video_NewFrame)
Camera.Start()
ComboBox1.Visible = False
End Sub
Private Sub Video_NewFrame(sender As Object, eventArgs As AForge.Video.NewFrameEventArgs)
Dim ORIGINAL As Bitmap = DirectCast(eventArgs.Frame.Clone(), Bitmap)
Dim FILTER As Bitmap = DirectCast(eventArgs.Frame.Clone(), Bitmap)
Dim CFILTER As New ColorFiltering
CFILTER.Red = New IntRange(MINR, MAXR)
CFILTER.Green = New IntRange(MING, MAXG)
CFILTER.Blue = New IntRange(MINB, MAXB)
CFILTER.ApplyInPlace(FILTER)
Dim GRAY As Grayscale = Grayscale.CommonAlgorithms.BT709
Dim IMAGING As Bitmap = GRAY.Apply(FILTER)
Dim BLOBS As New BlobCounter()
BLOBS.MinHeight = 10
BLOBS.MinWidth = 10
BLOBS.ObjectsOrder = ObjectsOrder.Size
BLOBS.ProcessImage(IMAGING)
Dim Rectangle As Rectangle() = BLOBS.GetObjectsRectangles()
If Rectangle.Count > 0 Then
Dim Rectangle2 As Rectangle = Rectangle(0)
Dim STYLE As Graphics = Graphics.FromImage(ORIGINAL)
Dim CLR As New Pen(Color.Lime, 5)
STYLE.DrawRectangle(CLR, Rectangle2)
STYLE.Dispose()
End If
PictureBoxDefault.Image = ORIGINAL '
PictureBoxFilter.Image = FILTER
End Sub
Private Sub TrackBarMINR_Scroll(sender As System.Object, e As System.EventArgs) Handles TrackBarMINR.Scroll
MINR = TrackBarMINR.Value
LabelMINR.Text = "MINR: " & MINR
End Sub
Private Sub TrackBarMING_Scroll(sender As System.Object, e As System.EventArgs) Handles TrackBarMING.Scroll
MING = TrackBarMING.Value
LabelMING.Text = "MING: " & MING
End Sub
Private Sub TrackBarMINB_Scroll(sender As System.Object, e As System.EventArgs) Handles TrackBarMINB.Scroll
MINB = TrackBarMINB.Value
LabelMINB.Text = "MINB: " & MINB
End Sub
Private Sub TrackBarMAXR_Scroll(sender As System.Object, e As System.EventArgs) Handles TrackBarMAXR.Scroll
MAXR = TrackBarMAXR.Value
LabelMAXR.Text = "MAXR: " & MAXR
End Sub
Private Sub TrackBarMAXG_Scroll(sender As System.Object, e As System.EventArgs) Handles TrackBarMAXG.Scroll
MAXG = TrackBarMAXG.Value
LabelMAXG.Text = "MAXG: " & MAXG
End Sub
Private Sub TrackBarMAXB_Scroll(sender As System.Object, e As System.EventArgs) Handles TrackBarMAXB.Scroll
MAXB = TrackBarMAXB.Value
LabelMAXB.Text = "MAXB: " & MAXB
End Sub
Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Try
Camera.SignalToStop()
Catch ex As Exception
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles btnSave.Click
PictureBox1.Image.Save("D:\a.png", ImageFormat.Png)
End Sub
End Class
I had the same issue.
The code below is now working for me.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim img As Bitmap = PictureBox1.Image.Clone
img.Save("Z:\test.bmp", System.Drawing.Imaging.ImageFormat.Bmp)
End Sub
Just change "Z:\test.bmp" to your directory, haven't tried any other image formats but this is the only way I have gotten it to work so far.

opening files added to a combobox

Dim dir = "..//Football/"
Private Sub FTablebutton_Click(sender As Object, e As EventArgs) Handles FTablebutton.Click
For Each file As String In System.IO.Directory.GetFiles(dir)
FfilesComboBox.Items.Add(System.IO.Path.GetFileNameWithoutExtension(file))
Next
End Sub
Private Sub FfilesComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles FfilesComboBox.SelectedIndexChanged
Dim openfile As String = System.IO.Path.Combine(dir, FfilesComboBox.SelectedItem.ToString)
'start the process using the openfile string
Process.Start(openfile)
End Sub
I am able to add all the files to combobox but the problem is i cannot open the file when selected from the combobox
Try this
Private Sub FTablebutton_Click(sender As Object, e As EventArgs) Handles FTablebutton.Click
For Each file As String In System.IO.Directory.GetFiles(dir)
FfilesComboBox.DisplayMember = "key"
FfilesComboBox.ValueMember = "value"
FfilesComboBox.Items.Add(New DictionaryEntry(System.IO.Path.GetFileNameWithoutExtension(file), System.IO.Path.GetFileName(file)))
Next
End Sub
Private Sub FfilesComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles FfilesComboBox.SelectedIndexChanged
Dim openfile As String = System.IO.Path.Combine(dir, FfilesComboBox.SelectedItem.Value.ToString)
'start the process using the openfile string
Process.Start(openfile)
End Sub
If you Then use Visual studio 2008 or newer. you can use Anonymous class to store the full file path with the FileNameWithoutExtension.
Dim dir = "..//Football/"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FfilesComboBox.DisplayMember = "Text"
End Sub
Private Sub FTablebutton_Click(sender As Object, e As EventArgs) Handles FTablebutton.Click
For Each file As String In System.IO.Directory.GetFiles(Dir)
FfilesComboBox.Items.Add(New With {.Text = System.IO.Path.GetFileNameWithoutExtension(file), .Value = file})
Next
End Sub
you can use ComboBox1.SelectedItem.Value to get the value (that is the file full path)
Private Sub FfilesComboBox_SelectedIndexChanged(sender As Object, e As EventArgs) Handles FfilesComboBox.SelectedIndexChanged
'start the process using the openfile string
Process.Start(FfilesComboBox.SelectedItem.Value)
End Sub
This will work even you choose to loop over sub directories.
This code is tested and worked fine

Adding 150,000 records to a listview without freezing UI

I have a listview loop that is adding 150,000 items to my listview. For testing purposes I moved this code to a background worker with delegates, but it still freezes up the UI. I am trying to find a solution so that it can add these items in the background while I do other stuff in the app. What solutions do you guys recommend?
this is what I am using
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListView1.Clear()
ListView1.BeginUpdate()
bw.WorkerReportsProgress = True
bw.RunWorkerAsync()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If bw.IsBusy Then bw.CancelAsync()
End Sub
Private Sub bw_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bw.DoWork
For x = 1 To 125000
Dim lvi As New ListViewItem("Item " & x)
If bw.CancellationPending Then
e.Cancel = True
Exit For
Else
bw.ReportProgress(0, lvi)
End If
Next
End Sub
Private Sub bw_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bw.ProgressChanged
Try
Dim lvi As ListViewItem = DirectCast(e.UserState, ListViewItem)
Me.ListView1.Items.Add(lvi)
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Sub
Private Sub bw_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bw.RunWorkerCompleted
ListView1.EndUpdate()
If Not e.Cancelled Then
Debug.Print("Done")
Else
Debug.Print("Cancelled")
End If
End Sub
End Class
Give this a try, it's a great example for what you would need... I also had a progress bar that shows the progress and such, see example image that is attached. Also I wasn't seeing any delegate that you need to perform such operation, mine has one that will be required. The reason is you are adding items to a control on the UI thread, in order to add items we need to know if an Invoke is required, if so we invoke otherwise we add the item to the control... Also I made the thread sleep, so it can take a break; this also prevents the UI from wanting to lock up here and there, now it's responsive with NO FREEZING.
Option Strict On
Option Explicit On
Public Class Form1
Delegate Sub SetListItem(ByVal lstItem As ListViewItem) 'Your delegate..
'Start the process...
Private Sub btnStartProcess_Click(sender As Object, e As EventArgs) Handles btnStartProcess.Click
lvItems.Clear()
bwList.RunWorkerAsync()
End Sub
Private Sub AddListItem(ByVal lstItem As ListViewItem)
If Me.lvItems.InvokeRequired Then 'Invoke if required...
Dim d As New SetListItem(AddressOf AddListItem) 'Your delegate...
Me.Invoke(d, New Object() {lstItem})
Else 'Otherwise, no invoke required...
Me.lvItems.Items.Add(lstItem)
End If
End Sub
Private Sub bwList_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bwList.DoWork
Dim intCount As Integer = CInt(txtCount.Text)
Dim dblPercent As Integer = 100
Dim intComplete As Integer = 0
Dim li As ListViewItem = Nothing
For i As Integer = 1 To CInt(txtCount.Text)
If Not (bwList.CancellationPending) Then
li = New ListViewItem
li.Text = "Item " & i.ToString
AddListItem(li)
Threading.Thread.Sleep(1) 'Give the thread a very..very short break...
ElseIf (bwList.CancellationPending) Then
e.Cancel = True
Exit For
End If
intComplete = CInt(CSng(i) / CSng(intCount) * 100)
If intComplete < dblPercent Then
bwList.ReportProgress(intComplete)
End If
If li IsNot Nothing Then
li = Nothing
End If
Next
End Sub
Private Sub bwList_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles bwList.ProgressChanged
pbList.Value = e.ProgressPercentage
End Sub
Private Sub bwList_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bwList.RunWorkerCompleted
If pbList.Value < 100 Then pbList.Value = 100
MessageBox.Show(lvItems.Items.Count.ToString & " items were added!")
End Sub
Private Sub btnStopWork_Click(sender As Object, e As EventArgs) Handles btnStopWork.Click
bwList.CancelAsync()
End Sub
Private Sub btnRestart_Click(sender As Object, e As EventArgs) Handles btnRestart.Click
pbList.Value = 0
lvItems.Items.Clear()
txtCount.Text = String.Empty
End Sub
End Class
Screenshot in action...

add subitems to a listview

I'm using a backgroundworker to populate a listview, but i want to add subitems also. Can anyone help me out?
Public Class Form1
Private Sub bgw_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgw.DoWork
Dim li As New List(Of ListViewItem)
For Each fn As String In My.Computer.FileSystem.GetFiles("s:\Videos", FileIO.SearchOption.SearchAllSubDirectories, "*.*")
li.Add(New ListViewItem(My.Computer.FileSystem.GetName(fn)))
'here i want to add a subitem containing the filesize
'My.Computer.FileSystem.GetFileInfo(fn).Length
Next
e.Result = li.ToArray
End Sub
Private Sub bgw_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgw.RunWorkerCompleted
lv.Items.AddRange(DirectCast(e.Result, ListViewItem()))
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
bgw.RunWorkerAsync()
End Sub
End Class
Try this in your For Each loop:
Dim NewItem as New ListViewItem(My.Computer.FileSystem.GetName(fn))
NewItem.SubItems.Add(My.Computer.FileSystem.GetFileInfo(fn).Length)
li.Add(NewItem)
Hopefully that should do the trick
this is working too, but is it correct?
Public Class Form1
Dim item1 As String = ""
Dim item2 As String = ""
Private Sub bgw_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgw.DoWork
Dim progress As Integer = 0
'calculate progress later
progress = 1
For Each fn As String In My.Computer.FileSystem.GetFiles("s:\Videos", FileIO.SearchOption.SearchAllSubDirectories, "*.*")
item1 = My.Computer.FileSystem.GetName(fn)
item2 = My.Computer.FileSystem.GetFileInfo(fn).Length
bgw.ReportProgress(progress)
Next
End Sub
Private Sub bgw_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles bgw.ProgressChanged
Dim li As New ListViewItem
li = lv.Items.Add(item1, 0)
li.SubItems.Add(item2)
End Sub
Private Sub bgw_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgw.RunWorkerCompleted
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
lv.Items.Clear()
bgw.RunWorkerAsync()
End Sub
End Class