I'm designing a software using Visual Basic to configure my device parameters. I'm writing the code for windows forms app in .vb In this I've to send a data to device and get response from device. If I didn't get the required response from device for a particular time I should output a message.
I've worked on serial writing, and made a simple software just to write some data. I've made a console to read the response from the device. I haven't got the slightest idea of checking the response and timeout in software.
I'll put a sample of code I've written.
Private Sub BtnPub_Click(sender As Object, e As EventArgs) Handles BtnPub.Click
Dim Data As String
Timer1.Start()
SerialPort1.Write("$PUB " & TbPub.Text & Environment.NewLine)
SerialPort1.ReadTimeout = 2000
Timer1.Start()
Try
Data = SerialPort1.ReadLine()
Catch ex As TimeoutException
MessageBox.Show("No reponse", "BYE")
Catch ex As Exception
End Try
The above code is a blunder, but this is my attempt. And i'm a virgin in VB.
EDIT
Private Sub BtnPub_Click(sender As Object, e As EventArgs) Handles BtnPub.Click
Dim Data As String
SerialPort1.ReadTimeout = 2000
SerialPort1.Write("$PUB " & TbPub.Text & Environment.NewLine)
Try
Data = SerialPort1.ReadLine()
If Data.Contains("OK") Then
MessageBox.Show("SUCCESS", "Success")
End If
Catch ex As TimeoutException
MessageBox.Show("No reponse" & Environment.NewLine & ex.ToString(), "BYE")
Catch ex As Exception
MessageBox.Show(ex.ToString(), "BYE")
End Try
End Sub
This is aslo not working, am not getting anything to my software
Related
I am downloading a file using webclient handling DownloadProgressChanged and DownloadFileCompleted.
My code is working whenever I am not updating the gui with percentage,b but In case I am going to update just a single label with it, then it kind of freezing in random situations. Doesn't matter if the file is little or big.
Public WithEvents mclient As New WebClient
Private Sub Download()
Dim filepath As String = (filepath..)
mclient.Encoding = Encoding.UTF8
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
mclient.Headers.Add(HttpRequestHeader.UserAgent, "")
mclient.DownloadFileAsync(New Uri(link), filepath)
End Sub
Private Sub mClient_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs) Handles mclient.DownloadProgressChanged
Try
'file website missing Content-Length, so getting the real size parsing html (real size=label7)
label1.text= ((e.BytesReceived) / 1048576).ToString("0.00") & "/" & Label7.Text
Catch ex As Exception
End Try
End Sub
Private Sub mClient_DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs) Handles mclient.DownloadFileCompleted
Try
label2.text="Download ended"
Catch ex As Exception
End Try
End Sub
How can I keep label1.text updated without using it inside of DownloadProgressChanged?
If I use a variable on it, where can I keep it updated? I don't want to use a timer though..
I have been struggling with question for some time now and I have tried Everything. there are similar questions on stack overflow but I have tired all solutions none of them worked for me. The problem is changes are not stored on the data base file after I call the data source binding. below is the code snippet for save button
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
If isValidData() = True Then ' sub routine that checks data inputted into textboxes is valid.
Try
' i get data from the textboxes on form which are binded to the bindingsource viewplanet...
Me.ViewPlanetAlliancesBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.DsLab4)
MessageBox.Show("Successfully Saved Data Row")
Call updateViewPlanetAlliance()
Catch ex As DBConcurrencyException
MessageBox.Show("A concurrency erro occured. " & "the row was not deleted.", "Concurrency Exception")
Me.ViewPlanetAlliancesTableAdapter.FillByRegionID(DsLab4.viewPlanetAlliances, CInt(Me.lstRegion.SelectedValue))
Catch ex As ArgumentException
MessageBox.Show(ex.Message, "Argument exception")
Me.ViewPlanetAlliancesBindingSource.CancelEdit()
Catch ex As DataException
MessageBox.Show(ex.Message, ex.GetType.ToString)
Me.ViewPlanetAlliancesBindingSource.CancelEdit()
End Try
Else
Try
Me.TableAdapterManager.UpdateAll(Me.DsLab4)
Catch ex As DBConcurrencyException
MessageBox.Show("A concurrency erro occured. " & "the row was not deleted.", "Concurrency Exception")
Me.ViewPlanetAlliancesTableAdapter.FillByRegionID(DsLab4.viewPlanetAlliances, CInt(Me.lstRegion.SelectedValue))
End Try
End If
End Sub
This is what my form looks like and how my data is displayed
I created an app that can communicate each other through winsock. the app can send text to other pc then received via a method in form 1 and saved as variable. i am trying to make the received data can be displayed realtime in form 2 via a rich text box. but so far i can only pass the value when form 2 load, but i cannot make the value updated and added realtime, so it works like a log system. how i can make those two form work at the same time, one is for sending data and receiving it, while the other for displaying the data received.
code on form 1
Public Sub ReceiveSock_DataArrival(sender As Object, e As Winsock2005DLL.WinsockDataArrivalEventArgs) Handles ReceiveSock.DataArrival
Try
ReceiveSock.Get(IncomingMessage)
IncomingMessage = IncomingMessage + vbNewLine
RichTextBox1.Text = RichTextBox1.Text + vbNewLine + IncomingMessage
Form2.RichTextBox1.Text = Form2.RichTextBox1.Text + IncomingMessage + vbNewLine
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
On Form 2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.RichTextBox1.Text = ""
Me.RichTextBox1.Text = Me.RichTextBox1.Text + Form1.IncomingMessage
End Sub
my app screenshot
I'm trying to notify users there has been a change to a file, by making a picturebox turn lime when the date in the application's settings is not equal to the LastWriteTime of a file. However, when i run the program and the two are equal (to my knowledge) it still says they are not equal. I've added a textbox in order to visualize it, but I don't know what I'm doing wrong...
My code:
fsw_wervelSTX_file = My.Computer.FileSystem.GetFileInfo("G:\divi\RATH\Applicaties\RSM\Program\Settings\IGART\WervelSTX\log_wervelSTX.txt")
If Not My.Settings.fsw_wevelSTX_lastwrite = fsw_wervelSTX_file.LastWriteTime Then
PictureBox_wervelSTX.BackColor = Color.Lime
MsgBox("Time in My.Settings: " & My.Settings.fsw_wevelSTX_lastwrite & " LastWriteTime: " & fsw_wervelSTX_file.LastWriteTime, MsgBoxStyle.Information)
Else
PictureBox_wervelSTX.BackColor = Color.Maroon
MsgBox("It is the same", MsgBoxStyle.Information)
End If
There's a screenshot of the MsgBox in the link:
MsgBox
The LastWriteTime is stored to My.Settings when the user clicks the button to open the specified file:
Code:
Private Sub Button11_Click(sender As System.Object, e As System.EventArgs) Handles Button11.Click
Try
Process.Start("G:\divi\RATH\Applicaties\RSM\Program\Settings\IGART\WervelSTX\log_wervelSTX.txt")
PictureBox_wervelSTX.BackColor = Color.Maroon
fsw_wervelSTX_file = My.Computer.FileSystem.GetFileInfo("G:\divi\RATH\Applicaties\RSM\Program\Settings\IGART\WervelSTX\log_wervelSTX.txt")
MsgBox(fsw_wervelSTX_file.LastWriteTime, MsgBoxStyle.Information)
My.Settings.fsw_wevelSTX_lastwrite = fsw_wervelSTX_file.LastWriteTime
Catch ex As Exception
MessageBox.Show("Error opening file: " & ex.Message)
End Try
End Sub
Thanks in advance.
Going from the code you posted I guess it's a serialization thing. The datetime is probably stored in your settings as something like 2016-01-06 12:08:11 (aside the actual date formatting) whereas the actual datetime probably has more/better 'resolution' and contains something like 2016-01-06 12:08:11.123. I'd suggest one of:
Storing it in a specific (specified) format and make sure you compare no more than the actual stored 'resolution'
Storing the value as ticks or some other specific long/integer value (e.g. UNIX timestamp for example)
Allow for some 'margin' when comparing
Which is best is up to you and the requirements / usecases.
There's all sorts of weird things with file datetimes like Why does the timestamp of a file increase by up to 2 seconds when I copy it to a USB thumb drive? but my best guess currently is that you're just comparing two slightly different values.
Added to load code:
Dim timecompare As Date
Private Sub IGART_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
fsw_wervelSTX_file = My.Computer.FileSystem.GetFileInfo("G:\divi\RATH\Applicaties\RSM\Program\Settings\IGART\WervelSTX\log_wervelSTX.txt")
timecompare = fsw_wervelSTX_file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")
If Not My.Settings.fsw_wevelSTX_lastwrite = timecompare Then
PictureBox_wervelSTX.BackColor = Color.Lime
MsgBox("Time in My.Settings: " & My.Settings.fsw_wevelSTX_lastwrite & " LastWriteTime: " & fsw_wervelSTX_file.LastWriteTime, MsgBoxStyle.Information)
Else
PictureBox_wervelSTX.BackColor = Color.Maroon
MsgBox("It is the same", MsgBoxStyle.Information)
End If
Added to button code:
Dim time As Date
Private Sub Button11_Click(sender As System.Object, e As System.EventArgs) Handles Button11.Click
Try
Process.Start("G:\divi\RATH\Applicaties\RSM\Program\Settings\IGART\WervelSTX\log_wervelSTX.txt")
PictureBox_wervelSTX.BackColor = Color.Maroon
fsw_wervelSTX_file = My.Computer.FileSystem.GetFileInfo("G:\divi\RATH\Applicaties\RSM\Program\Settings\IGART\WervelSTX\log_wervelSTX.txt")
MsgBox(fsw_wervelSTX_file.LastWriteTime, MsgBoxStyle.Information)
My.Settings.fsw_wevelSTX_lastwrite = fsw_wervelSTX_file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")
Catch ex As Exception
MessageBox.Show("Error opening file: " & ex.Message)
End Try
End Sub
I't making a program to delete the files in my temp folder. I've gotten as far as the code to delete the files, But I can't seem to figure out how to skip the files in use or catch the exception so that my program doesn't crash when it attempts to delete a file in use.
Here is the code I have so far:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
If CheckBox1.Checked = True Then
Dim s As String
For Each s In System.IO.Directory.GetFiles("C:\Users\" + System.Environment.UserName + "\AppData\Local\Temp")
System.IO.File.Delete(s)
Next s
End If
end sub
Use a Try/Catch block to catch errors (exceptions)
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
If CheckBox1.Checked = True Then
Dim s As String
For Each s In System.IO.Directory.GetFiles("C:\Users\" + System.Environment.UserName + "\AppData\Local\Temp")
Try
System.IO.File.Delete(s)
Catch ex As Exception
Console.WriteLine("File could not be deleted : {0}", ex.Message)
End Try
Next s
End If
end sub
That will allow your program to ignore the error and continue processing the next items.
When an exception is thrown, once it is handled by the Catch, execution will jump to the End Try. Therefore, where you place the beginning and ending of your Try/Catch block is important. For instance:
Try
Dim s As String
For Each s In System.IO.Directory.GetFiles("C:\Users\" + System.Environment.UserName + "\AppData\Local\Temp")
System.IO.File.Delete(s)
Next s
Catch ex As IOException
End Try
In the above example, if any call to Delete fails, it will jump to the End Try and skip the rest of the iterations of the For loop (thereby skipping the rest of the files). However, consider this:
Dim s As String
For Each s In System.IO.Directory.GetFiles("C:\Users\" + System.Environment.UserName + "\AppData\Local\Temp")
Try
System.IO.File.Delete(s)
Catch ex As IOException
End Try
Next s
In this second example, it will jump to the End Try and then continue to the next iteration of the For loop (thereby continuing on the the next file in the list).
Also, as noted in the comments, above, you definitely ought to be using Path.GetTempPath to get the path to the temporary folder. You should not construct the path yourself, since it could change. For instance, Windows does not require that you user folder has to be under C:\Users. You can actually change that.