VB.NET SetAttribute in WebBrowser doens't work - vb.net

I did some research previously, but all the answers do not work.
The "value" attribute exists in the element but does not appear in the webBrowser, nor in the input.
This is my code until then, I need the webBrowser to read an html file, then load your answers or values ​​from your inputs from a database.
PS:
My application is built in real time, there is no webbrowser control on the screen, it is created shortly after reading the html file and only then it is placed inside a panel.
Dim webBrowser As WebBrowser = New WebBrowser
Dim _doc As HtmlDocument
Dim htmlPath As String = "C:\ePrimeCare\Platis\Debug\Protocolos\" +
nomeProtocolo + "_" + idSistema.ToString() + ".html"
webBrowser.ScriptErrorsSuppressed = True
webBrowser.Navigate(htmlPath)
_doc = webBrowser.Document.OpenNew(False)
'webBrowser.DocumentText = IO.File.ReadAllText(htmlPath).ToString()
'webBrowser.Document.OpenNew(False)
'RetornaRespostasAnteriores(idSistema, idFicha, nomeProtocolo, _doc, Convert.ToDateTime(dtVisita))
_doc.Title = nomeProtocolo
_doc.Write(IO.File.ReadAllText(htmlPath).ToString())
Dim carregaRespostas As CarregarRespostaProtocoloHTML = New CarregarRespostaProtocoloHTML
Dim respostas As DataTable = carregaRespostas.BuscarRespostasProtocoloAnterior(idFicha, idSistema, dtVisita)
Dim idopcaoitem As String = 0
Dim idsetitem As String = 0
Dim value As DataRow()
Dim strArr As String()
For Each element As HtmlElement In _doc.GetElementsByTagName("input")
Dim type As String = element.GetAttribute("type")
Select Case type
Case "text"
strArr = element.GetAttribute("id").Split("_") 'For get the two ids
idopcaoitem = strArr(0)
value = respostas.Select(("IDOPCAOITEM = " + idopcaoitem.ToString()))
If value.Length > 0 Then
element.SetAttribute("value", value(0)(2).ToString())'Here i try to set the value, but does not work
End If
Case "radio"
Debug.WriteLine("Input de radio")
Case "checkbox"
Debug.WriteLine("Input de checkbox")
Case "hidden"
Debug.WriteLine("Input de hidden")
Case Else
Debug.WriteLine("Outro input")
End Select
Next
_doc.Write(IO.File.ReadAllText(htmlPath).ToString())
webBrowser.Refresh(WebBrowserRefreshOption.Completely)
webBrowser.Dock = Dock.Fill
pnlMain.Controls.Add(webBrowser)

All your document rewriting and the refresh you do at the end will overwrite any changes you made to it.
'Either of these will revert the document back to its original state.
_doc.Write(IO.File.ReadAllText(htmlPath).ToString())
webBrowser.Refresh(WebBrowserRefreshOption.Completely)
You don't even need to call _doc.Write() as WebBrowser1.Navigate(htmlPath) will work just as fine.
New code:
Dim webBrowser As New WebBrowser 'Shorthand statement.
Dim _doc As HtmlDocument
Dim htmlPath As String = "C:\ePrimeCare\Platis\Debug\Protocolos\" +
nomeProtocolo + "_" + idSistema.ToString() + ".html"
webBrowser.ScriptErrorsSuppressed = True
webBrowser.Navigate(htmlPath)
_doc = webBrowser.Document 'Removed OpenNew().
_doc.Title = nomeProtocolo
Dim carregaRespostas As New CarregarRespostaProtocoloHTML 'Another shorthand statement.
Dim respostas As DataTable = carregaRespostas.BuscarRespostasProtocoloAnterior(idFicha, idSistema, dtVisita)
(...your variables...)
For Each element As HtmlElement In _doc.GetElementsByTagName("input")
(...your code...)
Next
'(Removed _doc.Write() and Refresh() since they will undo all changes)
webBrowser.Dock = Dock.Fill
pnlMain.Controls.Add(webBrowser)

Related

HtmlAgilityPack - SelectNodes

I'm trying to retrieve a <p class> element.
<div class="thread-plate__details">
<h3 class="thread-plate__title">(S) HexHunter BOW</h3>
<p class="thread-plate__summary">created by Aazoth</p> <!-- (THIS ONE) -->
</div>
But with no luck.
The code I am using is below:
' the example url to scrape
Dim url As String = "http://services.runescape.com/m=forum/forums.ws?39,40,goto," & Label6.Text
Dim source As String = GetSource(url)
If source IsNot Nothing Then
' create a new html document and load the pages source
Dim htmlDocument As New HtmlDocument
htmlDocument.LoadHtml(source)
' Create a new collection of all href tags
Dim nodes As HtmlNodeCollection = htmlDocument.DocumentNode.SelectNodes("//p[#class]")
' Using LINQ get all href values that start with http://
' of course there are others such as www.
Dim links =
(
From node
In nodes
Let attribute = node.Attributes("class")
Where attribute.Value.StartsWith("created by ")
Select attribute.Value
)
Me.ListBox1a.Items.AddRange(links.ToArray)
Dim o, j As Long
For o = 0 To ListBox1a.Items.Count - 1
For j = ListBox1a.Items.Count - 1 To (o + 1) Step -1
If ListBox1a.Items(o) = ListBox1a.Items(j) Then
ListBox1a.Items.Remove(ListBox1a.Items((j)))
End If
Next
Next
For i As Integer = 0 To Me.ListBox1a.Items.Count - 1
Me.ListBox1a.Items(i) = Me.ListBox1a.Items(i).ToString.Replace("created by ", "")
Next
For Each s As String In ListBox1a.Items
Dim lvi As New NetSeal.NSListView
lvi.Text = s
NsListView1.Items.Add(lvi.Text)
Next
It runs but I can't get the 'created by XXX' text.
I've tried many ways but got no luck, an hand would be appreciated.
Thanks in advance everyone.
Looks like you are looking wrong string in the attribute.Value. What I see is that attribute.Value.StartsWith("created by ") must be changed to this one attribute.Value.StartsWith("thread-plate__summary").
And to grab inner content of node you have to do this: Select node.InnerText;
' the example url to scrape
Dim url As String = "http://services.runescape.com/m=forum/forums.ws?39,40,goto," & Label6.Text
Dim source As String = GetSource(url)
If source IsNot Nothing Then
' create a new html document and load the pages source
Dim htmlDocument As New HtmlDocument
htmlDocument.LoadHtml(source)
' Create a new collection of all href tags
Dim nodes As HtmlNodeCollection = htmlDocument.DocumentNode.SelectNodes("//p[#class]")
' Using LINQ get all href values that start with http://
' of course there are others such as www.
Dim links =
(
From node
In nodes
Let attribute = node.Attributes("class")
Where attribute.Value.StartsWith("thread-plate__summary")
Select node.InnerText
)
Me.ListBox1a.Items.AddRange(links.ToArray)
Dim o, j As Long
For o = 0 To ListBox1a.Items.Count - 1
For j = ListBox1a.Items.Count - 1 To (o + 1) Step -1
If ListBox1a.Items(o) = ListBox1a.Items(j) Then
ListBox1a.Items.Remove(ListBox1a.Items((j)))
End If
Next
Next
For i As Integer = 0 To Me.ListBox1a.Items.Count - 1
Me.ListBox1a.Items(i) = Me.ListBox1a.Items(i).ToString.Replace("created by ", "")
Next
For Each s As String In ListBox1a.Items
Dim lvi As New NetSeal.NSListView
lvi.Text = s
NsListView1.Items.Add(lvi.Text)
Next
I hope this will work for you.

Search line in text file and return value from a set starting point vb.net

I'm currently using the following to read the contents of all text files in a directory into an array
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
Within the text files are only 6 lines that all follow the same format and will read something like
forecolour=black
I'm trying to then search for the word "forecolour" and retrieve the information after the "=" sign (black) so i can then populate the below code
AllDetail(numfiles).uPath = ' this needs to be the above result
I've only posted parts of the code but if it helps i can post the rest. I just need a little guidance if possible
Thanks
This is the full code
Dim numfiles As Integer
ReDim AllDetail(0 To 0)
numfiles = 0
lb1.Items.Clear()
Dim lynxin As New IO.DirectoryInfo(zMailbox)
lb1.Items.Clear()
For Each txtfi In lynxin.GetFiles("*.txt")
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
ReDim Preserve AllDetail(0 To numfiles)
AllDetail(numfiles).uPath = 'Needs to be populated
AllDetail(numfiles).uName = 'Needs to be populated
AllDetail(numfiles).uCode = 'Needs to be populated
AllDetail(numfiles).uOps = 'Needs to be populated
lb1.Items.Add(IO.Path.GetFileNameWithoutExtension(txtfi.Name))
numfiles = numfiles + 1
Next
End Sub
AllDetail(numfiles).uPath = Would be the actual file path
AllDetail(numfiles).uName = Would be the detail after “unitname=”
AllDetail(numfiles).uCode = Would be the detail after “unitcode=”
AllDetail(numfiles).uOps = Would be the detail after “operation=”
Within the text files that are being read there will be the following lines
Unitname=
Unitcode=
Operation=
Requirements=
Dateplanned=
For the purpose of this array I just need the unitname, unitcode & operation. Going forward I will need the dateplanned as when this is working I want to try and work out how to only display the information if the dateplanned matches the date from a datepicker. Hope that helps and any guidance or tips are gratefully received
If your file is not very big you could simply
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
For each line in allLines
Dim parts = line.Split("="c)
if parts.Length = 2 andalso parts(0) = "unitname" Then
AllDetails(numFiles).uName = parts(1)
Exit For
End If
Next
If you are absolutely sure of the format of your input file, you could also use Linq to remove the explict for each
Dim line = allLines.Where(Function(x) (x.StartsWith("unitname"))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uName = line.Split("="c)(1)
End If
EDIT
Looking at the last details added to your question I think you could rewrite your code in this way, but still a critical piece of info is missing.
What kind of object is supposed to be stored in the array AllDetails?
I suppose you have a class named FileDetail as this
Public class FileDetail
Public Dim uName As String
Public Dim uCode As String
Public Dim uCode As String
End Class
....
numfiles = 0
lb1.Items.Clear()
Dim lynxin As New IO.DirectoryInfo(zMailbox)
' Get the FileInfo array here and dimension the array for the size required
Dim allfiles = lynxin.GetFiles("*.txt")
' The array should contains elements of a class that have the appropriate properties
Dim AllDetails(allfiles.Count) as FileDetail
lb1.Items.Clear()
For Each txtfi In allfiles)
Dim allLines() As String = File.ReadAllLines(txtfi.FullName)
AllDetails(numFiles) = new FileDetail()
AllDetails(numFiles).uPath = txtfi.FullName
Dim line = allLines.Where(Function(x) (x.StartsWith("unitname="))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uName = line.Split("="c)(1)
End If
line = allLines.Where(Function(x) (x.StartsWith("unitcode="))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uName = line.Split("="c)(1)
End If
line = allLines.Where(Function(x) (x.StartsWith("operation="))).SingleOrDefault()
if line IsNot Nothing then
AllDetails(numFiles).uOps = line.Split("="c)(1)
End If
lb1.Items.Add(IO.Path.GetFileNameWithoutExtension(txtfi.Name))
numfiles = numfiles + 1
Next
Keep in mind that this code could be really simplified if you start using a List(Of FileDetails)

Get a specific part of style attribute in VB.NET

If I used .GetAttribute("style") and it returned:
width:200px;height:300px;background-image:url('http://someurl.com/image.png");position:absolute;
How would I go about getting the background-image URL?
[ EDIT ]
I should also mention that the background-image changes every now and again, it doesn't stay the same.
[ EDIT ] I am trying to pull the background image from bing in a webbrowser. I want to set the background as my form background.
[EDIT]
Try
With bingCheck
Dim bgDiv As HtmlElement = .Document.GetElementById("bgDiv")
Dim imgUrl As String = bgDiv.Style("background-image").ToString
Dim request As HttpWebRequest = DirectCast(HttpWebRequest.Create(imgUrl), HttpWebRequest)
Dim response As Net.HttpWebResponse = DirectCast(request.GetResponse, Net.HttpWebResponse)
Dim grabbedImage As Image = Image.FromStream(response.GetResponseStream)
response.Close()
Me.BackgroundImage = grabbedImage
Me.Update()
End With
Catch ex As Exception
End Try
Many controls provide built-in Style collection. So you can do something like:
Dim sUrl As String = xMyControl.Style("background-image")
Dim str = "width:200px;height:300px;background-image:url('http://someurl.com/image.png');position:absolute;"
Dim v = "background-image:url("
Dim i = str.IndexOf(v) + v.Length + 1
Dim j = str.IndexOf(")", i)
Dim url = str.Substring(i, j - i - 1)

updating textbox.text in a tabpage

I've got an app with numerous textboxes that's basically a form to fill out. There are several tabpages in a tab control. In saving the data, I simply loop through the textboxes, get their names and text and put that in a text file with a '|' as a seperator. That works great and I can see all my textboxes and the data in the text file. Now comes the problem. When I read the file back (to load saved data back into the form) it loops through the control name and changes the text to whatever was in the file. It works fine with the textboxes that are on the form, but fails when it gets to the first textbox that is on a tabpage. How can I fix that? And if there's a better way to save the data, I'm all ears.
Here's the code that writes the file:
Private Sub savefile(file As String)
Dim ctl As Control = Me
Dim sw As System.IO.StreamWriter
sw = My.Computer.FileSystem.OpenTextFileWriter(file, False)
Do
ctl = Me.GetNextControl(ctl, True)
If ctl IsNot Nothing Then
If TypeOf ctl Is TextBox Then
sw.WriteLine(ctl.Name.ToString.Substring(3) & "|" & ctl.Text)
End If
End If
Loop Until ctl Is Nothing
sw.Close()
End Sub
Here's the code that reads the file and updates the textboxes:
Private Sub ReadFile(filename)
Dim strfilename As String = filename
Dim num_rows, x, y As Integer
Dim strarray(1, 1) As String
Dim ctrl As Control = Me
'Check if file exist
If File.Exists(strfilename) Then
Dim tmpstream As StreamReader = File.OpenText(strfilename)
Dim strrecords() As String
Dim strfields() As String
'Load content of file to strLines array
strrecords = tmpstream.ReadToEnd().Split(vbCrLf)
' Redimension the array.
num_rows = UBound(strrecords)
ReDim strarray(num_rows, 2)
' Copy the data into the array.
For x = 0 To num_rows - 1
strfields = strrecords(x).Split("|")
For y = 0 To 1
strarray(x, y) = strfields(y)
Next
Next
' Display the data in listbox
For x = 0 To num_rows - 1
Dim tbxname As String = strarray(x, 0)
tbxname = Remove(tbxname) 'routine that removes invisible characters
tbxname = "tbx" & tbxname
MsgBox(tbxname) 'used to verify each file and which one fails
Me.Controls(tbxname).Text = strarray(x, 1)
Next
Else : MsgBox("File doesn't exist!")
End If
End Sub
I hope that's enough information. Thanks in advance for any help!!
I think the line Me.Controls(tbxname).text = strarray(x,1) does not address your TextBox in your tab control, you may need to find out how to address your textbox in the tab page.
Something like
Me.TabControl1.TabPages(0).Controls(tbxname).text = starray(x,1)

Extract all form elements name htmlagilitypack

i have this code to extract all form input element in html document. currently, i cant get select, textarea and other elements except input element.
Dim htmldoc As HtmlDocument = New HtmlDocument()
htmldoc.LoadHtml(txtHtml.Text)
Dim root As HtmlNode = htmldoc.DocumentNode
If root Is Nothing Then
tsslStatus.Text = "Error parsing html"
End If
' parse the page content
For Each InputTag As HtmlNode In root.SelectNodes("//input")
'get title
Dim attName As String = Nothing
Dim attType As String = Nothing
For Each att As HtmlAttribute In InputTag.Attributes
Select Case att.Name.ToLower
Case "name"
attName = att.Value
Case "type"
attType = att.Value
End Select
If attName Is Nothing OrElse attType Is Nothing Then
Continue For
End If
Dim sResult As String = String.Format("Type={0},Name={1}", attType, attName).ToLower
If txtResult.Text.Contains(sResult) = False Then
'Debug.Print(sResult)
txtResult.Text &= sResult & vbCrLf
End If
Next
Next
Can anyone help me on how to get all elements in all forms in the html document?
i found the solution, what i did was use this
Dim Tags As HtmlNodeCollection = docNode.SelectNodes("//input | //select | //textarea")
thanks for looking