Stuck on my Login Panel - vb.net

It keeps returning null and I was hoping someone could clean it up for me and see if there is a simpler way to do this. I'm really wanting to start making my game.
Public Class frmLogin
Private Sub mnuExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuExit.Click
Application.Exit()
End Sub
Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
Dim FILE_NAME As String = "C:\Users\Nick\documents\visual studio 2010\Projects\LoginFixed\Accounts\" + Me.txtCUser.Text
If File.Exists(FILE_NAME) Then
Me.lblExists.Text = "Username has already been created!"
Return
End If
If txtCUser.Text.Length < 3 Then
Me.lblExists.Text = "Must have atleast 3 characters."
Return
End If
Dim writeFile As StreamWriter = File.CreateText("C:\Users\Nick\documents\visual studio 2010\Projects\LoginFixed\Accounts\" + Me.txtCUser.Text)
writeFile.WriteLine("User: " + Me.txtCUser.Text) ' user
writeFile.WriteLine("Pass: " + Me.txtCPass.Text) ' pass
writeFile.WriteLine("-------------------")
writeFile.Close()
End Sub
Private Function GetLine(ByVal fileName As String, ByVal line As Integer) As String
Try
If File.Exists(fileName) = False Then
Using sr As New StreamReader("C:\Users\Nick\documents\visual studio 2010\Projects\LoginFixed\Accounts\" + Me.txtUser.Text)
For i As Integer = 1 To line - 1
sr.ReadLine()
Next
Return (sr.ReadLine())
sr.Close()
End Using
End If
Catch ex As Exception
Return ex.Message
End Try
End Function
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Dim FILE_NAME As String = "C:\Users\Nick\documents\visual studio 2010\Projects\LoginFixed\Accounts\" + Me.txtUser.Text
If File.Exists(FILE_NAME) And Me.txtPassword.Text = (GetLine(FILE_NAME, 2).Substring(6)) Then
Me.lblLoggedIn.Text = "Logged"
ElseIf File.Exists(FILE_NAME) = False Then
Me.lblLoggedIn.Text = "You must create an account! Navigate to TabPage2."
End If
End Sub
End Class
It would really help a lot. I just started vb not to long ago maybe about a week or two.

Three things. First, in GetLine() you're attempting to open the file if it does NOT exist; change from False to True. Second, you should open the file name that was passed in, not a hard-coded one that uses the value from a TextBox. Lastly, to get rid of the warning, you need to return something if the file does not exist:
Change GetLine() to:
Private Function GetLine(ByVal fileName As String, ByVal line As Integer) As String
Try
If File.Exists(fileName) Then
Using sr As New StreamReader(fileName)
For i As Integer = 1 To line - 1
sr.ReadLine()
Next
Return sr.ReadLine()
End Using
Else
Return "{File Not Found: " & fileName & "}"
End If
Catch ex As Exception
Return ex.Message
End Try
End Function
*You were returning the exception as a string, so I followed that model with the file not found error. How will you know, though, if you have an actual error, or if the line in the file was exactly like the "error" being returned?

Related

Visual Basic time synchronizing

I am working oin a project in vb.net although I am not an expert in it, I just used it because U think it is the best for this kind of problem.
I have a project with two buttons and a label; first button is for sync windows date from a server and the other is to change the windows date to (2014, 11, 16). I am doing this because some programs I have doesn't run unless the date is this one and as you know browser must be the real time to run this is the idea of this project.
The second button is working perfectly, but the sync date button doesn't work and throws this error in my label
No connection because the target machine refused to connect
Here is my function and my server ip
Public Function GetNISTTime(ByVal host As String) As String
Dim timeStr As String = ""
Try
Dim reader As New StreamReader(New TcpClient(host, 13).GetStream)
LastSysTime = DateTime.UtcNow()
timeStr = reader.ReadToEnd()
reader.Close()
Catch ex As SocketException
GetNISTTime = ex.Message
Exit Function
Catch ex As Exception
GetNISTTime = ex.Message
Exit Function
End Try
'Dim jd As Integer = Integer.Parse(timeStr.Substring(1, 5))
'Dim yr As Integer = Integer.Parse(timeStr.Substring(7, 2))
'Dim mo As Integer = Integer.Parse(timeStr.Substring(10, 2))
'Dim dy As Integer = Integer.Parse(timeStr.Substring(13, 2))
'Dim hr As Integer = Integer.Parse(timeStr.Substring(16, 2))
'Dim mm As Integer = Integer.Parse(timeStr.Substring(19, 2))
'Dim sc As Integer = Integer.Parse(timeStr.Substring(22, 2))
'Dim Temp As Integer = CInt(AscW(timeStr(7)))
Return timeStr ' New DateTime(yr + 2000, mo, dy, hr, mm, sc)
End Function
and the button
Private Sub real_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles real.Click
GetNISTTime("mail.harf.com.sa")
Label1.Text = GetNISTTime("mail.harf.com.sa").ToString
End Sub
I think the problem is because of the server but I didn't find any dns server that does sync successfully.
This is my program download link if you want to see the problem in with your eyes (you should run it as adminstrator)
http://www.mediafire.com/file/wfw5jpag8w2hofb/Release.rar/file
Also it must be dns in Saudi Arabia time zone
Your function call is not correct.
Private Sub real_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles real.Click
GetNISTTime("mail.harf.com.sa")
Label1.Text = GetNISTTime("mail.harf.com.sa").ToString
End Sub
should be:
Private Sub real_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles real.Click
Label1.Text = GetNISTTime("mail.harf.com.sa")
End Sub
GetNISTTime is a function that returns a string, so your original first line (GetNISTTime("mail.harf.com.sa")) does the work but nothing is done with the return value. Your original second line takes a return value that is a string and then tries to convert it to a string.
In addition, your function may not return anything if an error occurs. You have used a VBA style assignment in the catch block. Instead, try:
Public Function GetNISTTime(ByVal host As String) As String
Dim timeStr As String = ""
Try
Dim reader As New StreamReader(New TcpClient(host, 13).GetStream)
LastSysTime = DateTime.UtcNow()
timeStr = reader.ReadToEnd()
reader.Close()
Catch ex As SocketException
return ex.Message
Catch ex As Exception
Return ex.Message
End Try
'any other stuff
Return timeStr
End Function
so i did like what Visual Vincent say and this is my code after editing it
and it worked perfectly with me just need administrator permissions
code
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports System.Runtime.InteropServices
Public Class Daytime
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim d As DateTime
d = "12:52:00"
Try
Microsoft.VisualBasic.TimeOfDay = d 'Your time...
Microsoft.VisualBasic.DateString = New Date(2014, 11, 16) 'The date...
Catch ex As Exception
'You might have to run as Administrator...?
End Try
End Sub
Private Sub real_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles real.Click
Process.Start("CMD", "/C net start w32time & w32tm /resync /force & pause")
End Sub
End Class

Search through text file and return a line of text

I am trying to create a program that will search a text file for a line of text and then return the full line of information.
Example line: Joe Blogs JBL 1234
Search: Joe Blogs
Search returns: Joe Blogs JBL 1234
To make it as simple as possible, I have 2 text boxes & 1 button.
Textbox1 = search
Textbox2 = Search results
Button = Search button
Can anyone tell me how to do this because I'm finding it really difficult. I'm new to VB coding so the simplest of code would be helpful!
This is what I have so far:
Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Input Text Error
If TextBox1.TextLength = 0 Then
MsgBox("Please enter a Staff Name or Staff Code", MsgBoxStyle.Information, "Error")
End If
'Perform Search
Dim strText As String = SearchFile("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt", TextBox1.Text)
If strText <> String.Empty Then
TextBox2.Text = strText
End If
End Sub
'Search Function
Public Shared Function SearchFile(ByVal strFilePath As String, ByVal strSearchTerm As String) As String
Dim sr As StreamReader = New StreamReader(strFilePath)
Dim strLine As String = String.Empty
Try
Do While sr.Peek() >= 0
strLine = String.Empty
strLine = sr.ReadLine
If strLine.Contains(strSearchTerm) Then
sr.Close()
Exit Do
End If
Loop
Return strLine
Catch ex As Exception
Return String.Empty
End Try
End Function
'Clear Button
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TextBox2.Text = ""
TextBox1.Text = ""
End Sub
' Open The text file
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Process.Start("C:\Users\kylesnelling\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt")
End Sub
End Class
Whenever I perform a search, all I get back is the last line of the text file... does anyone know why?
As Alex B has stated in comments, line If strLine.Contains("textbox1.text") should be If strLine.Contains(strSearchTerm)
Also you are not passing in the search item to the function. The below line you have passed in the string textbox1.text as a string rather than the text inside the textbox. Hence why you never find the line you are searching for and always returns the last record of your file.
Dim strText As String = SearchFile("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt", "textbox1,text")
This line should be:
Dim strText As String = SearchFile("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt", textbox1.text)
Also with this line Dim sr As StreamReader = New StreamReader("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt") why have you used the same path destination when you have already passed in this file location in the variable strFilePath.
line should be Dim sr As StreamReader = New StreamReader(strFilePath)
Its best to use the variables being passed into the function otherwise this function won't be very useful to other parts of code that may be referencing it or if search terms or filepaths change.
Updated from comments:
strLine.ToUpper.Contains(strSearchTerm.ToUpper) this line will make both text uppercase and the word you are searching for to uppercase, which will allow them to ignore case sensitivity, so for example, "text" can match with "Text" by both being converted to "TEXT" when used to compare.
Give this a try friend.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim searchResult As String = SearchFile("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt", _
"text to search for")
Me.TextBox2.Text = searchResult
End Sub
Public Shared Function SearchFile(ByVal strFilePath As String, ByVal strSearchTerm As String) As String
Dim fs As New System.IO.StreamReader(strFilePath)
Dim currentLine As String = String.Empty
Try
Dim searchResult As String = String.Empty
Do While fs.EndOfStream = False
currentLine = fs.ReadLine
If currentLine.IndexOf(strSearchTerm) > -1 Then
searchResult = currentLine
Exit Do
End If
Loop
Return searchResult
Catch ex As Exception
Return String.Empty
End Try
End Function

Download a file from google drive

First of all, sorry for my english. Second, I want to make an app that, at every launch download a .txt file from google drive, the file is defined (I mean, it's in drive). It's just a single file, but, when I launch the app, the file is downloaded, but dosen't contain anything..
Here is my code:
Private Function ReadLine(ByVal Line As Integer, ByVal lista As List(Of String)) As String
Return lista(Line - 1)
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If My.Computer.Network.IsAvailable() = True Then
Try
My.Computer.FileSystem.DeleteFile("C:\WINDOWS\" & fisier)
Catch ex As Exception
End Try
My.Computer.Network.DownloadFile("https://doc-14-7c-docs.googleusercontent.com/docs/securesc/17t22h2a63tpkhdgv047v6i0s5a9o8bm/qgqjocmi87jt0up72gfpg9dseeo3pt84/1458396000000/07699472972018131827/07699472972018131827/0B8iVIf__yN1FUDV1STNWODJUYms?e=download&nonce=5jnki0mtgo520&user=07699472972018131827&hash=0gi5r6k7rm2uob14062tlbsk0nhpkoo1", _
"C:\WINDOWS\" & fisier)
Dim reader As New IO.StreamReader("C:\WINDOWS\" & fisier)
Dim lista As New List(Of String)
While Not reader.EndOfStream
lista.Add(reader.ReadLine)
End While
reader.Close()
If My.Computer.FileSystem.FileExists(fisier2) = False Then
lblWould.Text = ReadLine(1, lista)
Else
Dim nr As Integer
nr = Val(My.Computer.FileSystem.ReadAllText(fisier2))
nrx = nr
End If
Dim contain As String = My.Computer.FileSystem.ReadAllText("C:\WINDOWS\" & fisier)
contain = contain.Replace(lblWould.Text, "SEEN!")
My.Computer.FileSystem.WriteAllText("C:\WINDOWS\" & fisier, contain, False)
Else
MsgBox("Trebuie sa fi connectat la internet!")
Me.Close()
End If
End Sub
Private Sub btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnYes.Click, btnNo.Click
Dim reader As New IO.StreamReader("C:\WINDOWS\" & fisier)
Dim lista As New List(Of String)
Dim a As String
While Not reader.EndOfStream
a = reader.ReadLine()
If Not a = "SEEN!" Then
lista.Add(reader.ReadLine)
End If
End While
lblWould.Text = lista(nrx + 1)
nrx += 1
Dim contain As String = My.Computer.FileSystem.ReadAllText("C:\WINDOWS\" & fisier)
contain = contain.Replace(lblWould.Text, "SEEN!")
My.Computer.FileSystem.WriteAllText("C:\WINDOWS\" & fisier, contain, False)
End Sub`
Thanks!

Reading a text file into an array does nothing when Submit is clicked

I need this program to take the countries.txt file and read it into the country.countryarray when the program loads. Then the user needs to be able to enter a country name in the nmtext.text field and click submit and the country abbreviation should be pulled from the array and displayed in the abbrevtext.text field and complete the same action if the user searches an abbreviation from the abbrevtext.text field then it needs to display the country name in the nmtext.text field.
The countries.txt file has 250 countries and has to be stored in the debug file for the project and the contents of the file look like this when viewed in notepad++ with a carriage return at the end of each line.
0.AC
1.Ascension Island
2.AD
3.Andorra
4.AE
5.United Arab Emirates
6.AF
7.Afghanistan
8.AG
9.Antigua and Barbuda
10.AI
Here is my code so far and it is not working it will pop up the form and let me enter a country name but it doesn't do anything when I hit submit.
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Public Class CountForm
'CREATES STRUCTURE AND ARRAY
Public Structure Countries
Public CountryArray
Public CountryString As String
End Structure
'CREATES OBJECT FOR STRUCTURE
Public Country As Countries
'CREATES STREAM READER
Private MyStreamReader As System.IO.StreamReader
'CREATES FILESTRING VARIALE TO REFERENCE THE FILE PATH
Public FileString As String = "C:\Users\User\Desktop\Basic\CountryFile\CountryFile\bin\Debug\Countries.Txt"
'CREATES TEXTFIELDPARSER AND REFERENCES FILESTRING TO CALL THE FILEPATH
Private TextFieldParser As New TextFieldParser(FileString)
Private Sub CountForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Try
Country.CountryArray = File.ReadAllText(FileString) '// gets all the text in the file'
Catch ex As Exception
Dim ResponseDialogResult As String
' File missing.
ResponseDialogResult = MessageBox.Show("Something Went Wrong",
"Debuging Purposes", MessageBoxButtons.OK,
MessageBoxIcon.Question)
If ResponseDialogResult = DialogResult.Yes Then
End If
If ResponseDialogResult = DialogResult.No Then
' Exit the program.
Me.Close()
End If
End Try
End Sub
Private Sub Submit_Click(sender As System.Object, e As System.EventArgs) Handles Submit.Click
Try
TextFieldParser.TextFieldType = FieldType.Delimited
TextFieldParser.SetDelimiters(Environment.NewLine)
Do Until MyStreamReader.Peek = -1
If NmText.Text.ToUpper.Contains(Country.CountryArray.ToUpper()) Then
AbbrevText.Text = Country.CountryArray.ToUpper - 1
Else
MessageBox.Show("Name or Abbreviation Was Not Found", "Error", MessageBoxButtons.OK)
End If
Loop
Catch ex As Exception
End Try
End Sub
Private Sub Clear_Click(sender As System.Object, e As System.EventArgs) Handles Clear.Click
NmText.Text = ""
AbbrevText.Text = ""
End Sub
End Class
The StreamReader/TextFieldParser approach seems really complicated. Maybe this works for you:
Public Class Form1
Private countryDict As New Dictionary(Of String, String)
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim lineArray = IO.File.ReadAllLines("countries.txt")
'this will cause trouble if there is a NewLine at the end of the file
'In this case just remove the last new line.
For index = 0 To lineArray.Length - 2 Step 2
countryDict.Add(lineArray(index), lineArray(index + 1))
Next
End Sub
Private Sub Submit_Click(sender As System.Object, e As System.EventArgs) Handles Submit.Click
If countryDict.ContainsKey(NmText.Text.ToUpper()) Then
AbbrevText.Text = countryDict(NmText.Text.ToUpper())
Else
MsgBox("Name or Abbreviation Was Not Found")
End If
End Sub
End Class

Read Text File and Output Multiple Lines to a Textbox

I'm trying to read a text file with multiple lines and then display it in a textbox. The problem is that my program only reads one line. Can someone point out the mistake to me?
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Public Class Form1
Private BagelStreamReader As StreamReader
Private PhoneStreamWriter As StreamWriter
Dim ResponseDialogResult As DialogResult
Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
'Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
'Is file already open
If PhoneStreamWriter IsNot Nothing Then
PhoneStreamWriter.Close()
End If
With OpenFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
'If ResponseDialogResult <> DialogResult.Cancel Then
' PhoneStreamWriter = New StreamWriter(OpenFileDialog1.FileName)
'End If
Try
BagelStreamReader = New StreamReader(OpenFileDialog1.FileName)
DisplayRecord()
Catch ex As Exception
MessageBox.Show("File not found or is invalid.", "Data Error")
End Try
End Sub
Private Sub DisplayRecord()
Do Until BagelStreamReader.Peek = -1
TextBox1.Text = BagelStreamReader.ReadLine()
Loop
'MessageBox.Show("No more records to display.", "End of File")
'End If
End Sub
Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
With SaveFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
PhoneStreamWriter.WriteLine(TextBox1.Text)
With TextBox1
.Clear()
.Focus()
End With
TextBox1.Clear()
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
PhoneStreamWriter.Close()
Me.Close()
End Sub
End Class
Here is a sample textfile:
Banana nut
Blueberry
Cinnamon
Egg
Plain
Poppy Seed
Pumpkin
Rye
Salt
Sesame seed
You're probably only getting the last line in the file, right? Your code sets TextBox1.Text equal to BagelSteramReader.ReadLine() every time, overwriting the previous value of TextBox1.Text. Try TextBox1.Text += BagelStreamReader.ReadLine() + '\n'
Edit: Though I must steal agree with Hans Passant's commented idea on this; If you want an more efficient algorithm, File.ReadAllLines() even saves you time and money...though I didn't know of it myself. Darn .NET, having so many features...
I wrote a program to both write to and read from a text file. To write the lines of a list box to a text file I used the following code:
Private Sub txtWriteToTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtWriteToTextfile.Click
Dim FileWriter As StreamWriter
FileWriter = New StreamWriter(FileName, False)
' 3. Write some sample data to the file.
For i = 1 To lstNamesList.Items.Count
FileWriter.Write(lstNamesList.Items(i - 1).ToString)
FileWriter.Write(Chr(32))
Next i
FileWriter.Close()
End Sub
And to read and write the contents of the text file and write to a multi-line text box (you just need to set the multiple lines property of a text box to true) I used the following code. I also had to do some extra coding to break the individual words from the long string I received from the text file.
Private Sub cmdReadFromTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdReadFromTextfile.Click
Dim sStringFromFile As String = ""
Dim sTextString As String = ""
Dim iWordStartingPossition As Integer = 0
Dim iWordEndingPossition As Integer = 0
Dim iClearedTestLength As Integer = 0
Dim FileReader As StreamReader
FileReader = New StreamReader(FileName)
sStringFromFile = FileReader.ReadToEnd()
sTextString = sStringFromFile
txtTextFromFile.Text = ""
Do Until iClearedTestLength = Len(sTextString)
iWordEndingPossition = CInt(InStr((Microsoft.VisualBasic.Right(sTextString, Len(sTextString) - iWordStartingPossition)), " "))
txtTextFromFile.Text = txtTextFromFile.Text & (Microsoft.VisualBasic.Mid(sTextString, iWordStartingPossition + 1, iWordEndingPossition)) & vbCrLf
iWordStartingPossition = iWordStartingPossition + iWordEndingPossition
iClearedTestLength = iClearedTestLength + iWordEndingPossition
Loop
FileReader.Close()
End Sub