For-loop doesn't complete all iterations - vb.net

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

Related

how to use serial port in a service application environment constantly listening for data

Ive written a service application that listens to a port for any communication that may come through, our lab will run a certain test which will send serial data down every couple hours or so. the service is runs picks up the data fine for a few hours and then mysteriously stops. the system eventlog says the service terminated unexpectedly. and in the application event log it has a more descriptive .NET error,
Application: BondTestService.exe Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.ObjectDisposedException at
System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean
ByRef) at
System.StubHelpers.StubHelpers.SafeHandleAddRef(System.Runtime.InteropServices.SafeHandle,
Boolean ByRef) at
Microsoft.Win32.UnsafeNativeMethods.GetOverlappedResult(Microsoft.Win32.SafeHandles.SafeFileHandle,
System.Threading.NativeOverlapped*, Int32 ByRef, Boolean) at
System.IO.Ports.SerialStream+EventLoopRunner.WaitForCommEvent() at
System.Threading.ThreadHelper.ThreadStart_Context(System.Object) at
System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext,
System.Threading.ContextCallback, System.Object, Boolean) at
System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext,
System.Threading.ContextCallback, System.Object, Boolean) at
System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext,
System.Threading.ContextCallback, System.Object) at
System.Threading.ThreadHelper.ThreadStart()
i was reading how services behave and how serial ports behave, so correct me if im wrong if the there is a 2 hour gap or so inbetween tests, the service will assume that its not running and stop itself?
I also read after reading the buffer from the serial port i append to a string builder object like below and do what i need to the string, then what happens to the serial port does it just stay open waiting for next value or do i have to close it and reopen it in order to refresh it?
Not sure how to handle this as it needs to be open waiting for the lab tester to send his data at any given time.
Imports System
Imports System.Data.SqlClient
Imports System.IO.Ports
Imports System.Net.Mime
Imports Microsoft.Win32
Imports System.IO
Imports System.Text.RegularExpressions
Imports BondTestService.PI
Imports PCA.Core.Configuration
Public Class Bond
Dim WithEvents serialPort As New IO.Ports.SerialPort
Public Delegate Sub myDelegate()
Public RawString As New System.Text.StringBuilder
Public value As String
Public BondTest As Integer = 10
#Region "Commport Traffic and Configuration Validations"
Public Sub StartListening()
If serialPort.IsOpen Then
serialPort.Close()
ErrorLog2(Now.ToString & "Port Closed because StartListening method started over")
End If
Try
With serialPort
.PortName = Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("commport")
.BaudRate = CInt(Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("baudrate"))
If Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("parity") = 0 Then
.Parity = Parity.None
End If
If Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("stopbits") = 1 Then
.StopBits = StopBits.One
End If
.DataBits = CInt(Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("bytesize"))
.Handshake = Handshake.None
If Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("RtsControl") = 1 Then
.RtsEnable = True
Else
.RtsEnable = False
End If
End With
serialPort.Open()
'debug
'ErrorLog2("Listening to COM 19, SerialPort has been Opened")
Catch ex As Exception
ErrorLog2(Now.ToString & ex.tostring)
End Try
End Sub
Public Function Filelocator() As String
' Dim filePath As String = IO.Path.Combine(Application.StartupPath, "bondtest.bat")
Dim filePath As String = IO.Path.Combine("C:\Program Files (x86)\PIPC\Interfaces\Lab", "BondTest.bat")
'Dim reader As New System.IO.StreamReader(filePath)
Dim LineNumber = 4
Using file As New StreamReader(filePath)
' Skip all preceding lines: '
For i As Integer = 1 To LineNumber - 1
If file.ReadLine() Is Nothing Then
ErrorLog2("LineNumber")
End If
Next
' Attempt to read the line you're interested in: '
Dim line As String = file.ReadLine()
If line Is Nothing Then
ErrorLog2("LineNumber")
End If
Return line
End Using
End Function
Private Sub serialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
Try
If GetBondInterfaceStatus = 1 Then
UPdateVariable()
Else
exit Sub
End If
Catch ex As Exception
Errorlog2(Ex.Tostring)
End Try
End Sub
#End Region
#Region "String Handling"
Public Sub UPdateVariable()
With RawString
.Append(serialPort.ReadLine())
End With
try
ErrorLog2(now.ToString & RawString.ToString)
InsertTestDataDEBUG(GetRecordID, BondTest, BondTestType.ToUpper.ToString, GetBondPosition(), StringParser(RawString.ToString()), RawString.tostring)
InsertTestData(GetRecordID, BondTest, BondTestType.ToUpper.ToString, GetBondPosition(), StringParser(RawString.ToString()))
RawString.Clear()
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
End Sub
Public Function StringParser(RawString As String)As Double ()
Dim Moisture = RawString
Dim pattern As String = "[0-9],"
Dim regex As New Regex(pattern)
Dim Counter As Integer = 0
Dim dblValues(1) As Double
Dim values As String() = Moisture.Split(New Char() {" "c})
for i = 0 to values.Count - 1
if regex.IsMatch(values(i)) Then
dblValues(Counter) = CDbl(values(i).Substring(0,1))
Counter = Counter + 1
Elseif values(i) = "" Then
continue for
else
if Double.TryParse(values(i), dblValues(Counter)) Then
Counter = Counter + 1
End If
End If
Next
Return dblValues
End Function
#End Region
#Region "SQL Statements"
Private Sub InsertTestData(RecordID As Integer, BondTest As Integer, TestType As String, TestPos As Integer, dataArray() As Double)
Dim InsertQuery As String = ""
Dim conn As New BondSQLConnection("PaperTests")
' Dim TestPos = StartingTestPos + (CInt(dataArray(0)) - 1)
conn("#RecordID") = RecordID
conn("#Test") = BondTest
conn("#TestType") = TestType
conn("#TestPos") = TestPos
conn("#TestData") = dataArray(1)
conn("#TestDateTime") = now.tostring
InsertQuery = "INSERT INTO PaperTests.dbo.PaperTestValues(ReelRecordID, Test, TestLocation, TestPosition, TestValue, TestTimeStamp) VALUES (#RecordID, #Test, #TestType, #TestPos, #TestData, #TestDateTime)"
Try
conn.ExecuteNonQuery(InsertQuery)
IncrementTestPosition
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
End Sub
Private Sub InsertTestDataDEBUG(RecordID As Integer, BondTest As Integer, TestType As String, TestPos As Integer, dataArray() As Double, rawString As String)
Dim InsertQuery As String = ""
Dim conn As New BondSQLConnection("PaperTests")
conn("#RecordID") = RecordID
conn("#Test") = BondTest
conn("#TestType") = TestType
conn("#TestPos") = TestPos
conn("#TestData") = dataArray(1)
conn("#RawString") = rawString
conn("#TestDateTime") = now.tostring
InsertQuery = "INSERT INTO PaperTests.dbo.InterfaceTesting(ReelRecordID, Test, TestLocation, TestPosition, TestValue, TestTimeStamp, RawValue) VALUES (#RecordID, #Test, #TestType, #TestPos, #TestData, #TestDateTime, #RawString)"
Try
conn.ExecuteNonQuery(InsertQuery)
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
End Sub
Private Sub IncrementTestPosition()
Dim tempPosition As Integer = GetBondPosition()
Dim FrontOriginalMax = 5
Dim CenterOriginalMax = 15
Dim BackOriginalMax = 25
Dim FrontRetestOrWinderMax = 10
Dim CenterRetestOrWinderMax = 20
Dim BackRetestOrWinderMax = 30
If tempPosition = FrontOriginalMax Then
tempPosition = 11
else if tempPosition = CenterOriginalMax Then
tempPosition = 21
else if tempPosition = BackOriginalMax Then
tempPosition = 1
Else If tempPosition = FrontRetestOrWinderMax then
tempPosition = 1
Else If tempPosition = CenterRetestOrWinderMax then
tempPosition = 1
Else If tempPosition = BackRetestOrWinderMax then
tempPosition = 1
else
tempPosition = tempPosition + 1
End If
SetBondPosition(tempPosition.tostring)
End Sub
#End Region
#Region "Get PiValues"
Private Function GetRecordID() As Int64
Dim RecordID As Int32 = 0
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
RecordID = piserver.GetCurrentValue("PAPERLAB:PaperLabReelSelected")
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return RecordID
End Function
Private Function GetBondPosition() As Int64
Dim BondPos As Int32 = 0
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
BondPos = CInt(piserver.GetCurrentValue("PAPERLAB:SBOND.POS"))
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return BondPos
End Function
Private Sub SetBondPosition(pos As String)
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
piserver.WriteValue("PAPERLAB:SBOND.POS", pos)
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
End Sub
Private Function BondTestType() As String
Dim TestType As String = ""
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
TestType = piserver.GetCurrentValue("M1:BOND.TYPE")
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return TestType
End Function
Private Function BondReelLoc() As String
Dim ReelLoc As String = ""
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
ReelLoc = piserver.GetCurrentValue("M1:BOND.ReelLoc")
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return ReelLoc
End Function
Private Function GetBondInterfaceStatus() As Integer
Dim Status As Integer = 0
Try
Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
Status = CInt(piserver.GetCurrentValue("PAPERLAB:BOND_INTERFACE.S"))
Catch ex As Exception
ErrorLog2(ex.ToString())
End Try
Return Status
End Function
#End Region
#Region "Debug"
Private Sub ErrorLog(RecordID As Int32, BondTest As Integer, ReelLoc As String, TestType As String, StartingTestPos As Integer, dataArray() As Double)
Dim SavePath As String = "C:\Program Files (x86)\PIPC\Interfaces\Lab"
Dim NameOfFile As String = "BondTest Debug File"
Dim TestPos = StartingTestPos + (CInt(dataArray(0)) - 1)
If System.IO.File.Exists(SavePath & "\" & NameOfFile & ".txt") Then
Using sw As StreamWriter = New StreamWriter(SavePath & "\" & NameOfFile & ".txt", True)
' For i = 0 To dataArray.Count -1
sw.WriteLine(" ")
sw.WriteLine(RecordID & " " & BondTest & " " & ReelLoc & " " & TestType & " " & TestPos & " " & dataArray(1).ToString)
' TestPos = TestPos + 1
' Next
End Using
else
File.Create(SavePath & "\" & NameOfFile & ".txt").Dispose()
Using sw As StreamWriter = File.CreateText(SavePath & "\" & NameOfFile & ".txt")
'For i = 0 To dataArray.Count -1
sw.WriteLine(" ")
sw.WriteLine(RecordID & " " & BondTest & " " & ReelLoc & " " & TestType & " " & TestPos & " " & dataArray(1).ToString)
' TestPos = TestPos + 1
'Next
End Using
End If
End Sub
Private Sub ErrorLog2(dataArray as string)
Dim SavePath As String = "C:\Program Files (x86)\PIPC\Interfaces\Lab"
Dim NameOfFile As String = "BondTest Debug File"
' Dim TestPos = StartingTestPos
If System.IO.File.Exists(SavePath & "\" & NameOfFile & ".txt") Then
Using sw As StreamWriter = New StreamWriter(SavePath & "\" & NameOfFile & ".txt", True)
sw.WriteLine(" ")
sw.WriteLine(dataArray)
End Using
else
File.Create(SavePath & "\" & NameOfFile & ".txt").Dispose()
Using sw As StreamWriter = File.CreateText(SavePath & "\" & NameOfFile & ".txt")
sw.WriteLine(" ")
sw.WriteLine(dataArray)
End Using
End If
End Sub
#End Region
This is a screenshot of the errors:
Thanks in advance
Normally, after opening the serial port in .NET it stays opened for arbitrary time. I've written several .NET applications were serial ports are used for months or years without app or computer restart and they work well.
According to the exception info you posted it looks like that serial port has been disposed. There are several possible reasons.
Using bad driver or HW, that disconnects your serial port. I've been using many USB-to-RS232 converters and some of them had bad drivers so sometimes ports were randomly disconnected and ObjectDisposedException was thrown. In earlier Windows editions (XP) the OS even 'blue-screened'. Here is more info about such situation where ObjectDisposedException is thrown.
This is a known problem with SerialPort. Device removal causes an uncatchable exception in a background thread it uses (WaitForCommEvent). The only solutions are to not use SerialPort or create a .config file that puts unhandled exception trapping mode back to .NET 1.1 behavior.
The USB cable of your RS232 converter is manually disconnected. If you do this, most drivers normally disconnect all handles to your serial port and .NET throws ObjectDisposedException.
Also check your power management settings on your USB port if USB-to-RS232 converter is used. Try to uncheck this option on USB device to which converter is connected.
SW bug in your code.
It's always advisable (especially if converter used) to try more types of converters just to be sure there is no problem in HW device/driver.
Update: So as Timmy was saying the connection was getting disposed by garbage collection. so i declared the object as a shared variable in the class
Shared Dim WithEvents serialPort as IO.Ports.SerialPort
and in the OnStart method i initiated it as a new Serial port and rocked on. has not throw any errors since garbage collection wont disposed of it. Hope this helps somebody having a similar issue.

VB.net lag across different machines

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

Converting Image VB.net

I have the following code
Public Sub ConvertImage(ByVal Filename As String, _
ByVal DesiredFormat As System.Drawing.Imaging.ImageFormat, _
ByVal NewFilename As String)
' Takes a filename and saves the file in a new format
Try
Dim imgFile As System.Drawing.Image = _
System.Drawing.Image.FromFile(Filename)
imgFile.Save(NewFilename, DesiredFormat)
Catch ex As Exception
Throw ex
End Try
End Sub
Private Sub btnPrintVC40_Click(sender As System.Object, e As System.EventArgs) Handles btnPrintVC40.Click
Dim SigName As String
Dim SigNameNew As String
SigName = "SELECT Signature FROM vw_Report_VehicleCheckFTA WHERE VCID = " & CStr(lRiskAssessID)
SigNameNew = SigName.PadLeft(SigName.Length - 4)
ConvertImage(SigName, _
System.Drawing.Imaging.ImageFormat.Jpeg, _
SigNameNew & ".jpeg")
runReport("SELECT * FROM vw_Report_VehicleCheckFTA WHERE VCID = " & CStr(lRiskAssessID), "FTAVehicleCheck2.rpt")
End Sub
Basically what this should do is convert a png image to jpeg, then launch a crystal report. Instead I get the following exception:
I just can't for the life of me figure out why.
SigName = "SELECT Signature FROM vw_Report_VehicleCheckFTA WHERE VCID = " & CStr(lRiskAssessID) ' lRiskAssessID is 3772 I guess
SigNameNew = SigName.PadLeft(SigName.Length - 4) 'SignameNew will become "SELECT Signature FROM vw_Report_VehicleCheckFTA WHERE VCID = 3772", PadLeft will actually do nothing at all
ConvertImage(SigName, _
System.Drawing.Imaging.ImageFormat.Jpeg, _
SigNameNew & ".jpeg")
Convert Image is called with Filename "SELECT Signature FROM vw_Report_VehicleCheckFTA WHERE VCID = 3772" and I guess that's not the real filename.
You should take a look on how to get data from your database, you can't just throw some string in the air to get it ;)

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.

Internal server error (500) httpwebrequest

System.Net.WebException: The remote
server returned an error: (500)
Internal Server Error. at
System.Net.HttpWebRequest.GetResponse()
at
refill.btnRequestRefill_Click(Object
sender, EventArgs e)
I get this error when trying to submit a form. Here is my code:
Protected Sub btnRequestRefill_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRequestRefill.Click
Try
Dim url As String = "www.domainname.com"
url += "lastName=" & LastName.Text
url += "&birthDate=" & Birthdate.Text
url += "&RxNumbers=" & RxNumber.Text
url += "&deliveryMethod=" & deliverymethod.SelectedValue
url += "&phone=" & PhoneNumber.Text
url += "&email=" & Email.Text
Dim myrequest As HttpWebRequest = TryCast(WebRequest.Create(url), HttpWebRequest)
Dim docresponse As WebResponse = myrequest.GetResponse()
Dim responsestream As Stream = docresponse.GetResponseStream()
Dim objXMLDoc As New XmlDocument()
Dim colElements As XmlNodeList
Dim colElements2 As XmlNodeList
Dim mywebclient As New WebClient()
Dim a As Object
Dim listingscount As Integer = 0
objXMLDoc.Load(responsestream)
colElements = objXMLDoc.GetElementsByTagName("script")
For Each objnode As XmlNode In colElements
Dim attCol As XmlAttributeCollection = objnode.Attributes
If objnode.Name = "script" Then
If attCol(0).Value = "false" Then
colElements2 = objXMLDoc.GetElementsByTagName("rxResponse")
For Each objnode2 As XmlNode In colElements2
Response.Write("<br/>" & objnode2.InnerText & "<br/>")
Next
Else
Response.Write("<br/>yay it when through<br/>")
Dim redir, mailto, mailfrom, subject, item, body, cc, bcc, message, html, template, usetemplate, testmode
subject = "Refill Submit - test"
usetemplate = False
Dim msg = Server.CreateObject("CDO.Message")
msg.subject = subject
msg.to = "name#domainname.com,name#domainname.com,name#domainname.com"
msg.from = "name#domainname.com"
For Each item In Request.Form
Select Case item
Case "redirect", "mailto", "cc", "bcc", "subject", "message", "template", "html", "testmode", "__EVENTTARGET", "__EVENTARGUMENT", "__VIEWSTATE", "__EVENTVALIDATION", "btnRequestRefill","__LASTFOCUS"
Case Else
If Not usetemplate Then
If item <> "mailfrom" Then body = body & item & ": " & Request.Form(item) & vbCrLf & vbCrLf
Else
body = Replace(body, "[$" & item & "$]", Replace(Request.Form(item), vbCrLf, "<br>"))
End If
End Select
Next
If usetemplate Then 'remove any leftover placeholders
Dim rx As New Regex("\[\$.*\$\]")
body = rx.Replace(body, "")
End If
If usetemplate And LCase(Request.Form("html")) = "yes" Then
msg.htmlbody = body
Else
msg.textbody = body
End If
msg.send()
msg = Nothing
End If
Else
Response.Write("<br/>" & "not script" & "<br/>")
End If
'Response.Write("<br/>" & objnode.Name & ": " & objnode.InnerText & "<br/>")
Next
Catch ex As Exception
Response.Write("<br/>" & ex.ToString & "<br/>")
End Try
End Su
I just wanted to make note that i was taking over this code from another developer. I found from the company that this was suppose to before that there was actually a missing querystring that was required by the service. by just adding url +="querystring=" & value it worked.