VB.net lag across different machines - vb.net

I wrote a small little key inventory program. Basically it uses an INI file to know what keys we have and which ones are signed out, to whom, by whom, etc. It is run on up to 4 computers all in the same room and accesses the ini file on our local server.
When I sign a key out or in, it shows the change instantly. If I run two instances of the same program on the same machine, again, it's instant.
When I sign out a key on machine A and a co-worker is running the same program on machine B, C or D, the change in what is signed out doesn't show up for 4-10 seconds.
The way the program checks for updates is by using IO.File.Getlastwritetime on loading (saving it to a label with visible = false) and then every time the timer goes (every second) it compares the files "getlastwritetime" to the label. If they are different, then it updates, if they are the same, it does nothing.
Any idea where I should start looking for this lag? Could it be a server problem?
Here is the code for Timer1.tick, I am using the read/write ini codes from http://deepvbnet.blogspot.in/2008/07/how-to-read-from-ini-file.html
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim TimeCheck As String = IO.File.GetLastWriteTime("G:/BFAS/DPS/Comm Center/TEST/keys.ini")
If TimeCheck <> Label5.Text Then
ListBox1.Items.Clear()
ComboBox1.Items.Clear()
str1 = "NumOfKeys"
Call readIniFile()
Dim OneTime As String = strdata.ToString
Dim numberofkeys As Integer = Convert.ToInt32(OneTime)
For i = 1 To numberofkeys
str1 = "Key" & i & "Out"
Call readIniFile()
Dim isKeyOut As String = strdata.ToString
If isKeyOut = "True" Then
str1 = "Key" & i & "Name"
Call readIniFile()
Dim KeyName As String = strdata.ToString
str1 = "Key" & i & "Unit"
Call readIniFile()
Dim string1 As String = strdata.ToString
str1 = "Key" & i & "Rent"
Call readIniFile()
Dim string2 As String = strdata.ToString
str1 = "Key" & i & "User"
Call readIniFile()
Dim string3 As String = strdata.ToString
str1 = "Key" & i & "Date"
Call readIniFile()
Dim string4 As String = strdata.ToString
str1 = "Key" & i & "Time"
Call readIniFile()
Dim string5 As String = strdata.ToString
ListBox1.Items.Add(LSet(KeyName, 20) + " - " + string1 + " - " + string2 + " - " + string3 + " - " + string4 + " - " + string5)
ElseIf isKeyOut = "False" Then
str1 = "Key" & i & "Name"
Call readIniFile()
Dim thisKeysName As String = strdata.ToString
ComboBox1.Items.Add(thisKeysName)
End If
Next
Dim FileTime As String = IO.File.GetLastWriteTime("G:/BFAS/DPS/Comm Center/TEST/keys.ini")
Label5.Text = FileTime
End If
Dim escortTime As String = IO.Directory.GetLastWriteTime("G:/BFAS/DPS/Comm Center/TEST/Escort")
If escortTime <> Label7.Text Then
ListBox2.Items.Clear()
For Each foundfile In My.Computer.FileSystem.GetFiles("G:/BFAS/DPS/Comm Center/TEST/Escort/")
If foundfile = "G:/BFAS/DPS/Comm Center/TEST/Escorthistory.txt" Then
'do nothing
Else
Dim Infomation As String = My.Computer.FileSystem.ReadAllText(foundfile)
ListBox2.Items.Add(Infomation)
End If
Next
Label7.Text = IO.Directory.GetLastWriteTime("G:/BFAS/DPS/Comm Center/TEST/Escort")
End If
Dim alarmtime As String = IO.Directory.GetLastWriteTime("G:/BFAS/DPS/Comm Center/TEST/Alarms")
If alarmtime <> Label8.Text Then
ListBox3.Items.Clear()
For Each foundfile In My.Computer.FileSystem.GetFiles("G:/BFAS/DPS/Comm Center/TEST/Alarms/")
Dim Infomation As String = My.Computer.FileSystem.ReadAllText(foundfile)
ListBox3.Items.Add(Infomation)
Next
Label8.Text = IO.Directory.GetLastWriteTime("G:/BFAS/DPS/Comm Center/TEST/Alarms")
End If
Dim turnovertime As String = IO.File.GetLastWriteTime("G:/BFAS/DPS/Comm Center/TEST/turnover.txt")
If Label9.Text <> turnovertime Then
Dim newTO As String = My.Computer.FileSystem.ReadAllText("G:/BFAS/DPS/Comm Center/TEST/turnover.txt")
TextBox3.Text = newTO
Label9.Text = IO.File.GetLastWriteTime("G:/BFAS/DPS/Comm Center/TEST/turnover.txt")
End If
End Sub

Related

Variable '' is used before it has been assigned a value.

I'm trying to make a program that downloads a bunch of domains and adds them windows hosts file but I'm having a bit of trouble. I keep getting an error when I try storing them in a list. I don't get why it doesn't work.
Sub Main()
Console.Title = "NoTrack blocklist to Windows Hosts File Converter"
Console.WriteLine("Downloading . . . ")
Dim FileDelete As String = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) & "/Downloads" & "/notracktemp.txt"
If System.IO.File.Exists(FileDelete) = True Then
System.IO.File.Delete(FileDelete)
End If
download()
Threading.Thread.Sleep(1000)
Dim s As New IO.StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) & "/Downloads" & "/notracktemp.txt", True)
Dim tempRead As String ' = s.ReadLine
Dim tempSplit As String() ' = tempRead.Split(New Char() {" "})
Dim i As Integer = 0
Dim tempStore As String()
s.ReadLine()
s.ReadLine()
Do Until s.EndOfStream = True
tempRead = s.ReadLine
tempSplit = tempRead.Split(New Char() {" "})
Console.WriteLine(tempSplit(0))
tempStore(i) = tempSplit(0)'The part that gives me the error
i = i + 1
Loop
Console.ReadKey()
End Sub
Sub download()
Dim localDir As String = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
'"Enter file URL"
Dim url As String = "https://quidsup.net/notrack/blocklist.php?download"
'"Enter directory"
Dim dirr As String = localDir & "/Downloads" & "/notracktemp.txt"
My.Computer.Network.DownloadFile(url, dirr)
'System.IO.File.Delete(localDir & "/notracktemp.txt")
End Sub
tempStore() has to have a size
count number of lines in file with loop, then declare it as tempStore(i) where i is the amount of lines. Here is a function that counts the lines.
Function countlines()
Dim count As Integer
Dim s As New IO.StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) & "/Downloads" & "/notracktemp.txt", True)
s.ReadLine()
s.ReadLine()
count = 0
Do Until s.EndOfStream = True
s.ReadLine()
count = count + 1
Loop
Console.WriteLine(count)
Return count
Console.ReadKey()
End Function
Then what you do is:
Dim count As Integer
count = countlines()
Dim tempStore(count) As String

Cannot get SQL Query to work with SafeSqlLiteral function

I have a function SafeSqlLiteral, found online. It's a function to prevent SQL injection attacks. I want to use this function inside my SQL query like so:
Dim com As String = "SELECT * FROM Person WHERE " &
SafeSqlLiteral(SearchCriteria, 2)
SearchCriteria being user input. I want the user to be able to enter: strState LIKE 'M%' and show all the records matching a state like Maine. It feels like this would work. (SELECT * FROM Person WHERE strState LIKE 'M%')
I'm getting a whole bunch of errors (probably too many to post on here, but will post them if needed), and I'm having a hard time figuring out how to make my query work with the SafeSqlLiteral function.
Here is the SafeSqlLiteral function:
Public Function SafeSqlLiteral(theValue As System.Object,
theLevel As System.Object) As String
Dim strValue As String = DirectCast(theValue, String)
Dim intLevel As Integer = CInt(theLevel)
If strValue IsNot Nothing Then
If intLevel > 0 Then
strValue = strValue.Replace("'", "''")
strValue = strValue.Replace("--", "")
strValue = strValue.Replace("[", "[[]")
strValue = strValue.Replace("%", "[%]")
End If
If intLevel > 1 Then
Dim myArray As String() = New String() {"xp_ ", "update ", "insert ", "select ", "drop ", "alter ",
"create ", "rename ", "delete ", "replace "}
Dim i As Integer = 0
Dim i2 As Integer = 0
Dim intLenghtLeft As Integer = 0
For i = 0 To myArray.Length - 1
Dim strWord As String = myArray(i)
Dim rx As New Regex(strWord, RegexOptions.Compiled Or RegexOptions.IgnoreCase)
Dim matches As MatchCollection = rx.Matches(strValue)
i2 = 0
For Each match As Match In matches
Dim groups As GroupCollection = match.Groups
intLenghtLeft = groups(0).Index + myArray(i).Length + i2
strValue = strValue.Substring(0, intLenghtLeft - 1) + " " + strValue.Substring(strValue.Length - (strValue.Length - intLenghtLeft), strValue.Length - intLenghtLeft)
i2 += 5
Next
Next
End If
Return strValue
Else
Return strValue
End If
End Function
Thanks in advance for anyone helping me solve this problem! It's greatly appreciated!

Splitting a full name string to separate variables (first, middle and last) without using the split function

So I was given the task to bifurcate a string with a full name and then print out the first and last name separately. For instance, input: Steve Robertson, output: First name: Steve Last name: Robertson.
I succeeded, it was fairly easy. But I'm having having trouble in dividing a full name string to first, last and middle. Here's what I've done so far.
Sub Main()
Dim string1 As String = ""
Dim string2 As String = ""
Dim string3 As String = ""
Dim string4 As String = ""
Dim temp1 As String = ""
Dim integer1 As Integer = 1
Console.WriteLine("Enter the string you want to bifurcate: ")
string1 = Console.ReadLine()
While integer1 <> 0
integer1 = InStr(string1, " ")
Console.WriteLine(string1)
string2 = Left(string1, integer1)
Console.WriteLine(string2)
string3 = Mid(string1, integer1 + 1)
Console.WriteLine(string3)
string4 = Mid(string1, integer1 + 1)
Console.WriteLine(string4)
string1 = string4
End While
Console.WriteLine("First name is: " & string2)
Console.WriteLine("Second name is: " & string3)
Console.WriteLine("Third name is: " & string4)
Console.ReadKey()
End Sub
Keep in mind that I'm only printing almost every single variable to see what their value is during the iteration. I can only use the len() function and whatever is already in the code.
EDIT:
So I fiddled around and finally got the thing, without the loop, but I was wondering if there was a cleaner/right way to do this without repeating the variables and also not needing to create any new ones either.
Sub Main()
Dim string1 As String = ""
Dim string2 As String = ""
Dim string3 As String = ""
Dim string4 As String = ""
Dim integer1 As Integer
Console.WriteLine("Enter the string you want to split: ")
string1 = Console.ReadLine()
integer1 = InStr(string1, " ")
string2 = Left(string1, integer1)
string3 = Mid(string1, integer1 + 1)
integer1 = InStr(string3, " ")
string4 = Left(string3, integer1)
string3 = Mid(string3, integer1 + 1)
Console.WriteLine("The first name is: " & string2)
Console.WriteLine("The middle name is: " & string4)
Console.WriteLine("The last name is: " & string3)
Console.ReadKey()
End Sub
Here is one way to do it. Loop through the characters from the input of the user. Continue to do so concatenating them together and throw them into a List(Of String) that way the can be easily written out at the end... This account's for multiple spaces as well if there's more than one in between names. Also I put some comment's into the code so it can be easier to understand.
Note: This is only one way to do it... (there are other ways)
CODE TRIED AND TESTED
Dim nList As New List(Of String)
Dim uStr As String = String.Empty
Console.WriteLine("Enter the string you want to bifurcate: ")
uStr = Console.ReadLine()
If Not String.IsNullOrEmpty(uStr) Then 'Make sure something was entered...
Dim tStr As String = String.Empty
'Loop through user's input...
Do Until uStr = String.Empty
For Each c As Char In uStr
If Not Char.IsWhiteSpace(c) Then 'If it's a space we can add to the current string...
tStr &= c.ToString
Else
'We can assume its another section of the name...
Exit For
End If
Next
'If its a space, remove it from current string...
If String.IsNullOrEmpty(tStr) Then uStr = uStr.Remove(0, tStr.Length + 1) : Continue Do
'Add the string to the list, could be first name, middle or lastname?
If nList.Count = 0 Then
nList.Add("First Name: " & tStr)
ElseIf nList.Count = 1 Then
nList.Add("Middle Name: " & tStr)
ElseIf nList.Count = 2 Then
nList.Add("Last Name: " & tStr)
End If
'Now we can remove what we got from the users input...
uStr = uStr.Remove(0, tStr.Length)
tStr = String.Empty
Loop
End If
'Finally write out the values...
Console.WriteLine(String.Join(Environment.NewLine, nList.ToArray))
Console.ReadLine()
Screenshot Of Program
Maybe something like this
Dim fullName = "Juan Perez"
Dim name = fullName.Substring(0, fullName.IndexOf(" "))
Dim lastName = fullName.Substring(fullName.IndexOf(" ") + 1)
How to separate full name string
I would suggest that you design extension methods that will return First and Last Name
Module Module1
<Extension()>
Public Function returnFirst(ByVal fullName As String) As String
Return fullName.Substring(0, fullName.IndexOf(" "))
End Function
<Extension()>
Public Function returnLast(ByVal fullName As String) As String
Return fullName.Substring(fullName.IndexOf(" ") + 1)
End Function
End Module
'call it
'import module1
Dim Name as string = 'FirstName LastName'
MessageBox.Show(NAME.returnFirst)
MessageBox.Show(NAME.returnLast)

For-loop doesn't complete all iterations

I have problem with this - I try to send broadcast SMS using AT Commands in my system. After that the SMS content will be stored in my database. My store content SMS function works well. I can store all my SMS content that I send, but the send function just sends message to my first data on my datagridview.
Please help me to deal with this - I posted my code below
Private Sub ButtonKirim_Click(sender As Object, e As EventArgs) Handles ButtonKirim.Click
Dim noPel As String
Dim isiPesan As String = ""
Dim tgl As Date = Now.Date
Dim strReplace(2) As String
Dim strIsi(2) As String
Dim tagBulan As String = "<bulan>"
Dim tagtagihan As String = "<tagihan>"
Dim tagLokasi As String = "<lokasi>"
Dim pesanKirim As String = ""
My.Settings.SettingPesan = RichTextBoxPesan.Text
My.Settings.Save()
'Label4.Text = isiPesan
For pelanggan As Integer = 0 To DataGridViewKirimPesan.RowCount - 1
'mengirim pesan/send message
noPel = DataGridViewKirimPesan.Rows(pelanggan).Cells(3).Value()
strReplace(0) = tagBulan
strReplace(1) = tagtagihan
strReplace(2) = tagLokasi
strIsi(0) = DataGridViewKirimPesan.Rows(pelanggan).Cells(4).Value
strIsi(1) = DataGridViewKirimPesan.Rows(pelanggan).Cells(5).Value
strIsi(2) = DataGridViewKirimPesan.Rows(pelanggan).Cells(6).Value
isiPesan = RichTextBoxPesan.Text
For i As Integer = LBound(strReplace) To UBound(strReplace)
isiPesan = isiPesan.Replace(strReplace(i), strIsi(i))
Next
SendMessage(noPel, isiPesan)
''menyimpan pesan keluar ke sms_terkirim/this query store my content SMS to table
Dim sqlSmsKeluar As String = "INSERT INTO sms_terkirim (`tgl_sms`,`id_pelanggan`, `isi_sms`) VALUES ( NOW()," & DataGridViewKirimPesan.Rows(pelanggan).Cells(0).Value & " , '" & isiPesan & "');"
cudMethod(sqlSmsKeluar)
MsgBox(sqlSmsKeluar)
'ProgressBarKirimPesan.Increment(1)
Next
'MsgBox("Pesan Sukses Terkirim")
' Catch ex As Exception
' MsgBox("Pesan Gagal Terkirim" + ex.Message)
'End Try
' End If
End Sub
and this code is AT Command to send message
Public Sub SendMessage(ByVal NomorPelanggan As String, ByVal IsiPesan As String)
If SerialModem.IsOpen() Then
With SerialModem
.Write("AT" & vbCrLf)
Threading.Thread.Sleep(100)
.Write("AT+CMGF=1" & vbCrLf)
Threading.Thread.Sleep(100)
.Write("AT+CMGS=" & Chr(34) & NomorPelanggan & Chr(34) & vbCrLf)
Threading.Thread.Sleep(100)
.Write(IsiPesan & vbCrLf & Chr(26))
Threading.Thread.Sleep(100)
End With
Else
MsgBox("Modem Belum Tersambung")
End If
End Sub

extracting text from comma separated values in visual basic

I have such kind of data in a text file:
12343,M,Helen Beyer,92149999,21,F,10,F,F,T,T,T,F,F
54326,F,Donna Noble,92148888,19,M,99,T,F,T,F,T,F,T
99999,M,Ed Harrison,92147777,28,F,5,F,F,F,F,F,F,T
88886,F,Amy Pond,92146666,31,M,2,T,F,T,T,T,T,T
37378,F,Martha Jones,92144444,30,M,5,T,F,F,F,T,T,T
22444,M,Tom Scully,92145555,42,F,6,T,T,T,T,T,T,T
81184,F,Sarah Jane Smith,92143333,22,F,5,F,F,F,T,T,T,F
97539,M,Angus Harley,92142222,22,M,9,F,T,F,T,T,T,T
24686,F,Rose Tyler,92142222,22,M,5,F,F,F,T,T,T,F
11113,F,Jo Grant,92142222,22,M,5,F,F,F,T,T,T,F
I want to extract the Initial of the first name and complete surname. So the output should look like:
H. Beyer, M
D. Noble, F
E. Harrison, M
The problem is that I should not use String Split function. Instead I have to do it using any other way of string handling.
This is my code:
Public Sub btn_IniSurGen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_IniSurGen.Click
Dim vFileName As String = "C:\temp\members.txt"
Dim vText As String = String.Empty
If Not File.Exists(vFileName) Then
lbl_Output.Text = "The file " & vFileName & " does not exist"
Else
Dim rvSR As New IO.StreamReader(vFileName)
Do While rvSR.Peek <> -1
vText = rvSR.ReadLine() & vbNewLine
lbl_Output.Text += vText.Substring(8, 1)
Loop
rvSR.Close()
End If
End Sub
You can use the TextFieldParserClass. It will parse the file and return the results directly to you as a string array.
Using MyReader As New Microsoft.VisualBasic.FileIO.
TextFieldParser("c:\logs\bigfile")
MyReader.TextFieldType =
Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {","}
Dim currentRow As String()
'Loop through all of the fields in the file.
'If any lines are corrupt, report an error and continue parsing.
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
' Include code here to handle the row.
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
" is invalid. Skipping")
End Try
End While
End Using
For your wanted result, you may changed
lbl_Output.Text += vText.Substring(8, 1)
to
'declare this first
Dim sInit as String
Dim sName as String
sInit = vText.Substring(6, 1)
sName = ""
For x as Integer = 8 to vText.Length - 1
if vText.Substring(x) = "," Then Exit For
sName &= vText.Substring(x)
Next
lbl_Output.Text += sName & ", " & sInit
But better you have more than one lbl_Output ...
Something like this should work:
Dim lines As New List(Of String)
For Each s As String In File.ReadAllLines("textfile3.txt")
Dim temp As String = ""
s = s.Substring(s.IndexOf(","c) + 1)
temp = ", " + s.First
s = s.Substring(s.IndexOf(","c) + 1)
temp = s.First + ". " + s.Substring(s.IndexOf(" "c), s.IndexOf(","c) - s.IndexOf(" "c)) + temp
lines.Add(temp)
Next
The list Lines will contain the strings you need.