Why is it that the LastWriteTime of a file and the stored Date&Time of that same file don't equal, even if are the same? - vb.net

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

Related

How to Read response data in for a particular time and check the data?

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

How to display value from TextBox into a MessageBox in VB.NET?

I honestly don't know what I'm doing wrong. I have a textbox named "txtNumSticks" where the user enters a number. After the user hits start, I want a message box to pop up that says "Okay! We'll play with (x) sticks!" But I can't get it to work. First day learning VB.net. Thanks in advance!
Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
Dim NumSticks As String
txtNumSticks.Text = NumSticks
Game.Show()
Me.Close()
MessageBox.Show("Okay! We'll play with " & NumSticks & "sticks!")
End Sub
You are setting the variable the wrong way around you should be assigning NumSticks to the value in the text box so:
NumSticks = txtNumSticks.Text
or alternatively without the use of a variable
MessageBox.Show("Okay! We'll play with " & txtNumSticks.Text & "sticks!")
You may want to add a little bit of error checking in your program to make sure your value entered is Numeric.
Dim NumSticks As String
NumSticks = txtNumSticks.Text.ToString
If IsNumeric(NumSticks) Then
Game.Show()
MessageBox.Show("Okay! We'll play with " & NumSticks & " sticks!")
Me.Close()
Else
' Let user know the value is non-numeric
MessageBox.Show("Non Numeric Value entered", "Error!", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If

StreamWriter leaving a file even if not saved

I have this code to write some data from textboxes into a textfile. And i'm using streamwriter to do this. Here you may see the code below:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim Save As New SaveFileDialog()
Dim myStreamWriter As System.IO.StreamWriter
Save.Filter = "Text [*.txt*]|*.txt|All Files [*.*]|*.*"
Save.CheckPathExists = True
Save.Title = "Export & Save - FNG"
Save.FileName = txtTitle.Text & " - Plugs Details File Exported"
Save.ShowDialog(Me)
Try
myStreamWriter = System.IO.File.AppendText(Save.FileName)
myStreamWriter.Write("Details of Plugs:" & Environment.NewLine & txtDetails.Text & Environment.NewLine & DateAndTime.Now)
myStreamWriter.Flush()
Catch ex As Exception
End Try
End Sub
The code does work fine, it saves the details into a text file too. But the problem is when i cancel the save file dialog (without saving the textfile) it stil creates a file in the application start path. Why is this happening? What am i doing wrong? How do i correct this?
Try
If Save.ShowDialog(Me) <> DialogResult.Ok Then Return
Cancelling the dialog doesn't automatically make your Sub return!
Further, you are using StreamWriter wrong. Use
Using myStreamWriter As System.IO.StreamWriter = System.IO.File.AppendText(Save.FileName)
myStreamWriter.Write("Details of Pish flaps:" & Environment.NewLine & txtDetails.Text & Environment.NewLine & DateAndTime.Now)
End Using
And remove the Dim of the StreamWriter. This will ensure that the StreamWriter is closed even if an exception is thrown.

Change date format in code only

I've a code that simply creates a folder in a directory and gives it a name based on the values of a datetimepicker and a text box.
The date picker is displayed on the form as "16 October 2013" (how I want to keep it) but when I generate the file name I would lime the date to read in the format "161013"
The code I'm using is below if that helps
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim lMailbox As String
lMailbox = t2.Text & "-" & d1.Text
' Check if folder exists, if not: create it
If Not Directory.Exists(nMailbox & lMailbox) Then
Directory.CreateDirectory(nMailbox & lMailbox)
' Folder created message
MessageBox.Show("Mailbox created!", "Lynx Control Panel", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
' Folder already exists
MessageBox.Show("Mailbox already exists!", "Lynx Control Panel", MessageBoxButtons.OK, MessageBoxIcon.Stop)
End If
End Sub
The nMailbox & lMailbox are declared at the top of the code page
d1 is the name of the datepicker
I'm very new to VB.net and would appreciate any help
Thanks
try this:
lMailbox = t2.Text & "-" & d1.Value.ToString("ddMMyy")
The format options are the same as for DateTime string formatting. Use Value of the DTP rather than the Text which is formatted otherwise/

Making a Trial version of a program

I am making trial version of my vb .net project but it is not counting the days , date and time .
Can u please give me any suggestions to correct it. I am using the following code
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim intTime As Integer = 1
Dim dteLastStart, dteStartDate As Date
Dim blnFirstTime, blnEnabled As Boolean
Dim lngTimeLeft As Long
blnEnabled = True
If dteStartDate = Nothing Then
dteStartDate = Now
End If
My.Application.SaveMySettingsOnExit = True
If DateDiff(DateInterval.Day, dteLastStart, Now) < 0 Then
'First clock change
If intTime = 1 Then
MsgBox("FRED has detected that you have changed your system date to an earlier date" & vbCrLf & "As FRED has built-in security," & vbCrLf & "FRED will only run until the next intTime you change your system date", MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "System Date Changed")
intTime = 2
ElseIf intTime = 2 Then
'Second clock change
blnEnabled = False
MsgBox("FRED has detected that you have changed your system date to an earlier date" & vbCrLf & "As this is the second warning, FRED will now be disabled", MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "System Date Changed")
End If
'disables app
If blnEnabled = False Then
If MsgBox("FRED is disabled", MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "Disabled") = MsgBoxResult.Ok Then
For Each form As Form In My.Application.OpenForms
form.Close()
Next
End If
End If
End If
If DateDiff(DateInterval.Day, dteStartDate, Now) > 29 Then
blnEnabled = False
If blnEnabled = False Then
If MsgBox("FRED has reached the end of it's trial.", MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "Trial Ended") = MsgBoxResult.Ok Then
'Close all open forms
For Each form As Form In My.Application.OpenForms
form.Close()
Next
End If
End If
End If
dteLastStart = Now
If blnFirstTime = True Then
blnFirstTime = False
End If
'Saves variable settings
My.Settings.Save()
lngTimeLeft = 29 - (DateDiff(DateInterval.Day, dteStartDate, Now))
MsgBox("This is a 29-day trial version." & vbCrLf & "You have " & CStr(lngTimeLeft) & " days left.", MsgBoxStyle.OkOnly, "FRED Trial")
end sub
end class
Let's say your program called "MyProg" and you want user to try it for 7 days.
So, conceptually, you'll have entry in registry:
HKLM\SOFTWARE\MyProg
Each run of the software, you will have to check if it exists, if not, assuming it's a first run and you will create the entry and set value. If entry exists, you will retrieve value and compare to now.
No for coding, here is an example function that handles registry and returns false if date expired or true if still trial period:
Private Function HandleRegistry() As Boolean
Dim firstRunDate As Date
firstRunDate = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\SOFTWARE\MyProg", "FirstRun", Nothing)
If firstRunDate = Nothing Then
firstRunDate = Now
My.Computer.Registry.SetValue("HKEY_LOCAL_MACHINE\SOFTWARE\MyProg", "FirstRun", firstRunDate)
ElseIf (Now - firstRunDate).Days > 7 Then
Return False
End If
Return True
End Function
No all you have to do, is to call it and handle response:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim result As Boolean = HandleRegistry()
If result = False Then 'something went wrong
MsgBox("Trial expired")
Else
MsgBox("Trial version")
End If
End Sub
Of course this is example only, so you get the idea, but practicality i would encode date and call registry name entry something else so it won't be user friendly. Also, remember the architecture issue so you know where it's written.
Hope that helps