Using Visual Basic to Select a Google Search Result in Internet Explorer - vb.net

I have VB code that goes to Google, fills in the search bar, and hits the search button. Is there a way to have my program select a particular result after my search? ie. I search for "cheese", I would like for my program to select the 2nd to last result (in this case, it is wwww.chuckecheese.com)

I ended up using Sendkeys to emulate the tab and down arrow keys on the keyboard. You can then navigate to your desired search results using these 2 keys

Or you can bypass using an API and avoid ads or cost using speech recognition to improve your Dictation searches. Programming isn't programming if you aren't thinking outside the box and innovating your own solutions.
Coding comes with creativity and you won't know what that is if you don't try. This site is excellent for this very purpose and many have contributed to innovation in coding.
You will have to add a text file to your project and call it whatever you want, then change the path below in the code to your own path. The text file stays blank. The program will write your spoken search to file and then execute the search, constantly over-writing itself.
For some odd reason, this method greatly improves the fusion of speech recognition and dictation. You can speak an entire phrase and it will conduct the search. A good mic is a must and speaking clearly without background disturbances.
Imports System.Speech.Recognition
'Declarations:
Private ReadOnly Drone As New SpeechRecognitionEngine()
Private ReadOnly Qa As New DictationGrammar()
Private Sub Form1_Load(sender As Object,
e As EventArgs) Handles MyBase.Load
'Dictation Mode | Google Engine
Drone.LoadGrammarAsync(Qa)
Drone.RequestRecognizerUpdate()
Drone.SetInputToDefaultAudioDevice()
Drone.InitialSilenceTimeout = TimeSpan.FromSeconds(2.5)
Drone.BabbleTimeout = TimeSpan.FromSeconds(1.5)
Drone.EndSilenceTimeout = TimeSpan.FromSeconds(1.2)
Drone.EndSilenceTimeoutAmbiguous = TimeSpan.FromSeconds(1.5)
AddHandler Drone.SpeechRecognized, AddressOf Drone_SpeechRecognized
Drone.RecognizeAsync(RecognizeMode.Multiple)
End Sub
Private Sub Drone_SpeechRecognized(sender As Object, e As SpeechRecognizedEventArgs)
Dim google As String = e.Result.Text.ToString
Select Case (google)
Case google
If google <> "+" Then
'This section will take spoken word, write to file then execute search.
Dim sb As New StringBuilder
'Be sure to change the text file path below to your path if you are new to this program.
sb.AppendLine(google)
'Add your own path below here. you can also change google to youtube and conduct youtube searches
File.WriteAllText("C:\Users\justin.ross\source\repos\ScarlettCenturium\Scarlett Centurium\Scarlett Centurium\File.txt", sb.ToString())
google = "https://www.google.com/search?q=" & Uri.EscapeUriString(google)
Dim proc As New Process()
Dim startInfo As New ProcessStartInfo(google)
proc.StartInfo = startInfo
proc.Start()
'This sendkey will close out previous tab on new search
SendKeys.Send($"^{{w}}")
Return
End If
End Select
End Sub

well you can use google api for that
goto http://code.google.com/p/google-api-for-dotnet/
download GoogleSearchAPI_0.4_alpha.zip
extract it and add reference to the dll file in your project ( in folder .net 2)
and you can use it like this
first import the library
Imports Google.API.Search
then in a sub or function put your code as
Dim rf As String = "http://www.google.com"
Dim v As New Google.API.Search.GwebSearchClient(rf)
Dim result = v.Search(TextBox1.Text, 40)
' number (40) is the amount of fetched results ( change it if you want )
For Each item In result
If item.Url.Contains("chuckecheese") Then
' your code goes here
End If
Next

Related

read event log detail in vb.net

I'm writing a application at the moment, part of it will be scraping some information from the windows event log, it mostly works....
Dim strValue As String
Dim objLogs() As EventLog
Dim Logname As String = "Application"
Dim objEntry As EventLogEntry
Dim objLogEntry As EventLogEntry
Dim objLog As EventLog
objLogs = EventLog.GetEventLogs()
For Each objLog In objLogs
If objLog.LogDisplayName = Logname Then
For Each objLogEntry In objLog.Entries
WriteLine("EventID")
WriteLine("Machinename")
WriteLine("message")
Next
Exit For
End If
Next
This will happily write out the EventID, machine name and event message.
details tab in event viewer
What I can't figure out is how to output the "details" tab in event viewer ideal into strings or similar.
MSDN isn't being helpful, could anyone point me in the right direction please?
Thanks in advance,
Looks like the details in the EventLogEntry is represented by the Data property that is stored as a byte array. You would have you would have to then converted to something readable. But the format of the data seems to vary on the Windows OS version.
Here an alternative way to do it. Code copied from answer to from the following question and converted to VB.Net.
Serializing a .NET EventLogEntry instance to XML
Imports System.Diagnostics.Eventing.Reader
Sub Main()
Dim query As New EventLogQuery("System", PathType.LogName)
Dim watcher As New EventLogWatcher(query)
AddHandler watcher.EventRecordWritten, AddressOf watcher_EventRecordWritten
watcher.Enabled = True
Console.ReadLine()
End Sub
Public Sub watcher_EventRecordWritten(sender As Object, e As EventRecordWrittenEventArgs)
Console.WriteLine(e.EventRecord.ToXml())
End Sub
Put in the main module of a simple console application and an watches for system events. Writing out the event data converted to XML as one long string.
Worked using 4.5 framework on a Windows 7 machine.

VB.NET batch pdf printer tool

I'm looking for a tool, but I can't find it. So I thought, maybe I can make one. Seems like a good idea, a program that fits my needs at last! Just one problem.. I don't know how!
Intro
At my work we create production drawings in .dwg format. Once this is done they are exported as .pdf sent to the client for approval. If approved they are issued for production, so they need to be plotted.
So my current workflow is:
Set my default printer preferences (number of copies, paper size, ..)
Go to the folder that has the .pdf files
Select 15 files
Right click print.
The problem here is
The files are printed in the order the printer receives them and not the order in the folder. So I would need to sort them out ( this x number times the number of copies sometimes this goes up to 6 times. )
I can only do 15 at a time (large projects are +100 documents)
I have to reset my preferences each time the sizes change.
Our file numbering system has some "intelligence" into it. Its build like this:
A1-12345-001 rev1
A1 = page size
12345 = document number, the same within a project. Other project means other number. (mostly irrelevant as I only print a project at a time)
001 = sequence number, next drawing will be 003,004,005,007,... you get the drift.
rev1 = revision number. Normally only the highest revision should be located in the folder, but it could be used to check for documents with a lower revision.
Now, I would like to automate my happy printing task, as this makes my week very bad if a large projects needs to go into production or, there are revisions mid-production and we need to re-issue them for production.
So far the situation sketch
Program sketch
So I've started to make a sketch of what the program should do.
User should be able to add .pdf files into a list. file browser object for starters, can be drag and drop later (the drawings are in one folder so there is no real need for drag and drop).
The list should contain 4 columns. paper size, document number, sequence, revision. Could be a data-grid view.
The list should be sorted by the drawing sequence. This how I would like to pass the drawing so, no sorting is required anymore! You can look at the sequence as page numbers.
Select the desired printer to do the job. (usually the same but other departments also have a printer so that would be a nice option.)
Set the number of copies. When printed, it shouldn't be 5x -001 then 5x -002 .. it should print them still in order of the sequence number and the re-loop the process x times.
Print the documents.
Adding PDF files
I started out with creating a dialog.. easy enough I guess.(please keep in mind that I'm a very low level programmer and nothing seems easy to me..) I added an open file dialog to my windows-form set multiple select true. Also made a filter to have only .pdf files
added a button with this code:
Private Sub ADD_FILES_Click(sender As Object, e As EventArgs) Handles ADD_FILES.Click
' Show the open file dialog. If user clicks OK, add pdf_document to list(of T)
If FileDialog.ShowDialog() = DialogResult.OK Then
Dim file As String
For Each file In FileDialog.FileNames
Debug.Print(file)
Next
End If
End Sub
So this should give me all the info I need from the file. I will edit this later, I know how to access it now!
The document object
I guess it would be wise to use some o.o.p. for this. As each file is a document and have the same required properties to make this work.
So I made a Public class for the document called PDF_Document
Public Class PDF_Document
Public FullFilePath As String
Public Property Size As String
Public Property DocNumber As String
Public Property Sequence As String
Public Property Revision As String
Public Sub New(ByVal oFilePath As String)
' Set the FullFilePath
FullFilePath = oFilePath
' Get the filename only without path.
Dim oFileName As String
oFileName = Path.GetFileName(oFilePath)
' Get the document size from the file name
Size = oFileName.Substring(0, 2)
' Get the document number from the file name
DocNumber = oFileName.Substring(3, 5)
' Get the sequence from the file name
Sequence = oFileName.Substring(9, 3)
' Chop of the .pdf from the name to get access the revision
Revision = oFileName.Substring(oFileName.Length - 5, 1)
End Sub
End Class
Well this should result into the info I need from the document..
creating a list(of t)
Wow, it seems to be getting somewhere.. Now to hold the list I'll have this collection I think don't know whats best for this? Public oPrintList As New List(Of PDF_Document)
So I think I should populate my list like this?
Public oPrintList As New List(Of PDF_Document)
Private Sub ADD_FILES_Click(sender As Object, e As EventArgs) Handles ADD_FILES.Click
' Show the open file dialog. If user clicks OK, add pdf_document to list(of T)
If FileDialog.ShowDialog() = DialogResult.OK Then
Dim oFile As String
For Each oFile In FileDialog.FileNames
Dim oPDF As New PDF_Document(oFile)
oPrintList.Add(oPDF)
Next
End If
End Sub
Making things visual for the user
Hmm okay, were getting somewhere, I got a list of all the files I need! But I want to see them in a viewer. I'm gonna use a data-grid view maybe? It should show my properties and it looks good I think.
So I made a binding that binds my List(of T) and added this binding as data-source for the data-grid view. I also change the ADD_FILES_Click a little, the PDF_Document is now added into the binding and not in the List(of T).
Public Class Form1
Public oPrintList As New List(Of PDF_Document)
Public oBinding As BindingSource
Private Sub ADD_FILES_Click(sender As Object, e As EventArgs) Handles ADD_FILES.Click
' Show the open file dialog. If user clicks OK, add pdf_document to list(of T)
If FileDialog.ShowDialog() = DialogResult.OK Then
Dim oFile As String
For Each oFile In FileDialog.FileNames
Dim oPDF As New PDF_Document(oFile)
oBinding.Add(oPDF)
Next
End If
End Sub
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
oBinding = New BindingSource(oPrintList, Nothing)
DataGridView1.DataSource = oBinding
End Sub
End Class
Printing the list
Well I managed to do quite some things now. But.. the main essence still isn't reached! I now got a form with a bunch of buttons that don't work yet, a list of select documents in queue for printing and .. thats it :)
Now I'm trying to create a method that prints a .pdf file.. easier sad than done. I need some help with this.. I search the net, but I can find samples that don't work, or I don't understand. All users PC's are equiped with acrobat reader.
Also feel free to comment me on the other parts of the program. ( yes I know there is no sorting function yet etc. ) but getting a page from the printer is more important now.
Sorry for the long post!
If your users have Adobe Acrobat Reader installed, the following code should do the trick. I recommend Acrobat Reader 11 or lower version. With Acrobat DC the window from Acrobat does not close anymore, that is a "design" decision by Adobe.
Dim pr As New Process()
pr.StartInfo.FileName = "c:\myfile.pdf"
pr.StartInfo.UseShellExecute = True
pr.StartInfo.Verb = "print"
pr.Start()
pr.WaitForExit()
I work with DWG and PDF files for 20+ years. If you are interested in a solution that fully automates all steps you explained in your "wishlist" software and does a ton more feel free to contact me at pdfmagick at gmail dot com
Another way to print PDF files with the Print Drivers dialog is as follows:
Dim starter As ProcessStartInfo
starter = New ProcessStartInfo(<pathToAdobeAcrobatExecutable>, String.Format(" /s /N /P ""{0}""", Filename))
Dim Process As New Process()
Process.StartInfo = starter
Process.Start()
Process.WaitForExit()
Process = Nothing
starter = Nothing
More command line switches are explained here
Adobe Reader Command Line Reference
Regards

Notepad database in VB

I am completely new to VB.net and have only been learning in for a few weeks
I am doing a project where i need to make an EPOS systems using notepad as a data base. I am able to make the values of the buttons appear in the list box, however I have numerous buttons all with different values but only the first value in the text box is appearing each time a different button is pressed.
E.G
When Heineken button pressed "Heineken €5.00" is displayed
when Guiness button pressed "Heineken €5.00" is displayed
Any help is greatly appreciated!
Imports System.IO
Public Class Form1
Private Sub btnHeineken_Click(sender As Object, e As EventArgs) Handles btnHeineken.Click
Dim sr As IO.StreamReader = IO.File.OpenText("DATABASE.txt")
'File DATABASE.TXT is the the debug folder
Dim name As String
Dim stock, price As Double
name = sr.ReadLine
stock = CDbl(sr.ReadLine)
price = CDbl(sr.ReadLine)
lstBox.Items.Add(name & "" & FormatCurrency(price))
name = sr.ReadLine
End Sub
Private Sub BtnGuiness_Click(sender As Object, e As EventArgs) Handles BtnGuiness.Click
Dim sr As IO.StreamReader = IO.File.OpenText("DATABASE.txt")
'File DATABASE.TXT is the the debug folder
Dim name As String
Dim stock, price As Double
name = sr.ReadLine
stock = CDbl(sr.ReadLine)
price = CDbl(sr.ReadLine)
lstBox.Items.Add(name & "" & FormatCurrency(price))
name = sr.ReadLine
End Sub
DATBASE.txt
Heineken
5.00
20
Guiness
4.50
50
Bulmers
5.00
25
Both your methods have exactly the same code. Thus, they do exactly the same thing: They show the contents of the first entry in your text file.
If you want your methods to do different things, you need to put different code in them.
Unfortunately, putting arbitrary code in your methods won't make them do what you want. It looks like you already discovered that. So the next step is to take a more structured approach:
Decide what your button click should do. It looks like you already did that: You want to display "Guiness €4.50" when the "Guiness" button is clicked.
Next, think about how your program can do that. Apparently, that's where you are stuck. You have a text file with a list of entries, how do you get the one you want?
Translate the result of step 2 (the "algorithm") in code.
You tried to do step 3 before step 2. That won't work, and that's the reason why your code doesn't work.
I suggest that you think really hard about step 2 (How do I find data in a text file? How would I do it if I had the file printed out in front of me and were searching for the data personally?), come up with an algorithm and then return here and ask a new question if you need help translating it to code.

No output in using wav file input with Microsoft SAPI 5.4 Api

I am working on a project where i need to use speech recognition to convert a wav file input speech ( conversation ) to text. After trying CMUSPhinx for a while, with terrible results, i am considering using Microsoft SAPI (Speech API) 5.4
I am coding as a Visual basic windows application from visual studio. Here is my code snippet :
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Dim SAPI
' SAPI = CreateObject("sapi.spvoice")
' SAPI.Speak(TextBox1.Text)
' Create new recognizer
Dim Recognizer As New SpInprocRecognizer
' create input file stream
InputFile = New SpFileStream
' Defaults to open for read-only, and DoEvents false
InputFile.Open(MY_WAVE_AUDIO_FILENAME)
' connect wav audio input to speech recognition engine
Recognizer.AudioInputStream = InputFile
' create recognition context
RecoContext = Recognizer.CreateRecoContext
' AddHandler RecoContext.Recognition, AddressOf RecoContext_Recognition
' create grammar
Grammar = RecoContext.CreateGrammar
' ... and load dictation
Grammar.DictationLoad()
' start dictating
Grammar.DictationSetState(SGDSActive)
End Sub
In the MY_WAVE_AUDIO_FILENAME, i have given the filename with full path. When i run this code on click of the button, i dont get any output. I have used the following recognition method :
Private Sub RecoContext_Recognition(ByVal StreamNumber As Long, ByVal StreamPosition As Object, ByVal RecognitionType As SpeechRecognitionType, ByVal Result As ISpeechRecoResult)
' Log/Report recognized phrase/information
Console.WriteLine("Reached here......")
TextBox1.Text = "Text should change"
End Sub
When i debug the application, flow is not reaching the RecoContext_Recognition method. The input file is a wav file with 16 bits per sample, 30 sec long conversation.
I am using the code mentioned in this link :
http://msdn.microsoft.com/en-us/library/ee431813(v=vs.85).aspx
How can i check for the issue ? I had read somewhere that dictation needs training to be given to Speech Recognition engine, if its required in my case too then how can i do that? Also in the link it is mentioned that we need to specify the length of the input file in order to do
this, am not sure how to do this as well. Help needed.
The sample code is missing a few steps that need to be addressed.
1) Inproc recognizers need to bind an engine before they will do any recognitions at all;
2) The inproc recognizer needs to be set active before it will start processing audio.
You should also consider adding handlers for other events, in particular SPEI_START_SR_STREAM, SPEI_SOUND_START, SPEI_SOUND_END, and SPEI_PHRASE_START to verify that the SR engine is processing audio at all and that it's trying to do some recognition.

VB.NET WebBrowser disable javascript

Is there a way to disable javascript webbrowser in vb.net?
works for me:
Private Function TrimScript(ByVal htmlDocText As String) As String
While htmlDocText.ToLower().IndexOf("<script type=""text/javascript"">") > -1
Dim s_index As Integer = htmlDocText.ToLower().IndexOf("<script type=""text/javascript"">")
Dim e_index As Integer = htmlDocText.ToLower().IndexOf("</script>")
htmlDocText = htmlDocText.Remove(s_index, e_index - s_index)
End While
Return htmlDocText
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString(yourUrl)
Dim wb As New WebBrowser
wb.Navigate("")
Do While wb.ReadyState <> WebBrowserReadyState.Complete
Application.DoEvents()
Loop
Dim script As String = TrimScript(result)
wb.DocumentText = script
End Sub
The short answer is: No.
The slightly longer answer is: No, the web-browser control API does not allow disabling standard browser functionality.
No really...but if you getting that annoying error message that pops up saying a script is running then you can turn the property of the webbrowser's suppress-errors "true"
Which popup message do you want to disable? If it's the alert message, try this, obviously resolving the window or frame object to your particular needs, I’ve just assumed top-level document, but if you need an iframe you can access it using window.frames(0). for the first frame and so on... (re the JavaScript part)... here is some code, assuming WB is your webbrowser control...
WB.Document.parentWindow.execScript "window.alert = function () { };", "JScript"
You must run the above code only after the entire page is done loading, i understand this is very difficult to do (and a full-proof version hasn't been published yet) however I have been doing it (full proof) for some time now, and you can gather hints on how to do this accurately if you read some of my previous answers labelled "webbrowser" and "webbrowser-control", but getting back to the question at hand, if you want to cancel the .confirm JavaScript message, just replace window.alert with window.confirm (of course, qualifying your window. object with the correct object to reach the document hierarchy you are working with). You can also disable the .print method with the above technique and the new IE9 .prompt method as well.
If you want to disable JavaScript entirely, you can use the registry to do this, and you must make the registry change before the webbrowser control loads into memory, and every time you change it (on & off) you must reload the webbrowser control out and into memory (or just restart your application).
The registry key is \HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\ - the keyname is 1400 and the value to disable it is 3, and to enable it is 0.
Of course, because there are 5 zones under the Zones key, you need to either change it for the active zone or for all zones to be sure. However, you really don't need to do this if all you want to do si supress js dialog popup messages.
Let me know how you go, and if I can help further.