Code getting stuck in BackgroundWorker - vb.net

Am having a problem with a BackgroundWorker getting stuck.
have thrown in loads of console.writeline's to help try and narrow down where the issue is, but am getting nowhere fast.
I noticed when going back through the output, I have this message...
The thread 0x2d68 has exited with code 259 (0x103)
Can anyone tell me what that means?
EDIT - Below is my full code.
To give some background, this app is processing requested received from a website to deploy a virtual machine in a cloud environment.
It works fine for the first few items, but then it gets stuck inside the "BuildProgressCheck" BackgroundWorker.
It then stops processing any more items and the BuildProgressCheck Backgroundworker isbusy sticks at true.
Any help appriciated, I've been trying to solve this for a while now. :(
Thanks!
Imports MySql.Data.MySqlClient
Imports System
Imports System.IO
Imports System.Xml
Imports System.Net.Mail
Imports System.Text
Imports System.Diagnostics
Public Class Home
Public dbserver As String
Public dbusername As String
Public dbpassword As String
Public dbdatabase As String
Public appdebug As String
Public appconfig As String
Public jobcheckresult As String = "jobcheckresult"
Public buildchecktickid As Integer = 0
Public jobchecktickid As Integer = 0
Public new_vm_jobid As String
Public new_vm_state As String
Public new_vm_ipaddress As String
Public new_vm_macaddress As String
Public new_vm_hostname As String
Public new_vm_cpunumber As String
Public new_vm_cpuspeed As String
Public new_vm_memory As String
Public new_vm_netmask As String
Public new_vm_gateway As String
Public new_vm_templatename As String
Public new_vm_instancename1 As String
Public job_check_status As String
Public jobcheckstatusid As String
Public new_vm_success_internal_email As String
Public new_vm_fail_internal_email As String
Public new_vm_success_external_email As String
Public new_vm_processing_internal_email As String
Public internal_email_recipient As String
Public internal_email_sender As String
Public internal_mail_server As String
Public internal_mail_server_username As String
Public internal_mail_server_password As String
Public logentrytext As String
Public logdirectory As String = "C:\CloudPlatform\"
Public logpath As String = logdirectory & "dbcpman_log.txt"
Public logappend As Boolean = True
Public ccnl = ControlChars.NewLine
Public cpapiurl As String = "http://192.168.16.221:8081/client/api?"
Public cpapikey As String = "apiKey=YUsTgg_d6QB9KhdjYS6K314t9BZhL0B3T-DHR1vm8BrkF2pv2qqx698Vzb8O-srSOAKYa0nYB8qLQdXjaKHefQ"
Public buildcheckactive As Integer = 0 ' 0=false, 1=true '
Public buildprogresscheckactive As Integer = 0 ' 0=false, 1=true '
Public jobcheckactive As Integer = 0 ' 0=false, 1=true '
Public Sub login_Shown(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Shown
Control.CheckForIllegalCrossThreadCalls = False
Dim config As String = "cloudcommander.conf"
If System.IO.File.Exists(config) = True Then
Dim objReader As New System.IO.StreamReader(config)
appconfig = objReader.ReadToEnd
objReader.Close()
Dim configlines() As String = appconfig.Split(vbCrLf)
For Each line As String In configlines
' MessageBox.Show(configlines)
Next
dbserver = configlines(1)
dbserver = Replace(dbserver, "server=", "")
dbdatabase = configlines(2)
dbdatabase = Replace(dbdatabase, "database=", "")
dbusername = configlines(3)
dbusername = Replace(dbusername, "userid=", "")
dbpassword = configlines(4)
dbpassword = Replace(dbpassword, "password=", "")
Else
lblstatus.Text = "Configuration Error"""
MsgBox("Could not locate configuration file " & ControlChars.NewLine & ControlChars.NewLine & "This program may not work correctly :(")
End If
lblstatus.Text = "Configuration is fine - moving along..."
Dim cn As New MySqlConnection
cn.ConnectionString = "server=" & dbserver & "; userid=" & dbusername & "; password=" & dbpassword & "; database=" & dbdatabase & ";Convert Zero Datetime=True"
Dim jobcheck As New MySqlDataAdapter("Select * FROM dbcpman_jobs WHERE failed='false'", cn)
Dim jobcheck_table As New DataTable
jobcheck.Fill(jobcheck_table)
Dim row As DataRow
For Each row In jobcheck_table.Rows
Dim strDetail As String
strDetail = row("dbxid")
buildpendinglist.Items.Add(strDetail)
logentrytext = "[STARTUP] Found pending job for import: " & strDetail
Call dbcpman_log(logentrytext, logdirectory, logpath, logappend) ''''''Do some logging
Next row
Try
logentrytext = "[JOB-CALLBACK] API response: " & jobcheckresult
Call dbcpman_log(logentrytext, logdirectory, logpath, logappend) ''''''Do some logging
Catch ex As Exception
End Try
BuildWorkerTimer.Start()
BuildProgressCheckTimer.Start()
End Sub
Private Sub NewItemCheck_Tick(sender As Object, e As EventArgs) Handles BuildWorkerTimer.Tick
buildchecktickid = buildchecktickid + 1
countbuilds.Text = buildcheckactive
countjobs.Text = buildprogresscheckactive
If BuildWorker.IsBusy Then
Beep()
Else
BuildWorker.RunWorkerAsync()
End If
End Sub
Private Sub BuildProgressCheckTimer_Tick(sender As Object, e As EventArgs) Handles BuildProgressCheckTimer.Tick
Console.WriteLine("Timer 'BuildProgressCheckTimer'.... TICK!")
Dim bpc_busy_count As Integer = 0
If BuildProgressCheck.IsBusy Then
Beep()
bpc_busy_count = bpc_busy_count + 1
If bpc_busy_count > 4 Then
Beep()
Beep()
BuildProgressCheck.CancelAsync()
End If
Else
BuildProgressCheck.RunWorkerAsync()
End If
End Sub
Private Sub BuildWorker_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BuildWorker.DoWork
lblstatus.Text = "Checking for new requests"
buildcheckactive = 1
Dim cn As New MySqlConnection
cn.ConnectionString = "server=" & dbserver & "; userid=" & dbusername & "; password=" & dbpassword & "; database=" & dbdatabase & ";Convert Zero Datetime=True"
Dim vmcheck As New MySqlDataAdapter("Select * FROM dbcpman_vm WHERE deployrequired='true' ", cn)
Dim vmcheck_table As New DataTable
vmcheck.Fill(vmcheck_table)
Dim row As DataRow
row = vmcheck_table.Select("deployrequired = 'true'").FirstOrDefault()
If Not row Is Nothing Then
Dim new_vm_id As String = row.Item("id")
Dim new_vm_account As String = row.Item("account")
Dim new_vm_name As String = row.Item("name")
Dim new_vm_displayname As String = row.Item("displayname")
Dim new_vm_memory As String = row.Item("memory")
Dim new_vm_cpuspeed As String = row.Item("cpuspeed")
Dim new_vm_cpunumber As String = row.Item("cpunumber")
Dim new_vm_group As String = row.Item("vmgroup")
Dim new_vm_instancename As String = row.Item("instancename")
Dim new_vm_diskofferingid As String = row.Item("diskofferingid")
Dim new_vm_disksize As String = row.Item("customdisksize")
Dim new_vm_serviceofferingid As String = row.Item("serviceofferingid")
Dim new_vm_serviceofferingname As String = row.Item("serviceofferingname")
Dim new_vm_publicip As String = row.Item("publicip")
Dim new_vm_os As String = row.Item("OS")
Dim new_vm_templateid As String = row.Item("templateid")
Dim dbx_id As String = row.Item("dbx_id")
Dim new_job_status As String = "NEW"
dbx_id = dbx_id & new_vm_id
Try
Dim myCommand As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim SQL As String
myCommand.Connection = cn
cn.Open()
myAdapter.SelectCommand = myCommand
SQL = "UPDATE dbcpman_vm SET dbx_id = '" & dbx_id & "' WHERE id = '" & new_vm_id & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
cn.Close()
Catch ex As Exception
MessageBox.Show("ERROR3 " & ccnl & ccnl & ex.Message)
End Try
buildpendinglist.Items.Add(dbx_id)
Dim commandstring As String = "command=deployVirtualMachine" _
& "&ServiceOfferingId=" & new_vm_serviceofferingid _
& "&size=" & new_vm_disksize _
& "&templateId=" & new_vm_templateid _
& "&zoneid=1" _
& "&displayname=" & new_vm_displayname _
& "&name=" & new_vm_name _
& "&instancename=" & new_vm_instancename _
& "&internalname=" & new_vm_displayname
Dim fullapiurl = cpapiurl & commandstring
Try
Dim myCommand As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim SQL As String
myCommand.Connection = cn
cn.Open()
myAdapter.SelectCommand = myCommand
SQL = "UPDATE dbcpman_vm SET deployrequired = 'false' WHERE id = '" & new_vm_id & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
cn.Close()
Catch ex As Exception
MessageBox.Show("ERROR2 " & ccnl & ccnl & ex.Message)
End Try
Try
Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString(fullapiurl)
Dim doc As New System.Xml.XmlDocument
doc.LoadXml(result)
Dim new_vm_jobidxml = doc.GetElementsByTagName("jobid")
For Each item As System.Xml.XmlElement In new_vm_jobidxml
new_vm_jobid = item.ChildNodes(0).InnerText()
Dim myCommand As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim SQL As String
myCommand.Connection = cn
cn.Open()
myAdapter.SelectCommand = myCommand
SQL = "UPDATE dbcpman_vm SET deploy_jobid = '" & new_vm_jobid & "' WHERE id = '" & new_vm_id & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
SQL = "UPDATE dbcpman_vm SET deploycompleted = 'false' WHERE id = '" & new_vm_id & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
SQL = "INSERT into dbcpman_jobs(jobid, status, dbxid) VALUES ('" & new_vm_jobid & "','" & new_job_status & "','" & dbx_id & "')"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
cn.Close()
'MessageBox.Show("ADDED ITEM TO JOBS")
Next
Catch ex As Exception
MessageBox.Show("ERROR1 " & ccnl & ccnl & ex.Message)
End Try
End If
new_vm_jobid = ""
new_vm_state = ""
new_vm_ipaddress = ""
new_vm_macaddress = ""
new_vm_hostname = ""
new_vm_cpunumber = ""
new_vm_cpuspeed = ""
new_vm_memory = ""
new_vm_netmask = ""
new_vm_gateway = ""
new_vm_templatename = ""
new_vm_instancename1 = ""
buildcheckactive = 0
End Sub
Private Sub BuildProgressCheck_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles BuildProgressCheck.DoWork
Dim i As Integer
For i = 0 To buildpendinglist.Items.Count - 1
Dim cn As New MySqlConnection
cn.ConnectionString = "server=" & dbserver & "; userid=" & dbusername & "; password=" & dbpassword & "; database=" & dbdatabase & ";Convert Zero Datetime=True"
Dim jobcheck As New MySqlDataAdapter("Select * FROM dbcpman_jobs WHERE dbxid='" & buildpendinglist.Items(i) & "'", cn)
Dim jobcheck_table As New DataTable
jobcheck.Fill(jobcheck_table)
Dim jobrow As DataRow
jobrow = jobcheck_table.Select("failed = 'false'").FirstOrDefault()
If Not jobrow Is Nothing Then
Dim job_id As String = jobrow.Item("id")
Dim job_jobid As String = jobrow.Item("jobid")
Dim job_status As String = jobrow.Item("status")
Dim job_dbxid As String = jobrow.Item("dbxid")
Dim jobcommand As String = "command=queryAsyncJobResult&jobId=" & job_jobid
Dim fulljobapicheckurl = cpapiurl & jobcommand
Try
Dim jobapicall As New System.Net.WebClient
jobcheckresult = jobapicall.DownloadString(fulljobapicheckurl)
Catch ex As Exception
Console.WriteLine("Error 'DBX-Err-1' - Error during API call")
End Try
If jobcheckresult.Contains("<jobstatus>1</jobstatus>") Then ''If true, job has completed
Console.WriteLine(job_dbxid & "Is completed")
Dim doc As New System.Xml.XmlDocument
doc.LoadXml(jobcheckresult) ''api_result contains xml returned from a http request.
Try
Console.WriteLine("Entering XML Parse...")
If doc.GetElementsByTagName("virtualmachine") IsNot Nothing Then
Dim elem As XmlNodeList = doc.GetElementsByTagName("virtualmachine").Item(0).ChildNodes
For Each item As XmlNode In elem
If item.Name.Equals("state") Then
new_vm_state += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("hostname") Then
new_vm_hostname += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("templatename") Then
new_vm_templatename += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("cpunumber") Then
new_vm_cpunumber += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("cpuspeed") Then
new_vm_cpuspeed += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("memory") Then
new_vm_memory += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("nic") Then
new_vm_netmask += ((item.ChildNodes.Item(3).InnerText.ToString()) + Environment.NewLine)
new_vm_gateway += ((item.ChildNodes.Item(4).InnerText.ToString()) + Environment.NewLine)
new_vm_ipaddress += ((item.ChildNodes.Item(5).InnerText.ToString()) + Environment.NewLine)
new_vm_macaddress += ((item.ChildNodes.Item(11).InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("instancename") Then
new_vm_instancename1 += ((item.InnerText.ToString()) + Environment.NewLine)
End If
Console.WriteLine("Finished XML parse")
Next
End If
Catch ex As Exception
Console.WriteLine("Error 'DBX-Err-2' - Error parsing returned XML string")
End Try
new_vm_macaddress = new_vm_macaddress.ToUpper
Console.WriteLine("Replacing chars from int IP")
Dim privateip As String = new_vm_ipaddress.Replace(" ", "").ToString
Dim publicip As String = privateip.Replace("172.16.11.", "196.15.17.")
Console.WriteLine("IP formatted correctly")
Try
Console.WriteLine("Entering SQL Try...")
Dim myCommand As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim SQL As String
myCommand.Connection = cn
cn.Open()
myAdapter.SelectCommand = myCommand
SQL = "DELETE FROM dbcpman_jobs WHERE jobid = '" & job_jobid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
Console.WriteLine("removed job from dbcpman_jobs")
SQL = "UPDATE dbcpman_vm SET deployresponse = '" & jobcheckresult & "' WHERE dbx_id = '" & job_dbxid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
Console.WriteLine("updated deployresponse in dbcpman_vm")
SQL = "UPDATE dbcpman_vm SET macaddress = '" & new_vm_macaddress & "' WHERE dbx_id = '" & job_dbxid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
Console.WriteLine("Updated macaddress in dbcpman_vm")
SQL = "UPDATE dbcpman_vm SET publicip = '" & publicip & "' WHERE dbx_id = '" & job_dbxid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
Console.WriteLine("updated publicIP in dbcpman_vm")
SQL = "UPDATE dbcpman_vm SET privateip = '" & privateip & "' WHERE dbx_id = '" & job_dbxid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
Console.WriteLine("updated privateIP in dbcpman_vm")
cn.Close()
Console.WriteLine("DB connection closed")
Dim new_vm_username As String = "clouduser"
Dim new_vm_password As String = GeneratePassword(7)
Console.WriteLine("clouduser password generated")
new_vm_password = new_vm_password & "oX7" ''''will remove this once generator can ensure complex passwords
System.Threading.Thread.Sleep(1000)
Dim new_vm_support_username As String = "dbxsupport"
Dim new_vm_support_password As String = GenerateSupportPassword(7)
Console.WriteLine("dbxsupport password generated")
new_vm_support_password = new_vm_support_password & "Kw3" ''''will remove this once generator can ensure complex passwords
cn.Open()
Console.WriteLine("Database connection opened")
myAdapter.SelectCommand = myCommand
SQL = "INSERT into dbcpman_credentials(username1, username2, password1, password2, type, link) VALUES ('" & new_vm_username & "','" & new_vm_support_username & "','" & new_vm_password & "','" & new_vm_support_password & "','Server root logon','" & job_dbxid & "')"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
Console.WriteLine("Saved credentials to dbcpman_credentials")
SQL = "INSERT into dbcpman_vm_boot(dbxid, ip, macaddress, hostname) VALUES ('" & job_dbxid & "','" & new_vm_ipaddress & "','" & new_vm_macaddress & "','" & job_dbxid & "')"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
Console.WriteLine("added VM tags to dbcpman_vm_boot")
cn.Close()
Console.WriteLine("Closed SQL connection")
Try ''''add monitoring for this host
Console.WriteLine("3 - Adding monitoring for " & job_dbxid)
Dim monitorurl As String = "http://192.168.16.32/addhost.php?hostname=" & job_dbxid & "&ipaddr=" & publicip
Dim webClient As New System.Net.WebClient
Dim monresult As String = webClient.DownloadString(monitorurl)
Console.WriteLine("Request sent to add monitoring")
If monresult = "SUCCESS" Then
Console.WriteLine("Monitoring added")
Else
Console.WriteLine("Unable to add monitoring")
End If
Catch ex As Exception
Console.WriteLine("Error 'DBX-Err-3' - Error adding monitoring")
End Try
buildcompletedlist.Items.Add(buildpendinglist.Items(i))
Console.WriteLine("Item removed from pending list")
buildpendinglist.Items.Remove(buildpendinglist.Items(i))
Console.WriteLine("Item added to complete list")
Catch ex As Exception
MessageBox.Show("ERROR- C " & ccnl & ccnl & ex.Message)
End Try
ElseIf jobcheckresult.Contains("<jobstatus>0</jobstatus>") Then ''If true, job is still pending
Console.WriteLine("Checking on pending job " & buildpendinglist.Items(i) & "...")
ElseIf jobcheckresult.Contains("<jobstatus>2</jobstatus>") Then ''If true, job has failed
Try
Console.WriteLine("An item has failed")
Dim myCommand As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim SQL As String
myCommand.Connection = cn
cn.Open()
myAdapter.SelectCommand = myCommand
SQL = "UPDATE dbcpman_jobs SET failed = 'true' WHERE jobid = '" & job_jobid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
Console.WriteLine("updated Failed in dbcpman_jobs")
cn.Close()
buildfailedlist.Items.Add(buildpendinglist.Items(i))
Console.WriteLine("Item remove from pending list")
buildpendinglist.Items.Remove(buildpendinglist.Items(i))
Console.WriteLine("Item added to failed list")
Try
Console.WriteLine("Trying to send email notifying support of a failure...")
Dim Errorbody As String = "Hi, " & ccnl & ccnl & "CloudCommander encountered a problem whilst deploying a VM and attention is required." & _
ccnl & ""
Dim SmtpServer As New SmtpClient()
Dim mail As New MailMessage()
SmtpServer.Credentials = New _
Net.NetworkCredential(internal_mail_server_username, internal_mail_server_password)
SmtpServer.Port = 25
SmtpServer.Host = internal_mail_server
mail = New MailMessage()
mail.From = New MailAddress("autoattendant#cloud.net")
mail.To.Add("support#cloud.net")
mail.Subject = "[CLOUDFAIL] A cloud server has failed to deploy"
mail.Body = Errorbody
SmtpServer.Send(mail)
Console.WriteLine("Mail sent.")
Catch ex As Exception
Console.WriteLine("Mail failed to send.")
End Try
Catch ex As Exception
End Try
End If
End If
Console.WriteLine("HEADING FOR THE NEXT ITEM")
Console.WriteLine("###################################################")
Next
buildprogresscheckactive = 0
Console.WriteLine("Done with async jobcheck for this pass")
End Sub
Private Sub JobWorker_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles JobWorker.DoWork
End Sub
Private Sub buildpendinglist_SelectedIndexChanged(sender As Object, e As EventArgs) Handles buildpendinglist.DoubleClick
ItemDetails.Show()
End Sub

The thread ... has exited with code 259 (0x103)
This is a known bug in VS2013, the feedback report is here. It doesn't mean anything and the bug is benign, it doesn't affect the way your BackgroundWorker executes. The bug is fixed, it is going to make it to your machine some day. Don't know when.

Related

How to edit and delete rows of a database using ASP?

I currently have a website that displays all the data within the database
Dim dcSQL As New SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("College").ConnectionString)
Dim dbAdapt As New System.Data.SqlClient.SqlDataAdapter()
Dim cmd As New SqlCommand("SELECT * FROM [College].[dbo].[Class]", dcSQL)
dbAdapt.SelectCommand = cmd
Dim ds As New DataSet
dbAdapt.Fill(ds)
If dbAdapt IsNot Nothing Then
gvStudents0.DataSource = ds.Tables(0)
gvStudents0.DataBind()
End If
Catch ex As Exception
End Try
End Sub'
But I want to create/edit and delete the database, I am aware of how to do this in EF but I am currently not aware in SQL, can someone help?
The following snippet is from SqlCommand.Parameters Property .
Updating
Dim commandText As String = _
"UPDATE Sales.Store SET Demographics = #demographics " _
& "WHERE CustomerID = #ID;"
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(commandText, connection)
' Add CustomerID parameter for WHERE clause.
command.Parameters.Add("#ID", SqlDbType.Int)
command.Parameters("#ID").Value = customerID
' Use AddWithValue to assign Demographics.
' SQL Server will implicitly convert strings into XML.
command.Parameters.AddWithValue("#demographics", demoXml)
Try
connection.Open()
Dim rowsAffected As Integer = command.ExecuteNonQuery()
Console.WriteLine("RowsAffected: {0}", rowsAffected)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Using
Deleting
For deleting the command could be as follows.
Dim commandText As String = _
"DELETE FROM Sales.Store WHERE CustomerID = #ID;"
(...)
command.Parameters.Add("#CustomerID ", SqlDbType.Int).Value = xxx;
Inserting
For inserting the sql will be something like the following
Dim commandText As String = _
"INSERT INTO tablename(column1,column2,column3)" _
& " VALUES(#column1,#column2,#column3);"
and then
command.Parameters.Add("#column1", SqlDbType.Int).Value = x;
command.Parameters.Add("#column2", SqlDbType.Int).Value = y;
command.Parameters.Add("#column3", SqlDbType.Int).Value = z;
or
command.Parameters.AddWithValue("#column1", x);
command.Parameters.AddWithValue("#column2", y);
command.Parameters.AddWithValue("#column3", z)
Please note that this is not ASP.NET specific. A console app could use this code as well.
You can use this class that I make and don’t care about SQL (in some cases).
You can just pas lists (Of String) as parameter and the methods do the tasks.
Imports System.Data.SqlClient
Friend Class SqlDB
Friend Property _SConessione As String = ""
Private _NomeDB As String = ""
Private _SQLConnection As SqlConnection
Private _SQLCommand As SqlCommand
Private _SQLAdapter As SqlDataAdapter
Private _SQLReader As SqlDataReader
Friend Enum Version
SQL_SERV_2005 = 90
SQL_SERV_2008 = 100
SQL_SERV_2012 = 110
End Enum
Friend Structure Inputs
Const _CHAR As String = "CHAR"
Const _VARCHAR As String = "VARCHAR"
Const _TEXT As String = "TEXT"
Const _NCHAR As String = "NCHAR"
Const _NVARCHAR As String = "NVARCHAR"
Const _NTEXT As String = "NTEXT"
Const _BIT As String = "BIT"
Const _BINARY As String = "BINARY"
Const _VARBINARY As String = "VARBINARY"
Const _IMAGE As String = "IMAGE"
Const _TINYINT As String = "TINYINT"
Const _SMALLINT As String = "SMALLINT"
Const _BIGINT As String = "BIGINT"
Const _DECIMAL As String = "DECIMAL(10,2)"
Const _NUMERIC As String = "NUMERIC(10)"
Const _FLOAT As String = "FLOAT"
Const _DATE As String = "DATE"
Const _DATETIME As String = "DATETIME"
End Structure
Friend Structure NULLS
Const NULL = "NULL"
Const NOT_NULL = "NOT NULL"
End Structure
Friend Structure Cols
Dim Nome As String
Dim TInput As String
Dim Length As Integer
Dim Null As String
End Structure
Private _Versione As Version = Version.SQL_SERV_2008
Friend Function SqlDate(dateStr As String) As String
If IsDate(dateStr) Then
Dim sDate As String = ""
dateStr = CDate(dateStr).ToShortDateString
sDate = " CONVERT(DATE, '" & dateStr & "', 0) "
Return sDate
Else
Throw New Exception("Formato data non valido")
End If
Return ""
End Function
Friend Property Versione As Version
Get
Return _Versione
End Get
Set(value As Version)
_Versione = value
End Set
End Property
Friend Enum TypeIndex
CLUSTER = 0
NONCOLUSTER = 1
End Enum
Friend Sub New(ByVal ConString As String,
ByVal VersionServer As Version)
Try
Versione = VersionServer
If ConString.Length > 0 Then
_SConessione = ConString
End If
Catch ex As Exception
#If DEBUG Then
Debug.WriteLine(ex.ToString)
#End If
End Try
End Sub
Friend Sub New(ByVal ConString As String)
Try
Versione = _Versione
If ConString.Length > 0 Then
_SConessione = ConString
End If
Catch ex As Exception
#If DEBUG Then
Debug.WriteLine(ex.ToString)
#End If
End Try
End Sub
Friend Function ExecuteRestore(Optional ByVal pathBackup As String = "", Optional NameDb As String = "") As Boolean
Dim res As Boolean = False
If NameDb.Length > 0 Then _NomeDB = NameDb
If _NomeDB.Length = 0 Then
Debug.WriteLine("Set the name of DB")
Return False
End If
Dim Sql = " USE [master]; " & vbCrLf
Sql &= " RESTORE DATABASE [" & _NomeDB & "]" & vbCrLf
Sql &= " FROM DISK = '" & pathBackup & "'" & vbCrLf
Sql &= " WITH FILE = 1, NOUNLOAD, REPLACE" & vbCrLf '
Try
Using SQLConnection = New SqlConnection(_SConessione)
Open(SQLConnection)
Dim command As New SqlCommand(Sql, SQLConnection)
res = CBool(command.ExecuteNonQuery())
res = True
End Using
Catch ex As Exception
#If DEBUG Then
Debug.WriteLine(ex.ToString)
#End If
End Try
Return res
End Function
Friend Function ExecuteQuery(sql As String) As Boolean
Dim res As Boolean = False
If sql.Length > 0 Then
sql = "USE [" & _NomeDB & "]; " & vbCrLf & sql
End If
Try
Using SQLConnection = New SqlConnection(_SConessione)
Open(SQLConnection)
Dim command As New SqlCommand(sql, SQLConnection)
command.ExecuteNonQuery()
End Using
Return True
Catch ex As Exception
#If DEBUG Then
Debug.WriteLine(ex.ToString)
#End If
End Try
Return res
End Function
Friend Function ReadTheFirstResult(sql As String) As Object
Dim sRet As Object = ""
If sql.Length > 0 Then
sql = "USE [" & _NomeDB & "]; " & vbCrLf & sql
End If
Try
Dim SQLConnection = New SqlConnection(_SConessione)
Open(SQLConnection)
Dim command As New SqlCommand(sql, SQLConnection)
Dim reader As SqlDataReader = command.ExecuteReader()
While reader.Read
sRet = reader(0)
Exit While
End While
Catch ex As SqlException
#If DEBUG Then
Debug.WriteLine(ex.ToString)
#End If
End Try
Return sRet
End Function
Friend Function GetDataAsDataReader(Sql As String, Optional ByRef RowsCount As Integer = -1) As SqlDataReader
Dim reader As SqlDataReader = Nothing
If Sql.Length > 0 Then
Sql = "USE [" & _NomeDB & "]; " & vbCrLf & Sql
End If
Try
Dim SQLConnection = New SqlConnection(_SConessione)
Open(SQLConnection)
If RowsCount > -1 Then
Dim DtTable As New DataTable
Dim mSqlAdapter As New SqlClient.SqlDataAdapter With {
.SelectCommand = New SqlCommand(Sql, SQLConnection)
}
mSqlAdapter.Fill(DtTable)
RowsCount = DtTable.Rows.Count
End If
Dim command As New SqlCommand(Sql, SQLConnection)
reader = command.ExecuteReader()
Catch ex As SqlException
#If DEBUG Then
Debug.WriteLine(ex.ToString)
#End If
End Try
Return reader
End Function
Friend Function CheckOrCreateDB(ByVal dbName As String) As Boolean
Try
Dim query As StringBuilder = New StringBuilder
query.Append(" USE [master]; ")
query.Append("IF NOT EXISTS(SELECT * FROM sys.databases Where name = '" & dbName & "') ")
query.Append(" CREATE DATABASE [" & dbName & "] ")
query.Append(" ALTER DATABASE [" & dbName & "] SET COMPATIBILITY_LEVEL = " & Versione & " ;")
query.Append(" ALTER DATABASE [" & dbName & "] SET READ_WRITE ;")
query.Append(" ALTER DATABASE [" & dbName & "] SET MULTI_USER ;")
Using SQLConnection = New SqlConnection(_SConessione)
Open(SQLConnection)
Dim command As New SqlCommand(query.ToString, SQLConnection)
command.ExecuteNonQuery()
_NomeDB = dbName
End Using
Return True
Catch ex As Exception
#If DEBUG Then
Debug.WriteLine(ex.ToString)
#End If
_NomeDB = ""
Return False
End Try
End Function
Friend Function CheckOrCreateTable(ByVal tableName As String, ByVal columns As List(Of Cols)) As Boolean
Try
If _NomeDB IsNot Nothing AndAlso _NomeDB.Length > 0 Then
Dim query As StringBuilder = New StringBuilder
query.Append(" USE [" & _NomeDB & "]; ")
query.Append(" IF NOT EXISTS ( SELECT * FROM sys.tables WHERE name = '" & tableName & "' ) ")
query.Append(" CREATE TABLE " & tableName & " ")
query.Append(" ( IndexRow INT IDENTITY(1,1) NOT NULL ); ")
Using SQLConnection = New SqlConnection(_SConessione)
Open(SQLConnection)
Dim command As New SqlCommand(query.ToString, SQLConnection)
command.ExecuteNonQuery()
End Using
query.Clear()
If columns IsNot Nothing AndAlso columns.Count > 0 Then
For i As Integer = 0 To columns.Count - 1
Dim TipoInput As String = columns(i).TInput & " "
If columns(i).Length > 0 Then
CreateColumn(tableName, columns(i).Nome, TipoInput, columns(i).Null, CStr(columns(i).Length))
Else
CreateColumn(tableName, columns(i).Nome, TipoInput, columns(i).Null)
End If
Next
End If
Return True
End If
Catch ex As Exception
#If DEBUG Then
Debug.WriteLine(ex.ToString)
#End If
End Try
Return False
End Function
Friend Function CreateColumn(ByVal tableName As String,
ByVal columnName As String,
ByVal TipoInput As String,
ByVal nullOrNot As String,
Optional ByVal Lunghezza As String = "-1") As Integer
Dim i As Integer = 0
Try
Dim mTipoInput As String = TipoInput
If CInt(Lunghezza) > -1 Then mTipoInput = mTipoInput & "(" & Lunghezza & ") "
Dim query As StringBuilder = New StringBuilder
query.Append(" USE [" & _NomeDB & "]; ")
query.Append(" IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID('" & tableName & "') AND name = '" & columnName & "' )")
query.Append(" ALTER TABLE " & tableName)
query.Append(" ADD " & columnName & " " & mTipoInput & " " & nullOrNot)
Using SQLConnection = New SqlConnection(_SConessione)
Open(SQLConnection)
Dim command As New SqlCommand(query.ToString, SQLConnection)
i = command.ExecuteNonQuery()
End Using
Catch ex As Exception
#If DEBUG Then
Debug.WriteLine(ex.ToString)
#End If
End Try
Return i
End Function
Friend Function CheckOrCreateColumn(ByVal tableName As String,
ByVal columnName As String,
Optional ByVal inputType As String = Inputs._VARCHAR,
Optional ByVal nullOrNot As String = "NULL",
Optional ByVal Lunghezza As String = "-1") As Integer
Dim i As Integer = 0
Try
Dim mTipoInput As String = inputType
If CInt(Lunghezza) > -1 Then mTipoInput = mTipoInput & "(" & Lunghezza & ") "
Dim query As StringBuilder = New StringBuilder
query.Append(" USE [" & _NomeDB & "]; ")
query.Append(" IF NOT EXISTS (SELECT * FROM syscolumns WHERE id = OBJECT_ID('" & tableName & "') AND name = '" & columnName & "' )")
query.Append(" ALTER TABLE " & tableName)
query.Append(" ADD " & columnName & " " & mTipoInput & " " & nullOrNot)
Using SQLConnection = New SqlConnection(_SConessione)
Open(SQLConnection)
Dim command As New SqlCommand(query.ToString, SQLConnection)
i = command.ExecuteNonQuery()
End Using
Catch ex As Exception
#If DEBUG Then
Debug.WriteLine(ex.ToString)
#End If
End Try
Return i
End Function
Friend Function CheckOrCreateIndex(tipo As TypeIndex,
indexName As String,
tableName As String,
columnsIndexes() As String,
Optional includedColumns() As String = Nothing) As String
Dim res As String = ""
Try
' CREATE INDEX IX_TableName_Col1
' ON dbo.TableName
' (column_1)
If columnsIndexes.Length > 0 Then
Dim query As StringBuilder = New StringBuilder
query.Append(" USE [" & _NomeDB & "]; ")
query.Append(" IF NOT EXISTS (SELECT name FROM sys.indexes WHERE name = '" & indexName & "')")
Select Case tipo
Case TypeIndex.CLUSTER
query.Append(" CREATE CLUSTERED INDEX " & indexName)
Case TypeIndex.NONCOLUSTER
query.Append(" CREATE NONCLUSTERED INDEX " & indexName)
End Select
query.Append(" ON [" & tableName & "] (" & JoinParams(columnsIndexes, False).Trim & ")")
If includedColumns IsNot Nothing AndAlso includedColumns.Length > 0 Then
query.Append(" Include (" & JoinParams(includedColumns, False) & ")")
End If
Using SQLConnection = New SqlConnection(_SConessione)
Open(SQLConnection)
Dim command As New SqlCommand(query.ToString, SQLConnection)
command.ExecuteNonQuery()
res = indexName
End Using
End If
Catch ex As Exception
#If DEBUG Then
Debug.WriteLine(ex.ToString)
'Debugger.Break()
#End If
End Try
Return res
End Function
Friend Function InsertInto(tableName As String, listOfCols As List(Of String), listOfValues As List(Of String)) As Boolean
Try
Dim Sql As String = " USE [" & _NomeDB & "]; "
Sql &= " INSERT INTO " & tableName
If listOfCols.Count > 0 AndAlso listOfValues.Count > 0 Then
Sql &= " (" & Join(listOfCols.ToArray, ",") & ")"
Sql &= " VALUES (" & JoinParams(listOfValues.ToArray) & ")"
Using SQLConnection = New SqlConnection(_SConessione)
Open(SQLConnection)
Dim command As New SqlCommand(Sql, SQLConnection)
command.ExecuteNonQuery()
End Using
Return True
End If
Catch ex As Exception
#If DEBUG Then
Console.WriteLine(ex.ToString)
'Stop
#End If
End Try
Return False
End Function
Friend Function UpdateInto(tableName As String, listOfCols As List(Of String), listOfValues As List(Of String), WhereClausola As String) As Integer
Dim ret As Integer = 0
Try
Dim Sql As String = " USE [" & _NomeDB & "]; "
Sql &= " UPDATE " & tableName & " SET "
If listOfCols.Count > 0 AndAlso listOfValues.Count > 0 Then
If listOfCols.Count > 0 AndAlso listOfValues.Count > 0 Then
' UPDATE Customers
'SET
'ContactName ='Alfred Schmidt',
'City ='Hamburg'
'WHERE CustomerName ='Alfreds Futterkiste';
For i As Integer = 0 To listOfCols.Count - 1
Sql &= " " & listOfCols(i) & "=" & CStr(IIf(listOfValues(i) IsNot Nothing, listOfValues(i), "NULL")) & CStr(IIf(i < listOfCols.Count - 1, ",", ""))
Next
If WhereClausola IsNot Nothing AndAlso WhereClausola.Length > 0 Then
WhereClausola = WhereClausola.ToLower.Replace("where", " ")
Sql &= " WHERE " & WhereClausola
Using SQLConnection = New SqlConnection(_SConessione)
Open(SQLConnection)
Dim command As New SqlCommand(Sql, SQLConnection)
ret = command.ExecuteNonQuery()
End Using
End If
End If
End If
Return ret
Catch ex As Exception
#If DEBUG Then
Console.WriteLine(ex.ToString)
'Stop
#End If
End Try
Return ret
End Function
Private Function JoinParams(ByVal params() As String, Optional ByVal UseVbcrlf As Boolean = True) As String
Dim s As String = ""
Dim mVbCrlf As String = CStr(IIf(UseVbcrlf, vbCrLf, " "))
For i As Integer = 0 To params.Length - 1
If params(i) IsNot Nothing Then
If i = params.Length - 1 Then
s &= params(i) & " " & mVbCrlf
Else
s &= params(i) & ", " & mVbCrlf
End If
End If
Next
Return s
End Function
Friend Sub Open(sqlConn As SqlConnection)
Try
_SQLConnection = sqlConn
Select Case sqlConn.State
Case <> ConnectionState.Connecting
sqlConn.Close()
sqlConn.ConnectionString = _SConessione
sqlConn.Open()
End Select
Catch ex As Exception
End Try
End Sub
Friend Sub Close()
Try
If _SQLConnection IsNot Nothing Then
_SQLConnection.Close()
End If
Catch ex As Exception
Debug.WriteLine(ex.ToString)
End Try
End Sub
End Class
Module SQLUtil
Function InLIKE(s As String) As String
'%email pippo%
If s IsNot Nothing AndAlso s.Length > 0 Then
Return "%" & s & "%"
End If
Return "%%"
End Function
Function InApice(value As String) As String
If value Is Nothing Then Return "''"
If value.Length = 0 Then Return "''"
Dim appice As String = "'" '"`"
value = value.Replace("'", "''")
Return " " & appice & value & appice & " "
End Function
Function ToDate(dateStr As String) As String
If IsDate(dateStr) Then
Dim sDate As String = CDate(dateStr).ToString
Return sDate
End If
Return dateStr
End Function
Function ToDbDate(dateStr As String) As String
dateStr = New Date(dateStr)
If IsDate(dateStr) Then
Dim mDate As Date = CDate(dateStr)
Dim anno As Integer = mDate.Year
Dim mese As Integer = mDate.Month
Dim giorno As Integer = mDate.Day
Dim ora As Integer = mDate.Hour
Dim minuto As Integer = mDate.Minute
If Not IsNumeric(anno) Then anno = 0
If Not IsNumeric(mese) Then mese = 0
If Not IsNumeric(giorno) Then giorno = 0
If Not IsNumeric(ora) Then ora = 0
If Not IsNumeric(minuto) Then minuto = 0
anno = Strings.Format(anno, "0000")
mese = Strings.Format(mese, "00")
giorno = Strings.Format(giorno, "00")
ora = Strings.Format(ora, "00")
minuto = Strings.Format(minuto, "00")
Dim sDate As String = CStr(anno) & CStr(mese) & CStr(giorno) & CStr(ora) & CStr(minuto)
Return sDate
End If
Return ""
End Function
Function FromDbDate(s As String, Optional ancheOraEMinuti As Boolean = False) As String
If s Is Nothing Then Return ""
If s.Length = 0 Then Return ""
If s.Length > 12 Then
Dim data As String = ""
Dim anno As String = s.Substring(0, 4)
Dim mese As String = s.Substring(5, 2)
Dim giorno As String = s.Substring(7, 2)
Dim ora As String = s.Substring(9, 2)
Dim minuti As String = s.Substring(11, 2)
End If
Return ""
End Function
End Module

Can anyone see why I'm getting the error, {"ExecuteReader: Connection property has not been initialized."}?

Been staring at this code for 2 hours and I can't find anything. It could be from fatigue. When I run the code, the errors points to
strSelect = "SELECT * FROM TGolfers where strFirstName like '%" &
cboGolfer.Text & "%' or strLastName like '%" & cboGolfer.Text & "%'"
cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
drSourceTable = cmdSelect.ExecuteReader
Using dt As New DataTable()"
in the GetGolfer function Hopefully someone can help me figure out why I'm getting this error and fix it. Thanks
Public Class frmGolfer
Private Sub frmGolfer_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
GetGolfer()
Try
Dim strSelect As String = ""
Dim cmdSelect As OleDb.OleDbCommand
Dim drSourceTable As OleDb.OleDbDataReader
Dim dt As DataTable = New DataTable
Dim strSQL As String = "INSERT INTO TGolfers(strFirstName, strLastName, strEmail) VALUES (#FirstName, #LastName, #Email)"
If OpenDatabaseConnectionSQLServer() = False Then
MessageBox.Show(Me, "Database connection Error." & vbNewLine &
"The application will now close.",
Text + "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End If
cboGolfer.BeginUpdate()
strSelect = "Select intGolferID, strLastName FROM TGolfers"
cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
drSourceTable = cmdSelect.ExecuteReader
dt.Load(drSourceTable)
cboGolfer.ValueMember = "intGolferID"
cboGolfer.DisplayMember = "strLastName"
cboGolfer.DataSource = dt
cboGolfer.EndUpdate()
drSourceTable.Close()
CloseDatabaseConnection()
Catch excError As Exception
MessageBox.Show(excError.Message)
End Try
If cboGolfer.Items.Count > 0 Then cboGolfer.SelectedIndex = 0
End Sub
Public Function GetGolfer()
Dim strSelect As String = ""
Dim cmdSelect As OleDb.OleDbCommand
Dim drSourceTable As OleDb.OleDbDataReader
strSelect = "SELECT * FROM TGolfers where strFirstName like '%" & cboGolfer.Text & "%' or strLastName like '%" & cboGolfer.Text & "%'"
cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
drSourceTable = cmdSelect.ExecuteReader
Using dt As New DataTable()
DgvGolfer.AutoGenerateColumns = False
DgvGolfer.DataSource = dt
End Using
End Function

The Connection String Property Has Not Been Initialized vb.net

Please can you tell me why my database info is not pulling through. i am fearly new to vb and i have been trying to create this project with the help of google but stuck on linking my db
Imports System.Data.OleDb
Public Class MyeventDB
Public Shared Function GetEvent(eventID As Integer) As Myevent
Dim myevent As New Myevent
Dim connection As OleDbConnection = MyAthleteEvents.GetConnection
Dim selectStatement As String =
"SELECT EventID, Title, Date, Fee, Location, Distance " &
"FROM Events " &
"WHERE EventID = #EventID"
Dim selectCommand As New OleDbCommand(selectStatement, connection)
selectCommand.Parameters.AddWithValue("#EventID", eventID)
Try
connection.Open()
Dim reader As OleDbDataReader _
= selectCommand.ExecuteReader(CommandBehavior.SingleRow)
If reader.Read Then
myevent.EventID = CInt(reader("EventID"))
myevent.Title = reader("Title").ToString
myevent.DDate = reader("Date").ToString
myevent.Fee = reader("Fee").ToString
myevent.Location = reader("Location").ToString
myevent.Distance = reader("Distance").ToString
Else
myevent = Nothing
End If
reader.Close()
Catch ex As Exception
Throw ex
Finally
connection.Close()
End Try
Return myevent
End Function
Public Shared Function AddEvent(myevent As Myevent) As Integer
Dim connection As OleDbConnection = MyAthleteEvents.GetConnection
Dim insertStatement As String =
"INSERT Events " &
"(Title, Date, Fee, Location, Distance) " &
"VALUES (#Title, #Date, #Fee, #Location, #Distance)"
Dim insertCommand As New OleDbCommand(insertStatement, connection)
insertCommand.Parameters.AddWithValue("#Title", myevent.Title)
insertCommand.Parameters.AddWithValue("#Date", myevent.DDate)
insertCommand.Parameters.AddWithValue("#Fee", myevent.Fee)
insertCommand.Parameters.AddWithValue("#Location", myevent.Location)
insertCommand.Parameters.AddWithValue("#Distance", myevent.Distance)
Try
connection.Open()
insertCommand.ExecuteNonQuery()
Dim selectStatement As String _
= "SELECT IDENT_CURRENT('Events') FROM Events"
Dim selectCommand As New OleDbCommand(selectStatement, connection)
Dim eventID As Integer = CInt(selectCommand.ExecuteScalar)
Return eventID
Catch ex As Exception
Throw ex
Finally
connection.Close()
End Try
End Function
Public Shared Function UpdateEvent(oldEvent As Myevent,
newEvent As Myevent) As Boolean
Dim connection As OleDbConnection = MyAthleteEvents.GetConnection
Dim updateStatement As String =
"UPDATE Events SET " &
"Title = #NewTitle, " &
"Date = #NewDate, " &
"Fee = #NewFee, " &
"Location = #NewLocation, " &
"Distance = #NewDistance " &
"WHERE EventID = #OldEventID " &
"AND Title = #OldTitle " &
"AND Date = #OldDate " &
"AND Fee = #OldFee " & "AND Location = #OldLocation " &
"AND Distance = #OldDistance"
Dim updateCommand As New OleDbCommand(updateStatement, connection)
updateCommand.Parameters.AddWithValue("#NewTitle", newEvent.Title)
updateCommand.Parameters.AddWithValue("#NewDate", newEvent.DDate)
updateCommand.Parameters.AddWithValue("#NewFee", newEvent.Fee)
updateCommand.Parameters.AddWithValue("#NewLocation", newEvent.Location)
updateCommand.Parameters.AddWithValue("#NewDistance", newEvent.Distance)
updateCommand.Parameters.AddWithValue("#OldEventID", oldEvent.EventID)
updateCommand.Parameters.AddWithValue("#OldTitle", oldEvent.Title)
updateCommand.Parameters.AddWithValue("#OldDate", oldEvent.DDate)
updateCommand.Parameters.AddWithValue("#OldFee", oldEvent.Fee)
updateCommand.Parameters.AddWithValue("#OldLocation", oldEvent.Location)
updateCommand.Parameters.AddWithValue("#OldDistance", oldEvent.Distance)
Try
connection.Open()
Dim count As Integer = updateCommand.ExecuteNonQuery
If count > 0 Then
Return True
Else
Return False
End If
Catch ex As Exception
Throw ex
Finally
connection.Close()
End Try
End Function
Public Shared Function DeleteEvent(myevent As Myevent) As Boolean
Dim connection As OleDbConnection = MyAthleteEvents.GetConnection
Dim deleteStatement As String =
"DELETE FROM Events " &
"WHERE EventID = #EventID " &
"AND Title = #Title " &
"AND Date = #Date " &
"AND Fee = #Fee " &
"AND Location = #Location " &
"AND Distance = #Distance"
Dim deleteCommand As New OleDbCommand(deleteStatement, connection)
deleteCommand.Parameters.AddWithValue("#EventID", myevent.EventID)
deleteCommand.Parameters.AddWithValue("#Title", myevent.Title)
deleteCommand.Parameters.AddWithValue("#Date", myevent.DDate)
deleteCommand.Parameters.AddWithValue("#Fee", myevent.Fee)
deleteCommand.Parameters.AddWithValue("#Location", myevent.Location)
deleteCommand.Parameters.AddWithValue("#Distance", myevent.Distance)
Try
connection.Open()
Dim count As Integer = deleteCommand.ExecuteNonQuery
If count > 0 Then
Return True
Else
Return False
End If
Catch ex As Exception
Throw ex
Finally
connection.Close()
End Try
End Function
End Class
Imports System.Data.OleDb
Public Class MyAthleteEvents
Public Shared Function GetConnection() As OleDbConnection
' If necessary, change the following connection string
' so it works for your system
Dim connectionString As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\lebom\Desktop\ICT3611Assignment\AthletesEvents.accdb")
Return New OleDbConnection()
End Function
End Class
In your MyAthleteEvents.GetConnection, you create one OleDbConnection object with a connection string but then, instead of returning that object, you return a second new OleDbConnection object.
This:
Return New OleDbConnection()
should be this:
Return connectionString
That said, why would you use the name 'connectionString' for a variable of type OleDbConnection? It's not a connection string so why name it as though it is? It would have to be a String to be a connection string.

Converting a OleDbDataReader to a String to display a COUNT command in List View

I want to display in a ListView the COUNT of a specific Employee Name whilst using two MS Access queries. The COUNT that is being displayed is only 0, 1 or 2 but there are many none "----" values in the database.
The command is binded to a RadioButton:
Private Sub RadioButton2_Click(sender As Object, e As EventArgs) Handles RadioButton2.Click
Dim con As New OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath & "\sheetlog.mdb;Jet OLEDB:Database Password = 'password';")
con.Open()
Dim try2 As String = "----"
Dim try3 As String
Dim oledbCmd, oledbCmd2 As OleDbCommand
Dim cmd, cmd2 As String
cmd = "SELECT DISTINCT empname FROM sheet"
oledbCmd = New OleDbCommand(cmd, con)
Dim oledbReader As OleDbDataReader = oledbCmd.ExecuteReader()
ListView1.Clear()
ListView1.GridLines = True
ListView1.FullRowSelect = True
ListView1.View = View.Details
ListView1.MultiSelect = False
ListView1.Columns.Add("Employee Name", 130)
ListView1.Columns.Add("New", 80)
ListView1.Columns.Add("Rev1", 80)
ListView1.Columns.Add("Rev2", 80)
ListView1.Columns.Add("Rev3", 80)
ListView1.Columns.Add("Rev4", 80)
ListView1.Columns.Add("Rev5", 80)
While (oledbReader.Read)
try3 = oledbReader("empname").ToString
cmd2 = "SELECT count(new) AS cnew, count(rev1) AS crev1, count(rev2) AS crev2, count(rev3) AS crev3, count(rev4) AS crev4, count(rev5) AS crev5 FROM sheet WHERE empname = '" & try3 & "' AND rev1 <> '" & try2 & "' AND rev2 <> '" & try2 & "' AND rev3 <> '" & try2 & "' AND rev4 <> '" & try2 & "' AND rev5 <> '" & try2 & "'"
oledbCmd2 = New OleDbCommand(cmd2, con)
Dim oledbReader2 As OleDbDataReader = oledbCmd2.ExecuteReader()
While (oledbReader2.Read)
With ListView1.Items.Add(oledbReader("empname"))
.subitems.add(oledbReader2("cnew"))
.subitems.add(oledbReader2("crev1"))
.subitems.add(oledbReader2("crev2"))
.subitems.add(oledbReader2("crev3"))
.subitems.add(oledbReader2("crev4"))
.subitems.add(oledbReader2("crev5"))
End With
End While
End While
con.Close()
End Sub
I've been away from VB.NET for a bit, but I think you need to do While(oledbReader2.Read())for the second DataReader:
Dim oledbReader2 As OleDbDataReader = oledbCmd2.ExecuteReader()
' I think you need this here:
While (oledbReader2.Read)
With ListView1.Items.Add(oledbReader("empname"))
.subitems.add(oledbReader2("cnew"))
.subitems.add(oledbReader2("crev1"))
.subitems.add(oledbReader2("crev2"))
.subitems.add(oledbReader2("crev3"))
.subitems.add(oledbReader2("crev4"))
.subitems.add(oledbReader2("crev5"))
End With
End While

Getting hung up in a BackgroundWorker

I've got an app that checks every few seconds for new orders.
If it sees a new entry in the database, it fires off a BackgroundWorker to process it.
I have 3 list boxes on my form, pending, completed and failed.
Theres is a second BackgroundWorker process which asynchronously checks with an api to see if the order has been fully processed yet, before moving the item in question to the 'completed' list box.
Everything seems to be working fine until I throw a few orders at a time at the app.
It processes the orders fine and adds them to pending, and it will check back on a few of them but eventually get stuck in the secondbackground worker process.
It will eventually crash out with a "This BackgroundWorker is currently busy" error.
I've gone over my code lots of times and I can't see where it would be crashing out.
Whats the best way for me to diagnose this?
Heres the code for the background worker where I'm getting stuck...
Private Sub BuildProgressCheck_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) _
Handles BuildProgressCheck.DoWork
lblstatus.Text = "Checking back on async jobs"
Dim i As Integer
For i = 0 To buildpendinglist.Items.Count - 1
Beep()
Dim cn As New MySqlConnection
cn.ConnectionString = "server=" & dbserver & "; userid=" & dbusername & "; password=" & dbpassword & "; database=" & dbdatabase & ";Convert Zero Datetime=True"
Dim jobcheck As New MySqlDataAdapter("Select * FROM dbcpman_jobs WHERE dbxid='" & buildpendinglist.Items(i) & "'", cn)
Dim jobcheck_table As New DataTable
jobcheck.Fill(jobcheck_table)
Dim jobrow As DataRow
jobrow = jobcheck_table.Select("failed = 'false'").FirstOrDefault()
If Not jobrow Is Nothing Then
Dim job_id As String = jobrow.Item("id")
Dim job_jobid As String = jobrow.Item("jobid")
Dim job_status As String = jobrow.Item("status")
Dim job_dbxid As String = jobrow.Item("dbxid")
Dim jobcommand As String = "command=queryAsyncJobResult&jobId=" & job_jobid
Dim fulljobapicheckurl = cpapiurl & jobcommand
Try
Dim jobapicall As New System.Net.WebClient
jobcheckresult = jobapicall.DownloadString(fulljobapicheckurl)
Catch ex As Exception
''Problem submitting the api request?
End Try
If jobcheckresult.Contains("<jobstatus>1</jobstatus>") Then ''If true, job has completed
Dim doc As New System.Xml.XmlDocument
doc.LoadXml(jobcheckresult) ''api_result contains xml returned from a http request.
If doc.GetElementsByTagName("virtualmachine") IsNot Nothing Then
Dim elem As XmlNodeList = doc.GetElementsByTagName("virtualmachine").Item(0).ChildNodes
For Each item As XmlNode In elem
If item.Name.Equals("state") Then
new_vm_state += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("hostname") Then
new_vm_hostname += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("templatename") Then
new_vm_templatename += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("cpunumber") Then
new_vm_cpunumber += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("cpuspeed") Then
new_vm_cpuspeed += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("memory") Then
new_vm_memory += ((item.InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("nic") Then
new_vm_netmask += ((item.ChildNodes.Item(3).InnerText.ToString()) + Environment.NewLine)
new_vm_gateway += ((item.ChildNodes.Item(4).InnerText.ToString()) + Environment.NewLine)
new_vm_ipaddress += ((item.ChildNodes.Item(5).InnerText.ToString()) + Environment.NewLine)
new_vm_macaddress += ((item.ChildNodes.Item(11).InnerText.ToString()) + Environment.NewLine)
ElseIf item.Name.Equals("instancename") Then
new_vm_instancename1 += ((item.InnerText.ToString()) + Environment.NewLine)
End If
Next
End If
new_vm_macaddress = new_vm_macaddress.ToUpper
Dim privateip As String = new_vm_ipaddress.Replace(" ", "").ToString
Dim publicip As String = privateip.Replace("172.16.11.", "198.73.112.")
Try
Dim myCommand As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim SQL As String
myCommand.Connection = cn
cn.Open()
myAdapter.SelectCommand = myCommand
SQL = "DELETE FROM dbcpman_jobs WHERE jobid = '" & job_jobid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
SQL = "UPDATE dbcpman_vm SET deployresponse = '" & jobcheckresult & "' WHERE dbx_id = '" & job_dbxid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
SQL = "UPDATE dbcpman_vm SET macaddress = '" & new_vm_macaddress & "' WHERE dbx_id = '" & job_dbxid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
SQL = "UPDATE dbcpman_vm SET publicip = '" & publicip & "' WHERE dbx_id = '" & job_dbxid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
SQL = "UPDATE dbcpman_vm SET privateip = '" & privateip & "' WHERE dbx_id = '" & job_dbxid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
cn.Close()
Dim new_vm_username As String = "clouduser"
Dim new_vm_password As String = GeneratePassword(7)
System.Threading.Thread.Sleep(1000)
Dim new_vm_support_username As String = "dbxsupport"
Dim new_vm_support_password As String = GenerateSupportPassword(7)
cn.Open()
myAdapter.SelectCommand = myCommand
SQL = "INSERT into dbcpman_credentials(username1, username2, password1, password2, type, link) VALUES ('" & new_vm_username & "','" & new_vm_support_username & "','" & new_vm_password & "','" & new_vm_support_password & "','Server root logon','" & job_dbxid & "')"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
SQL = "INSERT into dbcpman_vm_boot(dbxid, ip, macaddress, hostname) VALUES ('" & job_dbxid & "','" & new_vm_ipaddress & "','" & new_vm_macaddress & "','" & job_dbxid & "')"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
cn.Close()
Try ''''add monitoring for this new host
Dim monitorurl As String = "http://192.168.16.32/addhost.php?hostname=" & job_dbxid & "&ipaddr=" & publicip
Dim webClient As New System.Net.WebClient
Dim monresult As String = webClient.DownloadString(monitorurl)
If monresult = "SUCCESS" Then
''success message
Else
''fail message
End If
Catch ex As Exception
End Try
buildcompletedlist.Items.Add(buildpendinglist.Items(i))
buildpendinglist.Items.Remove(buildpendinglist.Items(i))
buildprogresscheckactive = 0
BuildProgressCheck.CancelAsync()
Catch ex As Exception
End Try
ElseIf jobcheckresult.Contains("<jobstatus>0</jobstatus>") Then ''If true, job is still pending
''job still pending - do nothing, will check again on next pass
ElseIf jobcheckresult.Contains("<jobstatus>2</jobstatus>") Then ''If true, job has failed
Try
Dim myCommand As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim SQL As String
myCommand.Connection = cn
cn.Open()
myAdapter.SelectCommand = myCommand
SQL = "UPDATE dbcpman_jobs SET failed = 'true' WHERE jobid = '" & job_jobid & "'"
myCommand.CommandText = SQL
myCommand.ExecuteNonQuery()
cn.Close()
buildfailedlist.Items.Add(buildpendinglist.Items(i))
buildpendinglist.Items.Remove(buildpendinglist.Items(i))
Catch ex As Exception
BuildProgressCheck.CancelAsync()
buildprogresscheckactive = 0
End Try
End If
End If
Next
buildprogresscheckactive = 0
End Sub
My best guess based on the appended text and code is as follows:
"..checks every few seconds for new orders."
Error: "This BackgroundWorker is currently busy"
So I believe you're starting the asynchronous work in a Tick event of a Timer. So, let's say your timer ticks every 2 seconds.
Friend WithEvents mytimer As New System.Windows.Forms.Timer With {.Interval = 2000, .Enabled = True}
Private Sub _Tick(sender As Object, e As EventArgs) Handles mytimer.tick
Me.BuildProgressCheck.RunWorkerAsync()
End Sub
Now, lets imagine that for 6 ticks BuildProgressCheck_DoWork are executed in less than 2 seconds. No error occurs and everything seems okay. But, at the 7th tick it take 3 seconds. Then, when the timer raise tick for the 8th time, the BackGroundWorker is "currently busy" and throws an error.
What you need to do is to suspend the timer before running the worker and resume it when the worker has completed. Here's an example:
Private Sub _Tick(sender As Object, e As EventArgs) Handles mytimer.Tick
'Suspend the timer:
Me.mytimer.Enabled = False
'Do background work:
Me.BuildProgressCheck.RunWorkerAsync()
End Sub
Private Sub _DoWork(sender As Object, e As DoWorkEventArgs) Handles BuildProgressCheck.DoWork
'Important: Do not invoke any UI controls inside this method.
' (We're inside the background thread)
End Sub
Private Sub _ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BuildProgressCheck.ProgressChanged
'Here you can safely invoke UI controls.
'(We're inside UI thread)
'Me.Label1.Text = "Started..."
End Sub
Private Sub _RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BuildProgressCheck.RunWorkerCompleted
Try
If (e.Error Is Nothing) Then
If (e.Cancelled) Then
'Cancelled
Else
'Success
End If
Else
'Error
End If
Catch ex As Exception
'...
Finally
'Restart the timer.
Me.mytimer.Enabled = True
End Try
End Sub