So I've finally got this to almost work but now every few times I test the process the form and the progressbar freeze. I'm also sure there are much more efficient ways of doing this so any constructive criticism would be greatly appreciated.
This is the coding for one page of a program that allows the user to click one button to download and install one application and then press the next button to download and install a different application:
Imports System.Net.WebRequestMethods
Public Class Software
'Open link in external browser
Public Sub HandleRequestNavigate(ByVal sender As Object, ByVal e As RequestNavigateEventArgs)
Process.Start(New ProcessStartInfo(e.Uri.AbsoluteUri))
e.Handled = True
End Sub
'Declarations
Shared progressamc As New Progress
Shared progresscti As New ProgressCTI
WithEvents startcti As New Process
WithEvents startamc As New Process
WithEvents startsfstb As New Process
WithEvents amcworker As New ComponentModel.BackgroundWorker
WithEvents ctiworker As New ComponentModel.BackgroundWorker
Dim ProgressBarAMC As Object = Progress.ProgressBar1
Dim blprgrsAMC As Object = Progress.blprgrs
Dim ProgressBarCTI As Object = progresscti.ProgressBar1
Dim blprgrsCTI As Object = progresscti.blprgrs
'FTP Values
Const host As String = "ftp://10.167.16.80/"
Const username As String = "anonymous"
Const password As String = ""
'AMC File Put/Get
Const localfileamc As String = "C:\AMC.exe"
Const Remotefileamc As String = "Bin/AMC.exe"
'CTI File Put/Get
Const localfilecti As String = "C:\CTI.exe"
Const Remotefilecti As String = "Bin/CTI.exe"
'On Init
Public Sub New()
InitializeComponent()
amcworker.WorkerReportsProgress = True
amcworker.WorkerSupportsCancellation = True
ctiworker.WorkerReportsProgress = True
ctiworker.WorkerSupportsCancellation = True
End Sub
'Install AMC Button
Private Sub ButtonAMC(sender As Object, e As RoutedEventArgs)
Dim butt1 As Button = DirectCast(sender, Button)
butt1.IsEnabled = False
Dispatcher.BeginInvoke(New Action(AddressOf progressamc_Show))
AddHandler Progress.Cancel_Click, AddressOf myProcessamc_Exited
amcworker.RunWorkerAsync()
End Sub
'Open Dialog
Private Sub progressamc_Show()
Try
progressamc.ShowDialog()
Catch ex As Exception
MessageBox.Show("An error has occurred during the process:" & vbCrLf & vbCrLf & ex.Message & vbCrLf & vbCrLf & "Please close the application and try again." _
& vbCrLf & "If you continue to encounter this error please Email")
End Try
End Sub
'FTP - Download
Private Sub ftpseshamc_DoWork(ByVal sender As System.Object, ByVal e As ComponentModel.DoWorkEventArgs) Handles amcworker.DoWork
Dim URI As String = host & Remotefileamc
Dim FTP As System.Net.FtpWebRequest = CType(System.Net.FtpWebRequest.Create(URI), System.Net.FtpWebRequest)
'Set the credentials
FTP.Credentials = New System.Net.NetworkCredential(username, password)
'FTP Options
FTP.KeepAlive = False
FTP.UseBinary = True
'Define the action as Download
FTP.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
'Get the response to the Ftp request and the associated stream
Try
Dim response As System.Net.FtpWebResponse = CType(FTP.GetResponse, System.Net.FtpWebResponse)
Dim Length As Long = response.ContentLength
Dim StopWatch As New Stopwatch
Dim CurrentSpeed As Double = Nothing
Using responseStream As IO.Stream = response.GetResponseStream
'loop to read & write to file
Using fs As New IO.FileStream(localfileamc, IO.FileMode.Create)
Dim buffer(2047) As Byte
Dim read As Integer = 0
Dim count As Integer
Do
If amcworker.CancellationPending = True Then
e.Cancel = True
Return
End If
StopWatch.Start()
amcworker.ReportProgress(CShort(count / Length * 100 + 0.5))
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
count += read
Loop Until read = 0
StopWatch.Stop()
responseStream.Close()
fs.Flush()
fs.Close()
End Using
responseStream.Close()
End Using
response.Close()
Catch ex As Exception
MessageBox.Show("An error has occurred during the process:" & vbCrLf & vbCrLf & ex.Message & vbCrLf & vbCrLf & "Please close the application and try again." _
& vbCrLf & "If you continue to encounter this error please Email")
myProcessamc_Exited()
End Try
Installamc()
End Sub
'Starts the installation
Sub Installamc()
startamc.StartInfo.FileName = "C:\AMC.exe"
startamc.EnableRaisingEvents = True
Try
startamc.Start()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Dispatcher.Invoke(New Action(AddressOf Progressamc_Hide))
End Sub
'Hide Dialog during install
Private Sub Progressamc_Hide()
progressamc.Hide()
End Sub
'Report progress
Private Sub amcworker_ProgressChanged(ByVal sender As System.Object, ByVal e As ComponentModel.ProgressChangedEventArgs) Handles amcworker.ProgressChanged
ProgressBarAMC.value = e.ProgressPercentage
blprgrsAMC.Content = "Downloading: " & e.ProgressPercentage & "%"
End Sub
End Class
Again, any help would be greatly appreciated.
Edit: I've made the following edit to the code but I'm not entirely sure it's doing what I think it's doing. Basically what I intended is for the ReportProgress to only run once every 2047 bytes read.
'Get the response to the Ftp request and the associated stream
Try
Dim response As System.Net.FtpWebResponse = CType(FTP.GetResponse, System.Net.FtpWebResponse)
Dim Length As Long = response.ContentLength
Dim StopWatch As New Stopwatch
Dim CurrentSpeed As Double = Nothing
Using responseStream As IO.Stream = response.GetResponseStream
'loop to read & write to file
Using fs As New IO.FileStream(localfileamc, IO.FileMode.Create)
Dim buffer(2047) As Byte
Dim read As Integer = 0
Dim count As Integer
Dim chunk As Integer = Int(2047 / Length)
Dim cycle As Integer = chunk = count
Do
If amcworker.CancellationPending = True Then
e.Cancel = True
Return
End If
StopWatch.Start()
If cycle = True Then
amcworker.ReportProgress(CShort(count / Length * 100 + 0.5))
Else
End
End If
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
count += read
Loop Until read = 0
StopWatch.Stop()
responseStream.Close()
fs.Flush()
fs.Close()
End Using
responseStream.Close()
End Using
response.Close()
Catch ex As Exception
MessageBox.Show("An error has occurred during the process:" & vbCrLf & vbCrLf & ex.Message & vbCrLf & vbCrLf & "Please close the application and try again." _
& vbCrLf & "If you continue to encounter this error please Email")
myProcessamc_Exited()
End Try
I didn't scrutinize the code carefully, but I don't see why you're using stopwatch, so I took out the references. I'm not sure what starting it multiple times inside the loop and ending it outside would do anyway.
The use of the word END in the second example will comletely end your app! Pretty sure that's what you want there.
Try this modification of your first code. The key is only updating if change is >= 5%:
Using fs As New IO.FileStream(localfileamc, IO.FileMode.Create)
Dim buffer(2047) As Byte
Dim read As Integer = 0
Dim count As Integer
dim LastPct as Short = -5
dim Pct as Short = 0
Do
If amcworker.CancellationPending = True Then
e.Cancel = True
Return
End If
Pct = CShort(count / Length * 100 + 0.5)
if Pct>= (LastPct + 5)
amcworker.ReportProgress(Pct)
LastPCT= Pct
EndIf
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
count += read
Loop Until read = 0
amcworker.ReportProgress(100)
responseStream.Close()
fs.Flush()
fs.Close()
End Using
Related
The code below works as intended in DEBUG with no errors. I input my search parameters, the record returns and populates all textboxes and loads the PDF file into the AxAcroPDF1 viewer.
However, after I compile and install the program I am receiving the error "Access to the path 'C:\Program Files (x86)\NAME OF PROGRAM\temp.file' is denied'
This only occurs when I search for a record and the PDF (in Binary format in the DB) to that record is supposed to load fails with the error message listed above. How can I resolve the permissions level (assuming this is the issue) to allow for the PDF to load? The area of concern presumably and more specifically is the LoadPDF() sub.
My code is as follows:
Imports System.Data.SqlClient
Public Class LoadDocs
Private DV As DataView
Private currentRow As String
Private Sub LoadDocs_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'DocDataset.Documents_Table' table. You can move, or remove it, as needed.
Documents_TableTableAdapter.Fill(DocDataset.Documents_Table)
'Loads last record on to form
DocumentsTableBindingSource.Position = DocDataset.Documents_Table.Rows.Count - 1
DV = New DataView(DocDataset.Documents_Table)
'LoadPDF()
End Sub
Private Sub BtnOpenPDF_Click(sender As Object, e As EventArgs) Handles btnOpenPDF.Click
tbRecNumb.Clear()
tbFileName.Clear()
tbPetsLoadNumber.Clear()
tbBrokerLoadNumber.Clear()
tbFilePath.Clear()
Dim CurYear As String = CType(Now.Year(), String)
On Error Resume Next
OpenFileDialog1.Filter = "PDF Files(*.pdf)|*.pdf"
OpenFileDialog1.ShowDialog()
AxAcroPDF1.src = OpenFileDialog1.FileName
tbFilePath.Text = OpenFileDialog1.FileName
Dim filename As String = tbFilePath.Text.ToString
tbFileName.Text = filename.Substring(Math.Max(0, filename.Length - 18))
Dim loadnumber As String = tbFileName.Text
tbPetsLoadNumber.Text = loadnumber.Substring(7, 7)
End Sub
' Search for PETS Load Number, Broker Load Numberthen load record if found
Private Sub BtnSearchBtn_MouseEnter(sender As Object, e As EventArgs) Handles btnSearch.MouseEnter
Cursor = Cursors.Hand
btnSearch.BackgroundImage = My.Resources.ButtonDwn_Teal_Trans
End Sub
Private Sub BtnSearchBtn_MouseLeave(sender As Object, e As EventArgs) Handles btnSearch.MouseLeave
Cursor = Cursors.Default
btnSearch.BackgroundImage = My.Resources.Button_Teal_Trans
End Sub
Private Sub TbSearchInput_KeyDown(sender As Object, e As KeyEventArgs) Handles tbSearchInput.KeyDown
Cursor = Cursors.Hand
If e.KeyCode = Keys.Enter Then
Search()
End If
End Sub
Private Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
btnSearch.BackgroundImage = My.Resources.ButtonClk_Teal_Trans
Cursor = Cursors.Hand
Search()
End Sub
Private Sub Search()
Cursor = Cursors.WaitCursor
If cbColName.Text = "SEARCH BY:" Then
MeMsgBoxSearchCriteria.ShowDialog()
Else : lblSearchResults.Items.Clear()
Select Case DocDataset.Documents_Table.Columns(cbColName.Text).DataType
Case GetType(Integer)
DV.RowFilter = cbColName.Text & " = " & tbSearchInput.Text.Trim
Case GetType(Date)
DV.RowFilter = cbColName.Text & " = #" & tbSearchInput.Text.Trim & "#"
Case Else
DV.RowFilter = cbColName.Text & " LIKE '*" & tbSearchInput.Text.Trim & "*'"
End Select
If DV.Count > 0 Then
For IX As Integer = 0 To DV.Count - 1
lblSearchResults.Items.Add(DV.Item(IX)("PETS_LOAD_NUMBER"))
Next
If DV.Count = 1 Then
lblSearchResults.SelectedIndex = 0
Dim ix As Integer = DocumentsTableBindingSource.Find("PETS_LOAD_NUMBER", CInt(lblSearchResults.SelectedItem.ToString))
DocumentsTableBindingSource.Position = ix
LoadPDF()
Else
lblSearchResults.Visible = True
lblSearchResults.BringToFront()
End If
Else
' Display a message box notifying users the record cannot be found.
MeMsgBoxNoSearch.ShowDialog()
End If
End If
Cursor = Cursors.Default
End Sub
Private Sub LblSearchResults_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lblSearchResults.SelectedIndexChanged
Dim ix As Integer = DocumentsTableBindingSource.Find("PETS_LOAD_NUMBER", CInt(lblSearchResults.SelectedItem.ToString))
DocumentsTableBindingSource.Position = ix
lblSearchResults.Visible = False
End Sub
Private Sub LoadPDF()
Dim temp = Environment.GetEnvironmentVariable("TEMP", EnvironmentVariableTarget.User)
If File.Exists(Application.StartupPath() & "\temp.file") = True Then
AxAcroPDF1.src = "blank.pdf"
My.Computer.FileSystem.DeleteFile(Application.StartupPath() & "\temp.file")
End If
Dim cmd As New SqlCommand
cmd.CommandText = "SELECT DOCUMENTS FROM Documents_Table WHERE PETS_LOAD_NUMBER = #pl"
cmd.Parameters.AddWithValue("#pl", tbPetsLoadNumber.Text)
cmd.CommandType = CommandType.Text
cmd.Connection = New SqlConnection With {
.ConnectionString = My.MySettings.Default.PETS_DatabaseConnectionString
}
Dim Buffer As Byte()
cmd.Connection.Open()
Buffer = cmd.ExecuteScalar
cmd.Connection.Close()
File.WriteAllBytes(Application.StartupPath() & "\temp.file", Buffer)
'DATA READER
AxAcroPDF1.src = Application.StartupPath() & "\temp.file"
End Sub
Private Sub DocumentsTableBindingSource_PositionChanged(sender As Object, e As EventArgs) Handles DocumentsTableBindingSource.PositionChanged
Try
currentRow = DocDataset.Documents_Table.Item(DocumentsTableBindingSource.Position).ToString
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub BtnSavePDF_Click(sender As Object, e As EventArgs) Handles btnSavePDF.Click
If tbPetsLoadNumber.Text.Length = 0 Then
MessageBox.Show("Please enter a PETS Load Number", "Missing Load Number", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
ElseIf tbBrokerLoadNumber.Text.Length = 0 Then
MessageBox.Show("Please enter a Broker Load Number", "Missing Load Number", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
ElseIf tbFileName.Text.Length = 0 Then
MessageBox.Show("Please enter a Filename", "Missing Filename", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Exit Sub
End If
Try
Using OpenFileDialog As OpenFileDialog = OpenFileDialog1()
If (OpenFileDialog.ShowDialog(Me) = DialogResult.OK) Then
tbFilePath.Text = OpenFileDialog.FileName
Else 'Cancel
Exit Sub
End If
End Using
'Call Upload Images Or File
Dim sFileToUpload As String = ""
sFileToUpload = LTrim(RTrim(tbFilePath.Text))
'Initialize byte array with a null value initially.
Dim data As Byte() = Nothing
'Use FileInfo object to get file size.
Dim fInfo As New FileInfo(tbFilePath.Text)
Dim numBytes As Long = fInfo.Length
'Open FileStream to read file
Dim fStream As New FileStream(tbFilePath.Text, FileMode.Open, FileAccess.Read)
'Use BinaryReader to read file stream into byte array.
Dim br As New BinaryReader(fStream)
'Supply number of bytes to read from file.
'In this case we want to read entire file. So supplying total number of bytes.
data = br.ReadBytes(CInt(numBytes))
'Insert the details into the database
Dim cmd As New SqlCommand
cmd.CommandText = "INSERT INTO Documents_Table (BROKER_LOAD_NUMBER, PDF_FILENAME, PETS_LOAD_NUMBER, DOCUMENTS)
VALUES (#bl, #fn, #pl, #pdf)"
cmd.Parameters.Add("#fn", SqlDbType.NVarChar, 50).Value = tbFileName.Text
cmd.Parameters.Add("#pl", SqlDbType.Int).Value = tbPetsLoadNumber.Text
cmd.Parameters.Add("#bl", SqlDbType.NVarChar, 20).Value = tbBrokerLoadNumber.Text
cmd.Parameters.Add("#pdf", SqlDbType.VarBinary, -1).Value = data
cmd.CommandType = CommandType.Text
cmd.Connection = New SqlConnection With {
.ConnectionString = My.MySettings.Default.PETS_DatabaseConnectionString
}
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
MsgBox("File Successfully Imported to Database")
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
End Class
In your function LoadPDF you create a reference to tempdir and then don't use it. Instead, you use Application.StartupPath() which will point to C:\Programs(x86) and is usually not writeable without admin rights.
But why don't you use your temp dir:
Dim temp = SpecialDirectories.Temp 'more robust approach to get tempdir
If File.Exists(temp & "\temp.file") = True Then
AxAcroPDF1.src = "blank.pdf"
My.Computer.FileSystem.DeleteFile(temp & "\temp.file")
End If
...
File.WriteAllBytes(temp & "\temp.file", Buffer)
'DATA READER
AxAcroPDF1.src = temp & "\temp.file"
I am writing an application which checks the computer for viruses from a specific path(including system paths, such as the Windows directory, Program Files, Application Data, etc)
The user will click a button "Start scan", will begin checking of system files(including Windows/ProgramFiles directories) for viruses, comparing files to MD5 hashes from a text files named "viruslist.txt"
However, I am having some issues with UnauthorizedAccessException errors. The application will stop when it detects a file which cannot be accessed.
I want the application to skip the denied files and move on to the next file in the specific path.
My code is as it follows:
Backgroundworker Do Work code:
Try
For Each file As String In IO.Directory.EnumerateFiles(FolderBrowserDialog3.SelectedPath, IO.SearchOption.AllDirectories).Union(IO.Directory.EnumerateFiles(FolderBrowserDialog4.SelectedPath, "*", IO.SearchOption.AllDirectories))
Try
Dim scanbox As New TextBox
Dim read As String = My.Computer.FileSystem.ReadAllText(System.AppDomain.CurrentDomain.BaseDirectory & "viruslist.txt")
scanbox.Text = read.ToString
Dim md5 As MD5CryptoServiceProvider = New MD5CryptoServiceProvider
Dim f As FileStream = New FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)
f = New FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)
md5.ComputeHash(f)
Dim hash As Byte() = md5.Hash
Dim buff As StringBuilder = New StringBuilder
Dim hashByte As Byte
For Each hashByte In hash
buff.Append(String.Format("{0:X2}", hashByte))
Next
If scanbox.Text.Contains(buff.ToString) Then
AddListItem2(ListBox2, "" & file & "")
End If
Catch ex As Exception
End Try
' SetLabelText_ThreadSafe(Me.Label1, "" & file & "")
If (BackgroundWorker1.CancellationPending = True) Then
e.Cancel = True
Exit For
End If
SetLabelText_ThreadSafe(Me.Labelscannedfiles, file & "")
int = int + 1
SetLabelText_ThreadSafe(Me.Label2, int & " Out Of " & filecount & "")
Dim pct As Integer = (int / filecount * 100)
BackgroundWorker1.ReportProgress(pct)
Next file
Catch ex as unauthorizedaccessexception
Also, the button code(start scan):
FolderBrowserDialog3.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.Windows)
Try
For Each strDir As String In
System.IO.Directory.GetDirectories(FolderBrowserDialog3.SelectedPath)
For Each strFile As String In System.IO.Directory.GetFiles(strDir)
Next
Next
Catch ex As Exception
Listbox2- used to display detected infected objects.
I've tried the following:
Changing the app's manifest to "requireAdministrator" and "highestavailable" ;
Disabling UAC .
Nothing worked so far!
UPDATE
Thanks to JQSOFT for providing the solution to my issue. The below solution will surely help a lot of people who have the same issue I had. This question has been solved.
Here's some points.
'Set this to True in the Cancel button...
Private cancel As Boolean
Sub New()
InitializeComponent()
'...
BackgroundWorker1.WorkerReportsProgress = True
BackgroundWorker1.WorkerSupportsCancellation = True
End Sub
Use this iterator function to get the authorized files and folders:
Private Iterator Function IterateFolders(startDir As String,
includeFiles As Boolean,
includeSubDir As Boolean) As IEnumerable(Of String)
Try
For Each dirName In Directory.EnumerateDirectories(startDir)
Yield dirName
Try
If includeFiles Then
For Each fileName In Directory.EnumerateFiles(startDir)
Yield fileName
Next
End If
If includeSubDir Then
For Each subDir In IterateFolders(dirName, includeFiles, includeSubDir)
Yield subDir
Next
End If
Catch ex As UnauthorizedAccessException
Catch ex As Exception
End Try
Next
Catch ex As UnauthorizedAccessException
Catch ex As Exception
End Try
End Function
The start scan button
Private Sub Scan_Click(sender As Object, e As EventArgs) Handles Scan.Click
If BackgroundWorker1.IsBusy Then Return
Using fbd As New FolderBrowserDialog
If fbd.ShowDialog = DialogResult.OK Then
cancel = False
'...
BackgroundWorker1.RunWorkerAsync(fbd.SelectedPath)
End If
End Using
End Sub
The BackgroundWorker events:
Private Sub BackgroundWorker1_DoWork(sender As Object,
e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim dir = e.Argument.ToString
For Each file In IterateFolders(dir, True, True).
Where(Function(f) IO.File.Exists(f)) '<- To get the files only.
If cancel Then
e.Cancel = True
Return
End If
Try
Dim b As Boolean = False
Using md5 As New MD5CryptoServiceProvider,
f As FileStream = New FileStream(file,
FileMode.Open,
FileAccess.Read,
FileShare.Read, 8192)
md5.ComputeHash(f)
Dim hash As Byte() = md5.Hash
Dim buff As New StringBuilder
Dim hashByte As Byte
For Each hashByte In hash
buff.Append(String.Format("{0:X2}", hashByte))
Next
b = IO.File.ReadLines("...FullPathOf\viruslist.txt").
Any(Function(x) x = buff.ToString)
End Using
'The main thread...
Invoke(New Action(Sub()
If b Then ListBox2.Items.Add(file)
Labelscannedfiles.Text = ....
Label2.Text = $"{int} Out of {filecount}"
End Sub))
'Code to update the progress here...
Catch ex As IOException
Catch ex As Exception
End Try
Next
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object,
e As ProgressChangedEventArgs) _
Handles BackgroundWorker1.ProgressChanged
'Update the progress...
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object,
e As RunWorkerCompletedEventArgs) _
Handles BackgroundWorker1.RunWorkerCompleted
If e.Error IsNot Nothing Then
'An error occurred
ElseIf e.Cancelled Then
'Operation canceled...
Else
'On success ....
End If
End Sub
So I have a big web browser project and everything seems to be working just fine.
I have a feature which allows the user to get news about my website when they click a specific button.
The way this is supposed to work is it is going to read text out of a txt file in my dropbox and then display that text in a richtextbox in my application.
The way I did is that I simply uploaded a txt file into my Dropbox folder and gave it a name which never changes so as to work with my code , and then I copied the share link of this file and put it inside my code.
Now whenever I want to update my news , all I have to do is to just edit the txt file in my Dropbox folder , keeping the same file name so the link stays the same and doesn't change thus allowing my application to correctly update the news.
I tested this on my Laptop (which I do all the programming on) and it worked great. I tested this on my old desktop PC and it worked great. I had some friends from different countries around the world test this and this where the problem happens ... it worked great for some of them and for the others it failed and gave an error ... (Hostname couldn't be resolved)
Not only this makes the news function in my application not useable , but it also makes the auto update function i have not useable as well because it also uses the same method.
Now let's jump into the code and please help find out what the problem is ...
The following are the main code that works on downloading a file from Dropbox:
Private Sub Download_Dropbox(URL As String, FileName As String)
Dim Data() = HTTP_Get(URL)
File.WriteAllBytes(FileName, Data)
End Sub
Private Function HTTP_Get(Page As String) As Byte()
Dim Request As HttpWebRequest = WebRequest.Create(Page)
Request.Method = "GET"
Request.KeepAlive = True
Request.ContentType = "application/x-www-form-urlencoded"
Request.UserAgent = "Mozilla/5.0 (Windows NT 6.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36"
Request.AllowAutoRedirect = True
Dim Response As HttpWebResponse = Request.GetResponse()
Dim Data As Stream = Response.GetResponseStream()
Dim Bytes() As Byte
Using Writer As New MemoryStream
Dim Buffer(&HFFF) As Byte
Do
Dim BytesRead As Long = Data.Read(Buffer, 0, Buffer.Length)
If BytesRead > 0 Then Writer.Write(Buffer, 0, BytesRead) Else Exit Do
Loop
Bytes = Writer.ToArray()
End Using
Return Bytes
End Function
and this is the code for the button that tries to update the news (reads a txt file):
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Form1.IsConnectionAvailable = True Then
Try
'Download_Dropbox("https://www.dropbox.com/s/8m2apm0x0rh91e0/orbitnews.txt?dl=1", CurDir & "\orbitnews.txt")
Dim ABC As String
Dim myWebClient As New System.Net.WebClient
Dim file As New System.IO.StreamReader(myWebClient.OpenRead("https://www.dropbox.com/s/8m2apm0x0rh91e0/orbitnews.txt?dl=1"))
ABC = file.ReadToEnd
file.Close()
newsshower.Text = ABC
My.Settings.oldnews = ABC
dater.Text = (DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"))
My.Settings.newsrefdate = dater.Text
My.Settings.Save()
Timer1.Enabled = True
Label2.Visible = True
If newsshower.Text.Contains("Click the button below to update your browser now!") Then
If newsshower.Text.Contains(Application.ProductVersion) Then
My.Settings.newsupdate = False
updatetoggler.Visible = False
Else
updatetoggler.Visible = True
My.Settings.newsupdate = True
My.Settings.Save()
End If
End If
Catch ex As Exception
MsgBox("An error has occured while refreshing news." & vbCrLf & "Please contact customer support and send them the following:" & vbCrLf & ex.ToString & vbCrLf & vbCrLf & "Customer Support E-mail:" & vbCrLf & "omaradoinc#hotmail.com")
End Try
Else
MsgBox("You aren't connected to the internet." & vbCrLf & "Please connect to the internet to be able to refresh the news.")
End If
End Sub
and this is the code that downloads files from Dropbox (which shouls happen when the programs works on updating itself):
Public Sub mainupdate()
Download_Dropbox("https://www.dropbox.com/s/eomar7a70hokm0l/Orbit.exe?dl=1", CurDir & "\Orbit.exe")
Download_Dropbox("https://www.dropbox.com/s/ij1qceoe5kr6tmp/Orbit.exe.config?dl=1", CurDir & "\Orbit.exe.config")
Download_Dropbox("https://www.dropbox.com/s/em4mo4lsoswba4p/Orbit.pdb?dl=1", CurDir & "\Orbit.pdb")
Download_Dropbox("https://www.dropbox.com/s/g0361qpzvq74ge4/Orbit.vshost.exe?dl=1", CurDir & "\Orbit.vshost.exe")
Download_Dropbox("https://www.dropbox.com/s/o5bbkn72cbs9bo7/Orbit.vshost.exe.config?dl=1", CurDir & "\Orbit.vshost.exe.config")
Download_Dropbox("https://www.dropbox.com/s/wzsyzjczibwa9sz/Orbit.xml?dl=1", CurDir & "\Orbit.xml")
Download_Dropbox("https://www.dropbox.com/s/l0ogz6kxrn951zv/OWBV.txt?dl=1", CurDir & "\OWBV.txt")
End Sub
Public Sub othersupdate()
Download_Dropbox("https://www.dropbox.com/s/lyv0kdmpi85rbdp/libzplay.dll?dl=1", CurDir & "\libzplay.dll")
End Sub
Public Sub soundsupdate()
Download_Dropbox("https://www.dropbox.com/s/hfl1vidanwecad4/not.wav?dl=1", CurDir & "\not.wav")
Download_Dropbox("https://www.dropbox.com/s/cfroifknr8zmnub/pokked.wav?dl=1", CurDir & "\pokked.wav")
Download_Dropbox("https://www.dropbox.com/s/c73af0a30hxg7gp/screenshotsound.wav?dl=1", CurDir & "\screenshotsound.wav")
Download_Dropbox("https://www.dropbox.com/s/ps5ztudy9cwvwnl/timerend.wav?dl=1", CurDir & "\timerend.wav")
End Sub
Private Sub Download_Dropbox(URL As String, FileName As String)
Dim Data() = HTTP_Get(URL)
File.WriteAllBytes(FileName, Data)
End Sub
and this is the code for IsConnectionAvailable() in Form1 :
Public Function IsConnectionAvailable() As Boolean
Dim objUrl As New System.Uri("http://www.google.com")
Dim objWebReq As System.Net.WebRequest
objWebReq = System.Net.WebRequest.Create(objUrl)
Dim objresp As System.Net.WebResponse
Try
objresp = objWebReq.GetResponse
objresp.Close()
objresp = Nothing
Return True
Catch ex As Exception
objresp = Nothing
objWebReq = Nothing
Return False
End Try
End Function
and this is the whole code for my update client which completely failes to download any files from Dropbox or read text:
Option Explicit On
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Public Class Form1
Dim Listener As New TcpListener(8000)
Dim Client As TcpClient
Dim CurDir As String = My.Application.Info.DirectoryPath
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
updatecheck()
End Sub
Private Sub helper_Click(sender As Object, e As EventArgs) Handles helper.Click
helpform.Show()
End Sub
Public Sub mainupdate()
Download_Dropbox("https://www.dropbox.com/s/eomar7a70hokm0l/Orbit.exe?dl=1", CurDir & "\Orbit.exe")
Download_Dropbox("https://www.dropbox.com/s/ij1qceoe5kr6tmp/Orbit.exe.config?dl=1", CurDir & "\Orbit.exe.config")
Download_Dropbox("https://www.dropbox.com/s/em4mo4lsoswba4p/Orbit.pdb?dl=1", CurDir & "\Orbit.pdb")
Download_Dropbox("https://www.dropbox.com/s/g0361qpzvq74ge4/Orbit.vshost.exe?dl=1", CurDir & "\Orbit.vshost.exe")
Download_Dropbox("https://www.dropbox.com/s/o5bbkn72cbs9bo7/Orbit.vshost.exe.config?dl=1", CurDir & "\Orbit.vshost.exe.config")
Download_Dropbox("https://www.dropbox.com/s/wzsyzjczibwa9sz/Orbit.xml?dl=1", CurDir & "\Orbit.xml")
Download_Dropbox("https://www.dropbox.com/s/l0ogz6kxrn951zv/OWBV.txt?dl=1", CurDir & "\OWBV.txt")
End Sub
Public Sub othersupdate()
Download_Dropbox("https://www.dropbox.com/s/lyv0kdmpi85rbdp/libzplay.dll?dl=1", CurDir & "\libzplay.dll")
End Sub
Public Sub soundsupdate()
Download_Dropbox("https://www.dropbox.com/s/hfl1vidanwecad4/not.wav?dl=1", CurDir & "\not.wav")
Download_Dropbox("https://www.dropbox.com/s/cfroifknr8zmnub/pokked.wav?dl=1", CurDir & "\pokked.wav")
Download_Dropbox("https://www.dropbox.com/s/c73af0a30hxg7gp/screenshotsound.wav?dl=1", CurDir & "\screenshotsound.wav")
Download_Dropbox("https://www.dropbox.com/s/ps5ztudy9cwvwnl/timerend.wav?dl=1", CurDir & "\timerend.wav")
End Sub
Private Sub Download_Dropbox(URL As String, FileName As String)
Dim Data() = HTTP_Get(URL)
File.WriteAllBytes(FileName, Data)
End Sub
Private Function HTTP_Get(Page As String) As Byte()
Dim Request As HttpWebRequest = WebRequest.Create(Page)
Request.Method = "GET"
Request.KeepAlive = True
Request.ContentType = "application/x-www-form-urlencoded"
Request.UserAgent = "Mozilla/5.0 (Windows NT 6.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36"
Request.AllowAutoRedirect = True
Dim Response As HttpWebResponse = Request.GetResponse()
Dim Data As Stream = Response.GetResponseStream()
Dim Bytes() As Byte
Using Writer As New MemoryStream
Dim Buffer(&HFFF) As Byte
Do
Dim BytesRead As Long = Data.Read(Buffer, 0, Buffer.Length)
If BytesRead > 0 Then Writer.Write(Buffer, 0, BytesRead) Else Exit Do
Loop
Bytes = Writer.ToArray()
End Using
Return Bytes
End Function
Public Function IsConnectionAvailable() As Boolean
Dim objUrl As New System.Uri("http://www.google.com")
Dim objWebReq As System.Net.WebRequest
objWebReq = System.Net.WebRequest.Create(objUrl)
Dim objresp As System.Net.WebResponse
Try
objresp = objWebReq.GetResponse
objresp.Close()
objresp = Nothing
Return True
Catch ex As Exception
objresp = Nothing
objWebReq = Nothing
Return False
End Try
End Function
Public Sub updatecheck()
Try
If IsConnectionAvailable() = True Then
Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("http://pastebin.com/wCt79dEc")
Dim response As System.Net.HttpWebResponse = request.GetResponse()
Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())
Dim newestversion As String = sr.ReadToEnd()
Dim fileContents As String
Try
fileContents = My.Computer.FileSystem.ReadAllText(CurDir & "\OWBV.txt")
If newestversion.Contains(fileContents) Then
updater.Enabled = False
Else
End If
Catch ex As Exception
MsgBox("Orbit version file not found. Update button disabled." & "You can do one of the following 2 methods to fix this error. (Administrator rights might be required)" & vbCrLf & "1- Please open Orbit and then head to (Settings) , then check the option (Enable Console) and save changes. " & vbCrLf & "2- Open (File) Menu and launch (Browser Console)" & vbCrLf & "3- Type in the following command without the brackets: ( /vfcreate ) and then press Enter on your keyboard." & vbCrLf & "If the process is successful , then please launch the update client again either through Orbit itself or close Orbit and launch it manually by running (OWBUpdater.exe) in the application directory. " & vbCrLf & "If the process isn't successful , then please contact customer support at: omaradoinc#hotmail.com" & vbCrLf & "The other method to fix this error is:" & vbCrLf & "1- Navigate to Orbit Installation directory/folder." & vbCrLf & "2-Create a notepad (.txt file) and name that file the following name without the brackets: (OWBV)" & vbCrLf & "3- Open the file and type Orbit's old version that you have or as instructed by customer support , save the changes." & vbCrLf & "If you fail to fix this error , please contact customer support at:" & vbCrLf & "omaradoinc#hotmail.com")
updater.Enabled = False
End Try
Else
updater.Enabled = False
repairer.Enabled = False
intnot.Visible = True
Me.Text = "Orbit Web Browser Update Client (No Internet connection)"
End If
Catch ex As Exception
MsgBox("An Error Has Occured While Checking For Updates..." & vbCrLf & "This May Happen Because Of a Load On The Server" & vbCrLf & "Please Try Again Later" & vbCrLf & "If The Problems Still Exists Then Please Report This To:" & vbCrLf & "omaradoinc#hotmail.com")
End Try
End Sub
Private Sub updater_Click(sender As Object, e As EventArgs) Handles updater.Click
Try
m1.Visible = False
m2.Visible = False
progressor.Visible = True
Me.Enabled = False
mainupdate()
Process.Start(CurDir & "\Orbit.exe")
MsgBox("Orbit was successfully updated to the latest version.")
Me.Close()
Catch ex As Exception
m1.Visible = True
m2.Visible = True
progressor.Visible = False
Me.Enabled = True
My.Computer.FileSystem.WriteAllText(CurDir & "\errorlog.txt", ex.ToString, True)
MsgBox("Update failed." & vbCrLf & "A log file was created in the application directory , Please send it to customer support at:" & vbCrLf & "omaradoinc#hotmail.com")
End Try
End Sub
Private Sub repairer_Click(sender As Object, e As EventArgs) Handles repairer.Click
Try
m1.Visible = False
m2.Visible = False
progressor.Visible = True
Me.Enabled = False
othersupdate()
soundsupdate()
Process.Start(CurDir & "\Orbit.exe")
MsgBox("Orbit was successfully repaired.")
Me.Close()
Catch ex As Exception
m1.Visible = True
m2.Visible = True
progressor.Visible = False
Me.Enabled = True
My.Computer.FileSystem.WriteAllText(CurDir & "\errorlog.txt", ex.ToString, True)
MsgBox("Repair failed." & vbCrLf & "A log file was created in the application directory , Please send it to customer support at:" & vbCrLf & "omaradoinc#hotmail.com")
End Try
End Sub
Private Sub remover_Click(sender As Object, e As EventArgs) Handles remover.Click
Try
Listener.Start()
m1.Visible = False
m2.Visible = False
progressor.Visible = True
My.Computer.FileSystem.WriteAllText(CurDir & "\uninstcmd.txt", "cmd:/send\performfactoryreset", True)
Timer1.Enabled = True
Timer1.Start()
Process.Start(CurDir & "\Orbit.exe")
updater.Enabled = False
repairer.Enabled = False
remover.Enabled = False
Catch ex As Exception
Listener.Stop()
Timer1.Stop()
Timer1.Enabled = False
m1.Visible = True
m2.Visible = True
progressor.Visible = False
MsgBox("Orbit.exe wasn't found." & vbCrLf & "Unable to complete uninstallation.")
End Try
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim Message As String
Dim nStart As Integer
Dim nLast As Integer
If Listener.Pending = True Then
Message = ""
Client = Listener.AcceptTcpClient
Dim Reader As New StreamReader(Client.GetStream())
While Reader.Peek > -1
Message &= Convert.ToChar(Reader.Read()).ToString
End While
If Message.Contains("</>") Then
nStart = InStr(Message, "</>") + 4
nLast = InStr(Message, "<\>")
Message = Mid(Message, nStart, nLast - nStart)
End If
If Message.Contains("cmd:/send\completedfactoryreset") Then
Try
My.Computer.FileSystem.WriteAllText(CurDir & "\uninstcmd.txt", "Nothing here.", True)
MsgBox("Orbit settings have been successfully cleaned." & vbCrLf & "Thanks for using Orbit , This client will now exit and launch the main uninstaller which will completely remove Orbit from your PC." & vbCrLf & "For customer support , Contact: omaradoinc#hotmail.com")
Process.Start(CurDir & "\Uninstal.exe")
Me.Close()
Catch ex As Exception
MsgBox("Orbit settings have been successfully cleaned." & vbCrLf & "Thanks for using Orbit , This client will now exit and launch the main uninstaller which will completely remove Orbit from your PC." & vbCrLf & "For customer support , Contact: omaradoinc#hotmail.com")
Process.Start(CurDir & "\Uninstal.exe")
Me.Close()
End Try
End If
End If
End Sub
End Class
For now I can't remember the line where the error was but i will try to get my friends to retest and get the exact error as i have setup my application with lots of Try Catch blocks and easy ways to grab the errors in txt files and send them to me so it shouldn't be much of a hassle before i can get the full error.
For now is there anything that seems out of space or could be improved to work better?
This is the first time that I have ever worked with networking in a program control webrelay. I was able to write my program with success... or so I thought. A couple of days ago I had a device drop off the network and my program "locked up". I know it did not truly lock up. I did some debugging and found out that what is happening is that when the tcpclient throws an exception, it just stops running any code after it. This causes my program to stop updating because of a timer that is never restarted and I con't control analog Outputs.
Public Class ControlPanelX317
Private SQL As New SQLControl
Private Sub ControlPanelX317_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LoadControlsX317()
End Sub
'Dislay Conrol
'__________________________________________________________________________________________________________________________________________________________________________
Private Sub LoadControlsX317()
Dim loadqry As String = "SELECT * FROM controlsX317 WHERE controlsX317.ValueVoltageID = '" & 1 & "' "
Dim SQLCmd As New SqlCommand(loadqry, Sql.SQLCon)
If Sql.SQLCon.State = ConnectionState.Closed Then Sql.SQLCon.Open()
Dim reader As SqlDataReader = SQLCmd.ExecuteReader
While reader.Read = True
txt_S1_VolueVoltage.Text = reader("S1VolueVoltage")
txt_S2_VolueVoltage.Text = reader("S2VolueVoltage")
txt_S3_VolueVoltage.Text = reader("S3VolueVoltage")
txt_S4_VolueVoltage.Text = reader("S4VolueVoltage")
End While
SQLCmd.Dispose()
reader.Close()
Sql.SQLCon.Close()
End Sub
Private Sub btn_Save_ValueVoltage_Click(sender As Object, e As EventArgs) Handles btn_Save_ValueVoltage.Click
If txt_S1_VolueVoltage.Text > 10 Then
MsgBox("Max Voltage is 10V")
txt_S1_VolueVoltage.Clear()
Exit Sub
End If
If txt_S2_VolueVoltage.Text > 10 Then
MsgBox("Max Voltage is 10V")
txt_S2_VolueVoltage.Clear()
Exit Sub
End If
If txt_S3_VolueVoltage.Text > 10 Then
MsgBox("Max Voltage is 10V")
txt_S3_VolueVoltage.Clear()
Exit Sub
End If
If txt_S4_VolueVoltage.Text > 10 Then
MsgBox("Max Voltage is 10V")
txt_S4_VolueVoltage.Clear()
Exit Sub
End If
If txt_S1_VolueVoltage.Text <> "" Then
Dim UpdateValueVoltage As String = "UPDATE controlsX317 SET S1VolueVoltage='" & txt_S1_VolueVoltage.Text & "', S2VolueVoltage='" & txt_S2_VolueVoltage.Text & "',
S3VolueVoltage='" & txt_S3_VolueVoltage.Text & "', S4VolueVoltage='" & txt_S4_VolueVoltage.Text & "'
WHERE ValueVoltageID ='" & 1 & "' "
If SQL.DataUpdate(UpdateValueVoltage) = 0 Then
MsgBox("The Sysytem could not be found!!! ")
Else
MsgBox("VolueVoltage successfully changed")
End If
Else
MsgBox("You must restart a Sysytem")
End If
End Sub
Private Sub btn_S1_SetVoltage_Click(sender As Object, e As EventArgs) Handles btn_S1_SetVoltage.Click
lbl_S1_AnalogOutput.Text = Val(txt_S1_VolueVoltage.Text) * Val(txt_S1_ControlViltage.Text / 100) & "V"
End Sub
Private Sub btn_S2_SetVoltage_Click(sender As Object, e As EventArgs) Handles btn_S2_SetVoltage.Click
lbl_S2_AnalogOutput.Text = Val(txt_S2_VolueVoltage.Text) * Val(txt_S2_ControlViltage.Text / 100) & "V"
End Sub
Private Sub btn_S3_SetVoltage_Click(sender As Object, e As EventArgs) Handles btn_S3_SetVoltage.Click
lbl_S3_AnalogOutput.Text = Val(txt_S3_VolueVoltage.Text) * Val(txt_S3_ControlViltage.Text / 100) & "V"
End Sub
Private Sub btn_S4_SetVoltage_Click(sender As Object, e As EventArgs) Handles btn_S4_SetVoltage.Click
lbl_S4_AnalogOutput.Text = Val(txt_S4_VolueVoltage.Text) * Val(txt_S4_ControlViltage.Text / 100) & "V"
End Sub
'End Display Control
'_________________________________________________________________________________________________________________________________________________________________________
'Conection to WebRelay X317
'_________________________________________________________________________________________________________________________________________________________________________
Public Sub getWebRelayState()
Dim tcpClient As New TcpClient()
Dim port As Integer
Try
port = Convert.ToInt32(txtPort.Text)
tcpClient.Connect(txt_IPAddress.Text, port)
If tcpClient.Connected Then
'Create a network stream object
Dim netStream As NetworkStream = tcpClient.GetStream()
'If we can read and write to the stream then do so
If netStream.CanWrite And netStream.CanRead Then
'Send the on command to webrelay
Dim sendBytes As Byte() = Encoding.ASCII.GetBytes("GET /state.xml?noReply=0 HTTP/1.1" & vbCrLf & "Authorization: Basic bm9uZTp3ZWJyZWxheQ==" & vbCrLf & vbCrLf)
netStream.Write(sendBytes, 0, sendBytes.Length)
'Get the response from webrelay
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
netStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
'Parse the response and update the webrelay state and input text boxes
Dim returndata As String = Encoding.ASCII.GetString(bytes)
'Parse out the relay state and input state
Dim array1 As Char() = returndata.ToCharArray()
Dim ana(4) As Integer
'Relay State found at index 66
If array1(66) = "1" Then
RelayState.Text = "ON"
Else
RelayState.Text = "OFF"
End If
'Input State found at index 94
If array1(94) = "1" Then
inputState.Text = "ON"
Else
inputState.Text = "OFF"
End If
End If
'Close the connection
tcpClient.Close()
End If
Catch ex As Exception
inputState.Text = "Error"
RelayState.Text = "Error"
'Disable the timer
TimerRelayRefresh.Enabled = False
End Try
End Sub
Private Sub sendRequest(ByVal val As String)
Dim tcpClient As New TcpClient()
Dim port As Integer
Try
'Disable the timer
TimerRelayRefresh.Enabled = False
port = Convert.ToInt32(txtPort.Text)
tcpClient.Connect(txt_IPAddress.Text, port)
If tcpClient.Connected Then
MsgBox("connection successful")
'Create a network stream object
Dim netStream As NetworkStream = tcpClient.GetStream()
'If we can read and write to the stream then do so
If netStream.CanWrite And netStream.CanRead Then
'Send the on command to webrelay
Dim sendBytes As Byte() = Encoding.ASCII.GetBytes("GET /state.xml?relayState=1 HTTP/1.1<CR><LF>" & vbCrLf & "Authorization: Basic bm9uZTp3ZWJyZWxheQ==<CR><LF><CR><LF>" & vbCrLf & vbCrLf)
netStream.Write(sendBytes, 0, sendBytes.Length)
'Get the response from webrelay
Dim bytes(tcpClient.ReceiveBufferSize) As Byte
netStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
'Parse the response and update the webrelay state and input text boxes
Dim returndata As String = Encoding.ASCII.GetString(bytes)
'Parse out the relay state and input state
Dim array1 As Char() = returndata.ToCharArray()
'Relay State found at index 66
If array1(66) = "1" Then
RelayState.Text = "ON"
Else
RelayState.Text = "OFF"
End If
'Input State found at index 94
If array1(94) = "1" Then
inputState.Text = "ON"
End If
Else
inputState.Text = "OFF"
End If
End If
'Enable the timer
TimerRelayRefresh.Enabled = True
Catch ex As Exception
inputState.Text = "Error"
RelayState.Text = "Error"
'Disable the timer
TimerRelayRefresh.Enabled = False
End Try
End Sub
Private Sub btn_ControlsX317_On_Click(sender As Object, e As EventArgs) Handles btn_ControlsX317_On.Click
sendRequest("1")
End Sub
Private Sub btn_ControlsX317_Off_Click(sender As Object, e As EventArgs) Handles btn_ControlsX317_Off.Click
sendRequest("0")
End Sub
Private Sub btn_ControlsX317_PULSE_Click(sender As Object, e As EventArgs) Handles btn_ControlsX317_PULSE.Click
sendRequest("2")
End Sub
'End Conetion
'_________________________________________________________________________________________________________________________________________________________________________
End Class
I have 2 projects, one which has a highscorelist stored on it, and one which tries to add highscores to that list and retrieve all items on the list. Trying to put items on the list works good, but retrieving the list doesn't work well. Here's the code:
Option Strict On
Option Explicit On
Imports System.Net.Sockets
Imports System.Threading
Public Class Main
Dim server As New TcpListener(45888)
Dim client As New TcpClient
Dim stream As NetworkStream
Dim connected As Boolean
Private Sub cmd_start_Click(sender As Object, e As EventArgs) Handles cmd_start.Click
server.Start()
cmd_start.Enabled = False
cmd_stop.Enabled = True
lbl_status.Text = "Running"
lbl_status.ForeColor = Color.Green
tmr.Start()
End Sub
Private Sub cmd_stop_Click(sender As Object, e As EventArgs) Handles cmd_stop.Click
server.Stop()
cmd_start.Enabled = True
cmd_stop.Enabled = False
lbl_status.Text = "Not running"
lbl_status.ForeColor = Color.Red
tmr.Stop()
End Sub
Private Sub Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
connected = False
CheckForIllegalCrossThreadCalls = False
End Sub
Dim x As Integer = 0
Private Sub tmr_Tick(sender As Object, e As EventArgs) Handles tmr.Tick
If server.Pending Then
client = server.AcceptTcpClient()
stream = client.GetStream()
tmr.Stop()
read()
Else
tmr.Start()
End If
lbl_mseconds.Text = "Relative time: " & x
x += 1
End Sub
Private Sub SendMessage(message As String)
Dim sendtext() As Byte = System.Text.Encoding.ASCII.GetBytes(message)
stream.Write(sendtext, 0, sendtext.Length)
stream.Flush()
End Sub
Private Sub read()
Dim rec(client.ReceiveBufferSize) As Byte
stream.Read(rec, 0, client.ReceiveBufferSize)
Dim rectext As String = System.Text.Encoding.ASCII.GetString(rec)
If rectext.Contains("#1#") Then
rectext = rectext.Substring(3)
If rectext.Split(CChar("-"))(0).Length = 2 Then rectext = "0" & rectext
If rectext.Split(CChar("-"))(0).Length = 1 Then rectext = "00" & rectext
listbox_highscores.Items.Add(rectext)
ElseIf rectext.Contains("#2#") Then
Dim tosend As String = listbox_highscores.Items(0).ToString
For i = 1 To listbox_highscores.Items.Count - 1
tosend &= "," & listbox_highscores.Items(i).ToString
Next
MsgBox(tosend)
SendMessage(tosend)
End If
tmr.Start()
End Sub
End Class
On the other project I have this:
Dim server As New TcpListener(45888)
Dim client As New TcpClient
Dim stream As NetworkStream
Friend Sub sendHighscore(name As String, score As Integer)
Try
client.Connect("192.168.1.127", 45888)
Catch ex As Exception
Exit Sub
End Try
stream = client.GetStream()
Dim sendtext() As Byte = Encoding.ASCII.GetBytes("#1#" & score & "-" & name)
stream.Write(sendtext, 0, sendtext.Length)
client = New TcpClient
End Sub
Friend Sub getHighscoreList()
ListBox_highscores.Items.Clear()
Try
client.Connect("192.168.1.127", 45888)
Catch ex As Exception
ListBox_highscores.Items.Add("Couldn't connect")
Exit Sub
End Try
stream = client.GetStream()
Dim sendtext() As Byte = Encoding.ASCII.GetBytes("#2#")
stream.Write(sendtext, 0, sendtext.Length)
client = New TcpClient
read()
End Sub
Private Sub read()
Dim rec(client.ReceiveBufferSize) As Byte
stream.Read(rec, 0, client.ReceiveBufferSize)
Dim rectext As String = Encoding.ASCII.GetString(rec)
Label2.Text = rectext
For Each item In rectext.Split(",")
ListBox_highscores.Items.Add(item)
Next
End Sub
Then when I use the sub sendHighscore() with a name and score, everything perfectly works and it shows in the other project on the list, but when I use the sub getHighscoreList() the list on the second project only contains the first item from the first list. Does someone has ideas?
Edit: Original answer removed entirely because it wasn't actually the problem (although it did offer improvements). My answer was nearly identical to this one anyway.
After analyzing this project much more closely, the problem with the For..Next loop not returning the expected results is because the strings are being sent back and forth as byte arrays in buffers much larger than necessary (client.ReceiveBufferSize). The actual "strings" received contain large amounts of non-printable characters (garbage) added to the end to fill the buffer. The quick and dirty solution is to remove all non-printable characters:
rectext = System.Text.RegularExpressions.Regex.Replace(rectext, _
"[^\u0020-\u007F]", String.Empty)
The whole Sub would read like this:
Private Sub read()
Dim rec(client.ReceiveBufferSize) As Byte
stream.Read(rec, 0, client.ReceiveBufferSize)
Dim rectext As String = System.Text.Encoding.ASCII.GetString(rec)
If rectext.Contains("#1#") Then
rectext = rectext.Substring(3)
If rectext.Split(CChar("-"))(0).Length = 2 Then rectext = "0" & rectext
If rectext.Split(CChar("-"))(0).Length = 1 Then rectext = "00" & rectext
rectext = System.Text.RegularExpressions.Regex.Replace(rectext, "[^\u0020-\u007F]", String.Empty)
listbox_highscores.Items.Add(rectext)
ElseIf rectext.Contains("#2#") Then
Dim tosend As String = listbox_highscores.Items(0).ToString
For i As Integer = 1 To (listbox_highscores.Items.Count - 1)
tosend &= "," & listbox_highscores.Items(i).ToString
Next
SendMessage(tosend)
End If
tmr.Start()
End Sub
Try this, your comma's are off as well...
Dim tosend As String = String.Empty
Dim intCount As Integer = 0
For i As Integer = 0 To listbox.Items.Count - 1
If intCount >= 1 Then
tosend &= "," & listbox.Items(i).ToString
Else
tosend &= listbox.Items(i).ToString
intCount += 1
End If
Next
MessageBox.Show(tosend)
Screenshot THAT IT WORKS!