Error: Index and length must refer to a location within the string - vb.net

Im getting the following exception on vb.net. I have trouble solving this error:
Error 5: Index and length must refer to a location within the string.Parameter name: length.
here is my code :
Private Sub attemptedNumbersNew2(ByVal date_start As DateTime, ByVal date_end As DateTime, ByVal port As String, ByVal team As String)
Dim con As New ADODB.Connection
Dim recordS As New ADODB.Recordset
Dim sql As String = "some query...."
Try
con.Open(connectStringA)
recordS.Open(sql, con)
If recordS.EOF Then
Else
Do While Not recordS.EOF
Dim temp As String
If name4number.Contains(lastAttempted) Then
temp = name4number.Item(lastAttempted)
Else
temp = lastAttempted
End If
If attemptedNames.Equals("NONE") Or attemptedNames.Equals("") Then
attemptedNames = temp
ElseIf Not temp.Equals("") Then
attemptedNames = attemptedNames & " - " & temp
End If
If agentsHashOffered.Contains(temp & "_" & team) Then
agentsHashOffered.Item(temp & "_" & team) = agentsHashOffered.Item(temp & "_" & team) + 1
Else
agentsHashOffered.Add(temp & "_" & team, 1)
End If
If recordS.Fields(2).Value >= oldDate Then
If answeringNumber.Equals("NONE") Then
answeringNumber = recordS.Fields(4).Value
If answeringNumber.Substring(0, 1).Equals("9") Then
answeringNumber = answeringNumber.Substring(1, 10)
End If
callDuration = -1
End If
disconnectionTime = recordS.Fields(3).Value
Else
End If
If attempted.Equals("NONE") Then
attempted = recordS.Fields(4).Value
If attempted.Substring(0, 1).Equals("9") Then
attempted = attempted.Substring(1, 10)
End If
attemptedCount = attemptedCount + 1
lastAttempted = attempted
Else
temp = recordS.Fields(4).Value
If temp.Substring(0, 1).Equals("9") Then
temp = temp.Substring(1, 10)
End If
attempted = attempted & " - " & temp
attemptedCount = attemptedCount + 1
lastAttempted = temp
End If
recordS.MoveNext()
Loop
End If
con.Close()
con = Nothing
recordS = Nothing
Catch ex As Exception
MsgBox("Error #" & Err.Number & ": " & Err.Description)
End Try
End Sub
It was working fine the other day, but suddenly I started getting this error.
any helps are welcome
THANK YOU in Advance

Related

Working code fails when run as backgroundworker

I am developing a client app on my PC. I have several modules connected to my network. The modules are boards I have designed which act as servers. I want the client to do a scan of the network every 15 seconds to see if there have been any new servers added to the network and if so, log them into the MySQL database and to determine which of the servers already logged to the database as online. Ones in the database which are offline are shown on a treeview in red, online in green so if a board goes down, I can check if it has failed or the cable damaged or some other reason for being off.
OK, this is the sub that does the scan
Public Sub ScanModules()
Dim Mdc As ADODB.Command
Dim Sr As ADODB.Recordset
Dim check As String
Dim modsonline As Integer = 0
Dim l, a, b As Integer
Dim repdelay As Integer = 100
Dim result As Integer = 0
Dim myser As String
Dim scantime As String = Date.Today.Date & " at " & TimeOfDay.ToString("h:mm:ss")
Dim modtype As String
Dim serno As String
Dim ismod As Boolean
If My.Computer.Network.IsAvailable Then
' get the ARP table and parse it to see all IP and MAC addresses currently registered
Dim sCommand As String = "arp"
Dim sArgs As String = "-a"
Dim psi As System.Diagnostics.ProcessStartInfo = New System.Diagnostics.ProcessStartInfo(sCommand, sArgs)
psi.UseShellExecute = False
psi.RedirectStandardOutput = True
psi.CreateNoWindow = True
arptable = ""
Dim proc As System.Diagnostics.Process = System.Diagnostics.Process.Start(psi)
arptable = proc.StandardOutput.ReadToEnd
l = Len(arptable)
a = 90
b = 112
Mdc = New ADODB.Command
Mdc.let_ActiveConnection(DBCon)
Mdc.CommandType = ADODB.CommandTypeEnum.adCmdText
Mdc.CommandText = "SELECT * from machine"
Sr = Mdc.Execute
nummacs = Sr.RecordCount
' look for Baart modules in the ARP table - MAC will start ea and be all decimal numbers
Do While b < l
myip = RTrim(Mid(arptable, a, 15))
mymac = Mid(arptable, b, 17)
If VB.Left(mymac, 2) = "ea" Then
ismod = True
check = Mid(mymac, 4, 2) & Mid(mymac, 7, 2) & Mid(mymac, 10, 2) & Mid(mymac, 13, 2) & Mid(mymac, 16, 2)
For z = 1 To 10
If Asc(Mid(check, z, 1)) > 57 Then ismod = False
Next
If ismod Then
Cmd = New ADODB.Command
Mdc.let_ActiveConnection(DBCon)
Mdc.CommandType = ADODB.CommandTypeEnum.adCmdText
Mdc.CommandText = "SELECT * from modules WHERE macaddr = '" & mymac & "'"
Sr = Mdc.Execute
If Sr.RecordCount = 0 Then 'module is not in database, add it
EthMsg = ""
sendmsg("ENQ", myip)
If EthMsg = "ACK" Then ' if reply is not ACK then either not a Baart or not actually online
EthMsg = ""
modsonline = modsonline + 1
sendmsg("SER", myip)
serno = EthMsg
EthMsg = ""
sendmsg("TYP", myip)
modtype = EthMsg
EthMsg = ""
sendmsg("EOT", myip)
If EthMsg = "ACK" Then
Mdc.CommandText = "INSERT INTO modules (macaddr, serno, modtype, ipaddr, active, assigned) VALUES ('"
Mdc.CommandText = Mdc.CommandText & mymac & "','" & serno & "','" & modtype & "','" & myip & "', 1, 0 )"
Mdc.Execute()
Mdc.CommandText = "SELECT * from modules WHERE macaddr = '" & mymac & "'"
Sr = Mdc.Execute
End If
End If
Else
Mdc.CommandText = "UPDATE modules set ipaddr = '" & myip & "', active = '1' WHERE macaddr = '" & mymac & "'"
Sr = Mdc.Execute
End If
End If
End If
a = a + 58
b = b + 58
Loop
' now update the module treeview showing which modules are online by pinging them
Mdc.CommandText = "SELECT * from modules"
Sr = Mdc.Execute
If Sr.RecordCount > 0 Then
Sr.MoveFirst()
For a = 0 To Sr.RecordCount - 1
myip = Trim(Sr.Fields.Item("ipaddr").Value)
myser = Sr.Fields.Item("serno").Value
If My.Computer.Network.Ping(myip, 100) Then
Mdc.CommandText = "UPDATE modules set active = '1', lastol = '" & scantime & "' WHERE ipaddr = '" & myip & "'"
Mdc.Execute()
For Each n As TreeNode In frmMain.ModView.Nodes(0).Nodes
If n.Text = myser Then
n.ImageIndex = 6
n.SelectedImageIndex = 6
End If
Next
Else
Mdc.CommandText = "UPDATE modules set active = '0' WHERE ipaddr = '" & myip & "'"
Mdc.Execute()
For Each n As TreeNode In frmMain.ModView.Nodes(0).Nodes
If n.Text = myser Then
n.ImageIndex = 7
n.SelectedImageIndex = 7
End If
Next
End If
Sr.MoveNext()
Next
End If
End If
End Sub
I also have these two subs in my code
Private Sub ScanTimer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ScanTimer.Tick
'BgdScan.RunWorkerAsync()
Call ScanModules()
Application.DoEvents()
End Sub
Private Sub BgdScan_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BgdScan.DoWork
Call ScanModules()
Application.DoEvents()
End Sub
You will see in ScanTimer_Tick sub I have BgdScan.RunWorkerAsync() commented out so it does not run in the background and this works great. If I unplug a board, it turns red on the treeview within 15 seconds. If I plug it back in it turns green. But if I uncomment BgdScan.RunWorkerAsync() and comment out the next two lines, it should run in the background but it crashes out with an 'ArgumentOutOfRangeException was unhandled by user code' at the line For 'Each n As TreeNode In frmMain.ModView.Nodes(0).Nodes' 22 lines from the bottom of the ScanModules sub. The exception detail is;
System.ArgumentOutOfRangeException was unhandled by user code
Message="Specified argument was out of the range of valid values. Parameter name: index"
ParamName="index"
Source="System.Windows.Forms"
StackTrace:
at System.Windows.Forms.TreeNodeCollection.get_Item(Int32 index)
at BaartOLM.General.ScanModules() in C:\BaartOLM.VBNET\General.vb:line 291
at BaartOLM.frmMain.BgdScan_DoWork(Object sender, DoWorkEventArgs e) in C:\BaartOLM.VBNET\main.vb:line 631
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
InnerException:
I have never used backgroundworker before so this is new to me. Can anyone suggest why this code will run OK in the foreground but not in the background?
Thanks for your help, Steve.

First-chance exception at 0x761EC42D in foo.exe: Microsoft C++ exception: int at memory location 0x003ED1EC

Dim ColNames(7) As String
Dim Values(7) As Object
Dim now As DateTime = DateTime.Now()
ColNames(0) = "Int1"
ColNames(1) = "Int2"
ColNames(2) = "String1"
ColNames(3) = "String2"
ColNames(4) = "String3"
ColNames(5) = "String4"
ColNames(6) = "String5"
ColNames(7) = "String6"
Values(0) = intVar1
Values(1) = intVar2
Values(2) = strVar1
Values(3) = strVar2
Values(4) = strVar3
Values(5) = strVar4
Values(6) = strVar5
Values(7) = strVar6
Dim goodToInsert As Boolean = True
For i As Integer = 0 To 7
If Values(i) = Nothing OrElse Len(Values(i)) = 0 Then
goodToInsert = False
End If
Next
If goodToInsert Then
accessDatabase.InsertIntoTable("MyTable", ColNames, Values)
End If
This part of the code handles gathering data to insert into my access database.
Public Sub InsertIntoTable(ByRef TableName As String, ByRef ColumnName() As String, ByRef KeyValue() As Object)
'ColumnName and KeyValue need to have the same number of elements
'be careful when attemping to insert a value into the PrimaryKey Column as it may be of a type that cannot but manually changed
'INSERT NEW DATA INTO A TABLE
' INSERT INTO {tablename} ([{columnname1}], [{columnname2}], [{columnname3}], ...) VALUES ('{string}', {number}, {boolean}, ...), oledbconnection
Dim ColumnString As String = vbNullString
Dim KeyString As String = vbNullString
For i As Integer = 0 To ColumnName.GetUpperBound(0)
'build the column names part of the string
If i <> ColumnName.GetUpperBound(0) Then
ColumnString = ColumnString & "[" & ColumnName(i) & "], "
Else
ColumnString = ColumnString & "[" & ColumnName(i) & "]"
End If
'build the values part of the string
Dim TempValue As String = vbNullString
If KeyValue(i) <> Nothing Then
If KeyValue(i).GetType.ToString = "System.String" Then
TempValue = "'" & KeyValue(i) & "'"
Else
TempValue = KeyValue(i)
End If
If i <> KeyValue.GetUpperBound(0) Then
KeyString = KeyString & vbNullString & TempValue & ", "
Else
KeyString &= TempValue
End If
Else
Debug.Print("Nothing")
If i <> KeyValue.GetUpperBound(0) Then
KeyString &= ", "
End If
End If
Next
Dim con As New OleDbConnection
Dim da As New OleDbDataAdapter
Dim sql As New OleDbCommand
con.ConnectionString = Connection()
con.Open()
Dim commandText As String = "INSERT INTO " & TableName & " (" & ColumnString & ") VALUES (" & KeyString & ")"
Try
sql.Connection = con
sql.CommandText = commandText
da.InsertCommand = sql
da.InsertCommand.ExecuteNonQuery()
Catch ex As Exception
Debug.Print(ex.ToString)
End Try
con.Close()
End Sub
This is the InsertIntoTable function.
The function runs properly and inserts data into my table correctly, but in my debug output I keep noticing this error on every call to da.InsertCommand.ExecuteNonQuery():
First-chance exception at 0x761EC42D in 3024 Card Sorter.exe: Microsoft C++ exception: int at memory location 0x003ED1EC.
First-chance exception at 0x761EC42D in 3024 Card Sorter.exe: Microsoft C++ exception: int at memory location 0x003ED1EC.
I was able to use the Visual Studio debugger to narrow it down to ExecuteNonQuery() being where it occurs, but I'm having trouble understanding what it means, and how to go about resolving it. I've attempted changing my intVars to Strings with no luck to resolving the exception, and I'm also extremely curious why this isn't being caught by my Try...Catch.

SELECT Query WHERE multiple values from checkboxlist are used

I was wondering if it was possible to filter down data from a table using multiple values from a checkboxlist? (or any other way) I have a checkboxlist and a gridview and when you check on of the boxes it does show the right data in the gridview but the problem arises when I try to check multiple values. It seems to search for the first checked value and then ignores the rest. You'd think it'd be simple! Perhaps it is. Here is my attempt below.
CODE BEHIND
Imports System.Data
Imports System.Data.SqlClient
Partial Class Default2
Inherits System.Web.UI.Page
Dim strSQL As New System.Text.StringBuilder
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
Dim i As Integer, c As Integer = 0
Dim strParams As String = ""
For i = 0 To Me.CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
c += 1
If c = 1 Then
strParams = "(Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
Else
strParams &= " AND (Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
End If
End If
Next
strSQL.Append("SELECT Project.*")
strSQL.Append(" FROM Keyword INNER JOIN Project ON Keyword.ProjID = Project.ProjID")
strSQL.Append(" WHERE" & strParams)
FillGridView()
End If
End Sub
Private Sub FillGridView()
Dim strMyConn As String = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\FYPMS_DB.mdf;Integrated Security=True"
Using MyConn As New SqlClient.SqlConnection(strMyConn)
MyConn.Open()
Dim cmd As New SqlClient.SqlCommand(strSQL.ToString, MyConn)
cmd.Connection = MyConn
cmd.CommandType = CommandType.Text
Try
Using dr As SqlClient.SqlDataReader = cmd.ExecuteReader
Dim dt As New DataTable
dt.Load(dr)
Me.GridView1.DataSource = dt
Me.GridView1.DataBind()
End Using
If Me.GridView1.Visible = False Then Me.GridView1.Visible = True
Catch ex As Exception
Me.GridView1.Visible = False
End Try
End Using
End Sub
Protected Sub CheckBoxList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim i As Integer, c As Integer = 0
Dim strParams As String = ""
For i = 0 To Me.CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
c += 1
If c = 1 Then
strParams = "(Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
Else
strParams &= " AND (Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
End If
End If
Next
If c <> 0 Then
strSQL.Append("SELECT Project.*")
strSQL.Append(" FROM Keyword INNER JOIN Project ON Keyword.ProjID = Project.ProjID")
strSQL.Append(" WHERE" & strParams)
End If
End Sub
End Class
Refactor this section to create a WHERE IN statement so it checks to see if the value is found among any item checked
Before
Dim strParams As String = ""
For i = 0 To Me.CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
c += 1
If c = 1 Then
strParams = "(Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
Else
strParams &= " AND (Keyword.Keyword = '" & CheckBoxList1.Items(i).Text & "')"
End If
End If
Next
After
Dim params As StringBuilder = New StringBuilder()
For i = 0 To Me.CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
params.Append("'")
params.Append(CheckBoxList1.Items(i).Text)
If i < Me.CheckBoxList1.Items.Count Then
params.Append("',") // don't append a comma if it's the last item
End If
End If
Next
strSQL.Append("SELECT Project.* FROM Keyword INNER JOIN Project ON Keyword.ProjID = Project.ProjID WHERE Keyword.Keyword in (")
strSQL.Append(params.ToString()) // append comma delimited values that make up where in statement
strSQL.Append("')") // close where in statement
FillGridView()

Update multi table access db using vb.net

Can someone please help me with that?
My prob is that When i use dataAdapter.Update in this next construction i get a return value of zero (no line was updated but no reason or errors return).
The update sentense works when i run it using Access and other update requests works fine when i work on a single table.
Im Using:
vb.net \ visual studio 2012 \ access 2010 DB
I update the Data on my DataGridView and call the update function:
update command:
Private Function createGeneralUpdateStatement() As String
Return "UPDATE EntitysDataTbl INNER JOIN ManagersExtraDataTbl ON EntitysDataTbl.entityID = ManagersExtraDataTbl.managerID " + _
"SET EntitysDataTbl.entityUserName = [#EntitysDataTbl].entityUserName, " + _
"EntitysDataTbl.entityLastEntry = [#EntitysDataTbl].entityLastEntry, " + _
"ManagersExtraDataTbl.mPassword = [#ManagersExtraDataTbl].mPassword, " + _
"ManagersExtraDataTbl.workGroup = [#ManagersExtraDataTbl].workGroup, " + _
"ManagersExtraDataTbl.entityAccessType = [#ManagersExtraDataTbl].entityAccessType, " + _
"ManagersExtraDataTbl.mActive = [#ManagersExtraDataTbl].mActive" + _
"WHERE EntitysDataTbl.entityID= [#EntitysDataTbl].entityID"
End Function
The parameters are:
Dim parmList(2) As String
parmList(0) = "mPassword"
parmList(1) = "entityUserName"
and the update function is:
Public Function updateDB(ByVal updateCommand As String, ByVal parmList() As String, Optional ByVal insertCommand As String = "") As Boolean
Dim res As Boolean = False
SyncLock Me
Try
mainDataSet.EndInit()
mUpdateCommand = New OleDb.OleDbCommand(updateCommand, MyBase.getConnector)
For Each Str As String In parmList
If Not Str Is Nothing Then
If (Str.StartsWith("%")) Then
mUpdateCommand.Parameters.Add("#" & Str.Trim("%"), OleDb.OleDbType.Boolean, MAX_COL_LEN, Str.Trim("%"))
Else
mUpdateCommand.Parameters.Add("[#" & Str & "]", OleDb.OleDbType.VarChar, MAX_COL_LEN, Str)
End If
End If
Next
mDataAdapter.UpdateCommand = mUpdateCommand
If (Not insertCommand.Equals("")) Then
mInsertCommand = New OleDb.OleDbCommand(insertCommand, MyBase.getConnector)
For Each Str As String In parmList
If Not Str Is Nothing Then
'If Str.Equals("RuleIDNum") Then
' Continue For
'End If
If (Str.StartsWith("%")) Then
mInsertCommand.Parameters.Add("#" & Str.Trim("%"), OleDb.OleDbType.Boolean, MAX_COL_LEN, Str.Trim("%"))
Else
mInsertCommand.Parameters.Add("[#" & Str & "]", OleDb.OleDbType.VarChar, MAX_COL_LEN, Str)
End If
End If
Next
mDataAdapter.InsertCommand = mInsertCommand
End If
Dim i As Integer = mDataAdapter.Update(mainDataSet)
'ERROR - i = 0 => NO LINE WAS UPDATED!!!!
res = True
Catch ex As Exception
res = False
End Try
mDBWasUpdated = res
End SyncLock
Return res
End Function

Unable write to SQL from VBA/Excel using ADO

I'm using VBA for working with SQL database, Select commands forking fine, problem is with modification of dbase - insert, delete. If I using external application for work with DBase, everything is OK, thats mean - my privilegs is OK. On example Select is done successfully, rest not...
Thanks for your help.
JB
Public LinkID As ADODB.Connection
Public QueryID As ADODB.Recordset
Private Record() As String
Public Row As Long
Public NumRows As Long
Public Function connect(Optional server As String = "", Optional uid As String = "", Optional pwd As String = "", _
Optional dbname As String = "") As Boolean
Dim connStr As String
If (server = "") Then server = "DBServer"
If (uid = "") Then uid = "User1"
If (pwd = "") Then pwd = "1234"
If (dbname = "") Then dbname = "Database1"
If (uid = "") Then
connStr = "DRIVER={SQL Server};SERVER=" & server & ";Trusted_Connection=Yes;APP=Office 2007 App;DATABASE=" & dbname
Else
'connStr = "DRIVER={SQL Server};SERVER=" & server & ";UID=" & uid & ";PWD=" & pwd & ";APP=Office 2007 App;DATABASE=" & dbname
connStr = "Provider=SqlOleDb;Data Source=DBServer;Initial Catalog = Database1;UID=" & uid & ";PWD=" & pwd & ";Options=-1;"
End If
If (LinkID Is Nothing) Then
Set LinkID = New ADODB.Connection
On Error Resume Next
LinkID.Open connStr
On Error GoTo 0
If (LinkID.State = 0) Then
ErrorNo = Err.Number
ErrorTxt = Err.Description
End If
End If
connect = LinkID.State
End Function
Public Function query(Optional queryStr As String = "") As Boolean
If (queryStr = "") Then Exit Function
If Not (connect) Then Exit Function
If (QueryID Is Nothing) Then
Set QueryID = New ADODB.Recordset
ElseIf (QueryID.State) Then
free_result
End If
On Error Resume Next
QueryID.Open queryStr, LinkID, adOpenForwardOnly, adLockOptimistic, -1 ', adLockBatchOptimistic
On Error GoTo 0
Row = 0
If (QueryID.State = 0) Then
ErrorNo = Err.Number
ErrorTxt = Err.Description
End If
NumRows = count_records
query = QueryID.State
End Function
Public Sub free_result()
If Not (QueryID Is Nothing) Then
QueryID.Close
End If
End Sub
Public Function count_records() As Integer
count_records = 0
If Not (QueryID Is Nothing) Then
If (QueryID.State) Then
While (Not QueryID.EOF)
count_records = count_records + 1
QueryID.MoveNext
Wend
If (count_records) Then
QueryID.Requery
End If
End If
End If
End Function
Sub Test()
query "SELECT * FROM Table1 WHERE Empl = 'Tom'"
query "INSERT INTO Table1 (EMPL)Values ('Tod')"
query "DELETE FROM Table1 WHERE Empl = 'Tod'"
End Sub
RecordSet.Open is only used to open a cursor (select) not execute some DML. For this you can use Connection.Execute. The last can also be used to create a RecordSet.
See for example [http://msdn.microsoft.com/en-us/library/ms807027.aspx]