How would I go back to a certain line Visual Basic 2013? - vb.net

I am currently using visual basic to create a project and am stuck on a certain point...
I am trying to get back to a certain point once the selected operation was completed.
I would like to repeat the Button1_Click sub if that's possible.
Heres my code so far.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Text = ("Transfer")
TextBox1.Text = ("This program only allows the use of one application at a time in order to prevent corrupt files etc.")
CheckBox1.Show()
CheckBox2.Show()
CheckBox3.Show()
CheckBox4.Show()
If CheckBox1.Checked Then
CheckBox2.Enabled = False
CheckBox3.Enabled = False
CheckBox4.Enabled = False
TextBox2.Show()
TextBox2.Text = ("Completed without any faults : If error occurs resort to readme in download file.")
Button1.Text = ("Quit")
End If
If CheckBox2.Checked Then
CheckBox1.Enabled = False
CheckBox3.Enabled = False
CheckBox4.Enabled = False
TextBox2.Show()
TextBox2.Text = ("Completed without any faults : If error occurs resort to readme in download file.")
Button1.Text = ("Quit")
End If
If CheckBox3.Checked Then
CheckBox1.Enabled = False
CheckBox2.Enabled = False
CheckBox4.Enabled = False
TextBox2.Show()
TextBox2.Text = ("Completed without any faults : If error occurs resort to readme in download file.")
Button1.Text = ("Quit")
End If
If CheckBox4.Checked Then
CheckBox2.Enabled = False
CheckBox3.Enabled = False
CheckBox1.Enabled = False
TextBox2.Show()
TextBox2.Text = ("Completed without any faults : If error occurs resort to readme in download file.")
Button1.Text = ("Quit")
End If
End Sub

Don't.
You've already implemented way too much functionality in that click handler, stop right there!
Extract Methods
You need to refactor a little bit here - extract a method for this part:
TextBox2.Show()
TextBox2.Text = ("Completed without any faults : If error occurs resort to readme in download file.")
Button1.Text = ("Quit")
And then replace all copies of that snippet with a method call.
Then extract another method for each chunk you have there - and name them.
Consider renaming your controls/buttons as well - and thank yourself later :)
When you're done, your click handler should read like a high-level summary of what's happening, instead of like a monolithic script written in 1997 - because that's what your execution flow feels like right now.
Write a method for every single thing you want your code to do, and then call these methods. Simple!
If your code does what it's supposed to be doing (i.e. works as intended), and just looks messy, confusing and inefficient, consider asking on Code Review next time!

Related

Form Show not Called After Second Show

So I am using Visual Basic to create a windows form application. I have buttons on the side to select a table like this. When the 'bookings' button is pressed, the user it taken to a form that looks like this. I need the following code to run every time the form is shown (the form is hidden shown multiple times). I put the below code inside both the form load and the form shown actions and both of them will only run the code on the first time. The code isn't really relevant, I just need to know how I can make this run every time the form is shown, not just once. The only other way I have thought about which works is to make the code run every second which is just unnecessary and a waste of processing power. Also, if I wanted another action to run after this, the action that occurs every second will take priority.
Private Sub Form2_Shown(sender As Object, e As EventArgs) Handles Me.Shown
If GlobalVariables.GlobalFlag = "1" Then
Table1Sleep.Visible = False
Table1Selected.Visible = True
Table1Selected.BringToFront()
table1text.BringToFront()
table1textdesc.BringToFront()
ElseIf GlobalVariables.GlobalFlag = "2" Then
Table2Sleep.Visible = False
Table2Selected.Visible = True
Table2Selected.BringToFront()
table2textdesc.BringToFront()
table2text.BringToFront()
ElseIf GlobalVariables.GlobalFlag = "3" Then
Table3Sleep.Visible = False
Table3Selected.Visible = True
Table3Selected.BringToFront()
table3text.BringToFront()
table3textdesc.BringToFront()
ElseIf GlobalVariables.GlobalFlag = "4" Then
Table4Selected.Visible = True
Table4Selected.BringToFront()
tabel4text.BringToFront()
table4textdesc.BringToFront()
table4sleep.Visible = False
ElseIf GlobalVariables.GlobalFlag = "5" Then
Table5Selected.Visible = True
table5sleep.Visible = False
Table5Selected.BringToFront()
table5text.BringToFront()
table5textdesc.BringToFront()
ElseIf GlobalVariables.GlobalFlag = "6" Then
table6sleep.Visible = False
Table6Selected.Visible = True
Table6Selected.BringToFront()
table6text.BringToFront()
table6textdesc.BringToFront()
Else
MessageBox.Show("Something went wrong. When you press 'OK', you will be taken back to the Main Menu.")
MainMenuForm.Show()
Me.Close()
End If
End Sub
Thanks :)

Check if Mage.exe batch manifest update was successful or not - ClickOnce

I have created a console app that creates a batch file in code, that will automatically update and re-sign my app manifest file using mage.exe when a new version gets published.
This batch file then gets executed by the same console app after it has created it.
I want to know if there is a way to determine if the mage.exe batch file failed in updating or signing the manifest?
Any help or ideas will be appreciated.
UPDATE
As per TnTinMn's comment, I forced the batch to fail on updating the manifest. This returned a exit code of 1. How is it then possible for me to extract that exit code to do my error handling? Im doing the following:
Dim procInfo As New ProcessStartInfo()
procInfo.UseShellExecute = True
procInfo.FileName = (sDriveLetter & ":\updatemanifest.bat")
procInfo.WorkingDirectory = ""
procInfo.Verb = "runas"
procInfo.WindowStyle = ProcessWindowStyle.Hidden
Dim sval As Object = Process.Start(procInfo) 'I tested the object to see if there is indeed a value that i can use.
While debugging and looking at the sval object's properties, the exit code is set to 1 but i can't seem to extract it from there.
There are two ways (that I know of) that you can wait for the process to exit before retrieving the Process.ExitCode.
The first as is a blocking call: Process.WaitForExit
and the second is to use the Exit event.
Private Sub RunProcess()
Dim psi As New ProcessStartInfo()
psi.UseShellExecute = True
psi.WindowStyle = ProcessWindowStyle.Hidden
psi.FileName = "cmd.exe"
psi.Arguments = "/c Exit 100"
Dim proc As Process = Process.Start(psi)
proc.EnableRaisingEvents = True
AddHandler proc.Exited, AddressOf ProcessExited
End Sub
Private Sub ProcessExited(sender As Object, e As EventArgs)
Dim proc As Process = DirectCast(sender, Process)
proc.Refresh()
Dim code As Int32 = proc.ExitCode
Me.BeginInvoke(Sub() MessageBox.Show(String.Format("Process has exited with code: {0}", code)), Nothing)
proc.Dispose()
End Sub

Reading TXT file line by line (VB 2010)

I have a program written to be a username/password creator, and there is a section that I am attempting to make that will determine whether the entered username is taken or not, and inform the user. It doesn't seem to be working. My code is as follows:
z = File.OpenText(a)
Do Until z.EndOfStream() = True
Dim password As String
password = CStr(z.ReadLine() & vbCrLf)
If password = TextBox1.Text Then
errors = errors + 1
msgPrompt = msgPrompt & "The username you entered, " & TextBox1.Text & " is already taken."
End If
If errors > 1 Then
TextBox5.Text = errors & " errors occured."
ElseIf errors = 0 Then
TextBox5.Text = "No errors!"
Else
TextBox5.Text = errors & " error occured."
End If
If errors >= 1 Then
Button2.Enabled = True
Else
Button2.Enabled = False
End If
Loop
The passwords are stored line by line in a .txt file, so basically I want the program to go over each entry one by one and see if it matches what the user entered. If I am doing something wrong, please inform me, I'd love to get this script working.
Assuming that the heading of your question is correct, your variables in your code are named incorrectly - This isn't vitally important, but it will confuse whoever comes back in 6 months to maintain the software. Also, when your code is running correctly, as all the usernames will be unique, there is no need to return the number of errors.
It is longer than your original code, but the TextExists function can be used to open the file of your choosing such as the password file and the username file - Though your usernames and password in this situation are better stored in the one file.
'Opens the file and if it contains the input text, returns True. Otherwise returns false
Private Function TextExists(filename As String, inputText As String) As Boolean
Dim z As StreamReader = File.OpenText(filename)
Dim fileText As String
Dim msgPrompt As String = ""
Do Until z.EndOfStream() = True
fileText = CStr(z.ReadLine())
If inputText = fileText Then
Return True
End If
Loop
Return False
End Function
Private Sub CheckUserName()
If TextExists(a, TextBox1.Text) Then
MessageBox.Show("Username Already Exists")
Button2.Enabled = False
Else
Button2.Enabled = True
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
CheckUserName()
End Sub
For serious storage of passwords the username and passwords should be encrypted before they are saved of course, and decrypted when loaded. Saving sensitive information like this in plain text is always a very bad idea.

Why won't my code Loop?

Sorry for the messy code :S
If CheckBox2.Checked = True Then
For i As Integer = 0 To 1 Step 0
If CheckBox1.Checked = True Then
If TextBox1.Text = lblCLickLImit.Text Then
Timer1.Stop()
TextBox1.Text = "0"
System.Windows.Forms.SendKeys.Send("{F5}")
System.Threading.Thread.Sleep(delaydelaytime)
System.Windows.Forms.SendKeys.Send("{ENTER}")
Else
If CheckBox1.Checked = False Then
If TextBox1.Text = lblCLickLImit.Text Then
Timer1.Stop()
TextBox1.Text = "0"
End If
End If
End If
Else
If CheckBox2.Checked = False Then
If CheckBox1.Checked Then
If TextBox1.Text = lblCLickLImit.Text Then
Timer1.Stop()
TextBox1.Text = "0"
System.Windows.Forms.SendKeys.Send("{F5}")
System.Threading.Thread.Sleep(delaydelaytime)
System.Windows.Forms.SendKeys.Send("{ENTER}")
End If
Else
If CheckBox1.Checked = False Then
If TextBox1.Text = lblCLickLImit.Text Then
Timer1.Stop()
TextBox1.Text = "0"
End If
End If
End If
End If
End If
Next
Basically this code is for an Auto Clicker program,(Hopefully this will help you understand, http://prntscr.com/7tuc3o interface) Ok so when the "Continuous" checkbox is selected the code is in theory supposed to loop for infinity. However when I run the program with everything selected as shown all that happens is the program clicks once and then crashes (not responding). Any help I have tried this loop in other programs and it works, just not with this code.
Your loop is tying up the UI thread. You'll need to look into using either a background worker:
BackgroundWorker handles long-running tasks. It does not freeze the entire program as this task executes.
(dotnetperls.com)
Here is the msdn walkthrough of how to set-up a backgroundworker:
https://msdn.microsoft.com/en-us/library/ywkkz4s1.aspx
Or
If this is a personal project and no one you love will need to maintain this code, you can use Application.DoEvents() to continue to pump messages while the program is looping. Here is the msdn documentation for that https://msdn.microsoft.com/en-us/library/system.windows.forms.application.doevents(v=vs.110).aspx
First of all, a Step of 0 doesn't really make any sense in a for loop. It may /work/ but it is going to drive anyone reading it later insane. If you want an infinite loop don't use a for loop, use:
While True
'code here
End While
For loops are used when you know exactly how many iterations of your loop you need. A while loop is designed to iterate as long as some condition is true. In this example the condition is always true so it loops indefinitely.
Your code is also just going to spin the UI thread constantly. It never pauses for input (even your sleep calls do not release the thread for input). As far as the OS knows, your app has locked up because it never processes any of the window messages that get posted to it. It is still happily spinning away though, until windows finally gets tired of it and prompts you to kill it.
Not sure what other "programs" you're working with but I can tell you you don't want to use a For loop for this. You want a do/while loop, like either:
While True
...
End While
or
Do
...
Loop While True

Vb.net checkbox won't load from text file

I attempted to load a checkbox from a text file in VB.NET as a part of the settings form for my application. I used this piece of code:
Sub loadfiles()
Dim read As System.IO.StreamReader
read = My.Computer.FileSystem.OpenTextFileReader("C:\Users\Public\Documents\procrastinGONEnotif.txt")
Dim text As String = read.ReadToEnd()
read.Close()
If text = "false" Then
CheckBox1.Checked = False
Else
If text = "true" Then
CheckBox1.Checked = True
Else
MessageBox.Show("ERROR!")
End If
End If
End Sub
The file saving code is right here:
Dim write As System.IO.StreamWriter
write = My.Computer.FileSystem.OpenTextFileWriter("C:\Users\Public\Documents\procrastinGONEnotif.txt", False)
If CheckBox1.Checked = True Then
write.WriteLine("true")
Else
write.WriteLine("false")
End If
write.Close()
The file is supposed to load when the form starts and save when I press a button. However, the form does not load the file even though it is present and contains "true" or "false". Instead, the code detects it as "neither true or false" and sends the message "ERROR!", which I added to the application to test if it actually read the file.
The issue is when you read/write the value false. There is a newline character after false in the output file, which is visible when you open the text file or initially read it into text. An easy solution to this is to simply use read.ReadToEnd().Trim() to remove the extra whitespace characters.
You can also combine your nested If...Else into If...ElseIf...Else to make your code less confusing.
Sub loadfiles()
Dim read As System.IO.StreamReader
read = My.Computer.FileSystem.OpenTextFileReader("C:\Users\Public\Documents\procrastinGONEnotif.txt")
Dim text As String = read.ReadToEnd().Trim()
read.Close()
If text = "false" Then
CheckBox1.Checked = False
ElseIf text = "true" Then
CheckBox1.Checked = True
Else
MessageBox.Show("ERROR!")
End If
End Sub
You can shorten your entire code to this
For loading:
CheckBox1.Checked = Convert.ToBoolean(System.IO.File.ReadAllText("FILE_PATH"))
For saving
IO.File.WriteAllText("FILE_PATH", Convert.ToString(CheckBox1.Checked))