Basic URI (Parsing?) - vb.net

I have been helped by the good people of stackoverflow many times before, so here's my problem...
I haven't been coding for a GOOD while, and for class, we are going to be starting Visual Basic. Visual Basic is really not that hard, but I am not familiar with it, and can't think of a proper way to do this.
As an exercise, I'm coding a very simple web browser. Here's my issue...
Private Sub Send_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Send.Click
Dim input As String = TextBox1.Text
Me.WebBrowser1.Navigate(New Uri(input))
If the user types "www.youtube.com" in the address bar, they throw an exception (I presume because there is no http:// at the beginning) However, I can't simply add "http://" to the beginning of the string, because then there is the chance for a double up.
How can I check the string for "http://" and add it accordingly?

You can use regular expression to validate the URL/URI.
Dim pattern = "http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"
Dim Inputurl = "http://www.abc.com/aa"
If Regex.IsMatch(Inputurl, pattern) Then
'
Else
'
End If
Or use String.StartsWith() method,
If Inputurl.StartsWith("http://") Then
'
End If

You need to do something like this:
Dim value As String = Mid(input, 1, 7)
if value = "http://" then
'you don't need to modifie the url
else
'you add your http:// string normaly
EndIf
Hope this can help you
PS: sory I corrected some mistakes I maid

Related

spell checking richtextbox in winforms project

I have a WinForms project that contains a RichTextBox (RTB) written with VB
I have set ShortcutsEnabled = FALSE in the RTB
To use any Spell Checker I am guessing this would need to set to TRUE
That is NOT my question! I have been reading for way more hours than I care to admit
With the understanding that Spell Checking is easy if you have a ASP.Net OR WPF project
Well I don't so here are the three candidates from NuGet NONE of these candidates offer much help
WeCantSpell.Hunspell and VPKSoft.SpellCheckUtility and NetSpell
I am not asking for a recommendation
Because I can not find a tutorial and am clueless on how to implement these Add In's with code
As well as NOT knowing if they are compatible with WinForms
I even looked at this CP post
CP LINK
Just a suggestion how to use one of these Add In's OR how to add spell checking to the RTB?
To achieve spell checking, you can try Nuget Package NHunspell.
First, you need to add "NHunspell" from "NuGet" and import it. The specific operation is as follows:
Right click the Reference and select "Manage NuGet Packages...", then type "NHunspell " in the search bar and install it:
Second step, you need to create a folder to store ".aff" and ".dic" like this.
Download the "zip" containing the corresponding file, you can access this site.
Here is a demo you can refer to.
Private Sub btCheck_Click(sender As Object, e As EventArgs) Handles btCheck.Click
Dim affFile As String = AppDomain.CurrentDomain.BaseDirectory & "../../Dictionaries/en_us.aff"
Dim dicFile As String = AppDomain.CurrentDomain.BaseDirectory & "../../Dictionaries/en_us.dic"
lbSuggestion.Items.Clear()
lbmorph.Items.Clear()
lbStem.Items.Clear()
Using hunspell As New Hunspell(affFile, dicFile)
Dim correct As Boolean = hunspell.Spell(TextBox1.Text)
checklabel.Text = TextBox1.Text + " is spelled " & (If(correct, "correct", "not correct"))
Dim suggestions As List(Of String) = hunspell.Suggest(TextBox1.Text)
countlabel.Text = "There are " & suggestions.Count.ToString() & " suggestions"
For Each suggestion As String In suggestions
lbSuggestion.Items.Add("Suggestion is: " & suggestion)
Next
Dim morphs As List(Of String) = hunspell.Analyze(TextBox1.Text)
For Each morph As String In morphs
lbmorph.Items.Add("Morph is: " & morph)
Next
Dim stems As List(Of String) = hunspell.Stem(TextBox1.Text)
For Each stem As String In stems
lbStem.Items.Add("Word Stem is: " & stem)
Next
End Using
End Sub
The result,
Hope this can help you.

TextBox Values not updating on click command

Im experimenting with upgrading from VBA to VB.NET, so I am learning some pretty basic stuff by figuring out the syntax differences between things I have done and). So far so good, but I cant seem to get a textbox to update the display value in the form. Anyone want to explain why I am dumb? I spent some time surfing the various interweb stuff, but have yet to find anything(unless I am dumb and just didnt understand it when i saw it).
Here's what I have so far:
Dim this As String = Trim$(Mid$(TextBox1.Text, InStr(TextBox1.Text, "&") + 1))
Dim oldtxt As String = TextBox1.Text
If InStr(TextBox1.Text, "&") > 0 Then
TextBox1.Text = TextBox1.Text.Replace(TextBox1.Text, "End Date Copied" & this)
Clipboard.SetText(this)
Threading.Thread.Sleep(2000)
TextBox1.Text = TextBox1.Text.Replace(TextBox1.Text, oldtxt)
End If
After digging through the UI of visual studio I was able to find a more "band-aid" type of resolution. Even though I havent messed with SubString function yet, that is my next learning step, I found this option to be sufficient in the immediate resolution. If I find a better way of implementing this I will post back for others to see (if they care).
Private Sub TextBox1_Enter(ByVal sender As Object, ByVal e As System.EventArgs) Handles Block1.Enter
Dim this As String = Trim$(Mid$(TextBox1.Text, InStr(TextBox1.Text, "&") + 1))
Dim oldtxt As String = TextBox1.Text
If InStr(TextBox1.Text, "&") > 0 Then
TextBox1.Text = TextBox1.Text.Replace(TextBox1.Text, "End Date Copied" & this)
Block1.Refresh()
Clipboard.SetText(this)
Threading.Thread.Sleep(200)
TextBox1.Text = TextBox1.Text.Replace(TextBox1.Text, oldtxt)
Block1.Refresh()
End If
End Sub
And just an FYI for #TEK, Enter and Click events for this work identically, so hopefully next time you try and help someone you wont get hung up on unnecessary details :)

Getting A NullRefrenceException And Cannot Find Out Why?

My goal here is to create a web browser that has a tab system in VB. Since I cannot explicitly name every single new tab the user will use, I have to make more generalized callings. Here's the conflicting code (my btnGo):
Dim thisBrowser As newWebBrowser = Me.tabBrowser.SelectedTab.Tag
If txtAdressSearch.Text.Contains(".com") Or txtAdressSearch.Text.Contains(".net") Or txtAdressSearch.Text.Contains(".gov") Or txtAdressSearch.Text.Contains(".edu") Or txtAdressSearch.Text.Contains(".org") Then 'More to be checked for
thisBrowser.Navigate(txtAdressSearch.Text)
Else
thisBrowser.Navigate("https://www.google.com/search?sourceid=chrome-psyapi2&rlz=1C1ASAA_enUS445&ion=1&espv=2&ie=UTF-8&q=" + txtAdressSearch.Text)
End If
And here's the newWebBrowser code:
Public Class newWebBrowser
Inherits WebBrowser
Private Sub webBrowserComplete() Handles Me.DocumentCompleted
Dim newTab As TabPage = frmBrowser.Tag()
Dim frmSK As New frmBrowser
Dim hi As String
newTab.Text = Me.DocumentTitle
frmSK.txtAdressSearch.Text = Me.Url.ToString
End Sub
End Class
Any time I enter something into txtAdressSearch, Visual Studio raises a NullRefrenceException and highlights thisBrowser.Navigate(txtAdressSearch.Text). As a side note, it says "Object reference not set to an instance of an object."
Anyone know whats the problem here? Thank you.
After debugging for more than an hour, I looked over my code and saw I was missing a big part of it. I wrote it all in and it worked fine. The issue was the tags weren't being defined correctly (and in some cases, not at all) so .Tag was returning Nothing.
Thanks to all who helped.

vb.net read string after certain character

I have an listbox which has some random URLs + basic info, eg:
[search website] - http://www.google.com/
[games website] - http://www.miniclip.com/
Each line is an item.
When I try to use this code, it crashes:
Private Sub doubleclickitem(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick
Dim url As String = ListBox1.SelectedItem
Process.Start(url)
End Sub
The error is the first characters are unknown for Process.Start.
How can I start the url? Someone told me I have to read the lines after the first " - ". Is this right? If so, how can I do so?
This should do it:
url = url.Substring(url.LastIndexOf(" - ") + 3)
you should be assigning a value to each text item in the list, then retrieving the value, and feeding that to process.start, for example if you want process.start to open google, then it would be like so....(provided you assign a value of http://www.google.com to whatever the selected item is)
Process.Start(ListBox1.SelectedValue)
this is for c#, but the same ideals will still apply http://forums.asp.net/t/1199141.aspx/1
Try this:
YourTextBox.Text = YourString.Substring(0, YourString.Text.LastIndexOf(" - "))

VB.NET Read Certain text in a text file

I want my program to read certain text in a text file. For example if I have a text file that contains the following info..
acc=blah
pass=hello
I want my vb.net application to get that the account variable is equal to blah, and the password variable is equal to hello.
Can anyone tell me how to do this?
Thanks
Here is a quick little bit of code that, after you click a button, will:
take an input file (in this case I created one called "test.ini")
read in the values as separate lines
do a search, using regular expressions, to see if it contains any "ACC=" or "PASS=" parameters
then write them to the console
here is the code:
Imports System.IO
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim strFile As String = "Test.INI"
Dim sr As New StreamReader(strFile)
Dim InputString As String
While sr.Peek <> -1
InputString = sr.ReadLine()
checkIfContains(InputString)
InputString = String.Empty
End While
sr.Close()
End Sub
Private Sub checkIfContains(ByVal inputString As String)
Dim outputFile As String = "testOutput.txt"
Dim m As Match
Dim m2 As Match
Dim itemPattern As String = "acc=(\S+)"
Dim itemPattern2 As String = "pass=(\S+)"
m = Regex.Match(inputString, itemPattern, _
RegexOptions.IgnoreCase Or RegexOptions.Compiled)
m2 = Regex.Match(inputString, itemPattern2, _
RegexOptions.IgnoreCase Or RegexOptions.Compiled)
Do While m.Success
Console.WriteLine("Found account {0}", _
m.Groups(1), m.Groups(1).Index)
m = m.NextMatch()
Loop
Do While m2.Success
Console.WriteLine("Found password {0}", _
m2.Groups(1), m2.Groups(1).Index)
m2 = m2.NextMatch()
Loop
End Sub
End Class
Have a look at this article
Reading and writing text files with VB.NET
Wile reading the file line by line, you can use String.Split Method with the splitter being "=", to split the string into param name, and param value.
Looks like you've got an INI file of some kind... The best way to read these is using the *PrivateProfile* functions of the windows API, which means you can actually have a proper full INI file quite easily for anything you need. There is a wrapper class here you may like to use.
Microsoft recommends that you use the registry to store this sort of information though, and discourages use of INI files.
If you wish to just use a file manually with the syntax you have, it is a simple case of splitting the string on '=' and put the results into a Dictionary. Remember to handle cases where the data was not found in the file and you need a default/error. In modern times though, XML is becoming a lot more popular for data text files, and there are lots of libraries to deal with loading from these.
My suggestion: you use XML. The .NET framework has a lot of good XML tools, if you're willing to make the transition to put all the text files into XML, it'll make life a lot easier.
Not what you're looking for, probably, but it's a cleaner solution than anything you could do with plain text (outside of developing your own parser or using a lower level API).
You can't really selectively read a certain bit of information in the file exclusively. You'll have to scan each line of the file and do a search for the string "pass=" at the beginning of the line. I don't know VB but look up these topics:
File readers (espically ones that can read one line at a time)
String tokenizers/splitting (as Astander mentioned)
File reading examples
Have you thought about getting the framework to handle it instead?
If you add an entry into the settings tab of the project properties with name acc, type string, scope user (or application, depending on requirements) and value pass, you can use the System.Configuration.ApplicationSettingsBase functionality to deal with it.
Private _settings As My.MySettings
Private _acc as String
Private _pass as String
Public ReadOnly Property Settings() As System.Configuration.ApplicationSettingsBase
Get
If _settings Is Nothing Then
_settings = New My.MySettings
End If
Return _settings
End Get
End Property
Private Sub SetSettings()
Settings.SettingsKey = Me.Name
Dim theSettings As My.MySettings
theSettings = DirectCast(Settings, My.MySettings)
theSettings.acc=_acc
theSettings.pass=_pass
Settings.Save()
End Sub
Private Sub GetSettings()
Settings.SettingsKey = Me.Name
Dim theSettings As My.MySettings
theSettings = DirectCast(Settings, My.MySettings)
_acc=theSettings.acc
_pass=theSettings.pass
End Sub
Call GetSettings in whatever load event you need, and SetSettings in closing events
This will create an entry in the application.exe.config file, either in your local settings \apps\2.0\etc etc directory, or your roaming one, or if it's a clickonce deployment, in the clickonce data directory. This will look like the following:-
<userSettings>
<MyTestApp.My.MySettings>
<setting name="acc" serializeAs="String">
<value>blah</value>
</setting>
<setting name="pass" serializeAs="String">
<value>hello</value>
</setting>
</MyTestApp.My.MySettings>
</userSettings>
Writing your own parser is not that hard. I managed to make one for a game (Using C#, but VB appears to have Regex class too. Using that, the acc variable in your file would be everything up to the = sign, and then blah would be everything past the = to the newline character (\n) Then go to the next line and repeat.
I have written this for you, check it and enjoy with the results, have a great day!
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim acc As New List(Of String)
Dim pass As New List(Of String)
Dim lines() As String = System.IO.File.ReadAllLines(".\credentials.txt")
For Each lineItem As String In lines
Dim vals() As String = lineItem.Split(Convert.ToChar("="))
If vals.Length > 0 Then
Dim lineId As String = vals(0)
If lineId = "acc" Then
acc.Add(vals(1))
ElseIf lineId = "pass" Then
pass.Add(vals(1))
End If
End If
Next
TextBox_acc.Text = String.Join(Environment.NewLine, acc)
TextBox_pass.Text = String.Join(Environment.NewLine, pass)
End Sub
End Class