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

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

Related

Use VB.NET Manipulate Microsoft Access Database

How can I make this work?
Private Sub ListView_MouseClick(sender As Object, e As MouseEventArgs) Handles ListView.MouseClick
conndb = New OleDbConnection
conndb.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database1.accdb"
Try
conndb.Open()
Dim str As String
str = "Select * FROM customer WHERE CustomerID = '" & ListView.FocusedItem.Text & "'"
COMMAND = New OleDbCommand(str, conndb)
dr = COMMAND.ExecuteReader
If dr.Read = True Then
txtID.Text = dr("CustomerID")
txtFirstName.Text = dr("FirstName")
txtSurname.Text = dr("Surname")
txtAddress.Text = dr("Address")
txtCN1.Text = dr("ContactNo1")
txtCN2.Text = dr("ContactNo2")
txtEmail.Text = dr("EmailAddress")
txtRemarks.Text = dr("Remarks")
txtDebtStatus.Text = dr("DebtStatus")
txtDownPay.Text = dr("DownPayment")
txtDebtBal.Text = dr("DebtBal")
txtCustomerDate.Text = dr("Date")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conndb.Dispose()
End Try
End Sub
I need help on how can I make this run without errors, Im using ms access as my database source. There seems to be an error using this code, this code works perfectly fine with mysql but in ms access, it says data mistype error or something like that. Need your help, thanks
Remove the ' surrounding the field CustomerID in your query :
str = "Select * FROM customer WHERE CustomerID = '" & ListView.FocusedItem.Text & "'"
becomes :
str = "Select * FROM customer WHERE CustomerID = " & ListView.FocusedItem.Text
MS Access sees a string when you put an apostrophe, so there is a Type Mismatch Exception, because it is expecting a number...
However, this is a pretty bad idea as Parametrized queries are a better way of doing this (see : Why should I create Parametrized Queries ?)
Also, Use Using
So all in all, it's just another brick in the wall :
Private Sub ListView_MouseClick(sender As Object, e As MouseEventArgs) Handles ListView.MouseClick
Using conndb As New OleDbConnection
conndb.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database1.accdb"
Try
conndb.Open()
Dim str As String
str = "Select * FROM customer WHERE CustomerID = #Customer"
Using COMMAND As New OleDbCommand(str, conndb)
COMMAND.Parameters.Add("#Customer", SqlDbType.Integer).Value = Integer.Parse(ListView.FocusedItem.Text)
dr = COMMAND.ExecuteReader
If dr.Read = True Then
txtID.Text = dr("CustomerID")
txtFirstName.Text = dr("FirstName")
txtSurname.Text = dr("Surname")
txtAddress.Text = dr("Address")
txtCN1.Text = dr("ContactNo1")
txtCN2.Text = dr("ContactNo2")
txtEmail.Text = dr("EmailAddress")
txtRemarks.Text = dr("Remarks")
txtDebtStatus.Text = dr("DebtStatus")
txtDownPay.Text = dr("DownPayment")
txtDebtBal.Text = dr("DebtBal")
txtCustomerDate.Text = dr("Date")
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub
Take a look at this sample code that I put together a while back. You can probably learn a lot from this.
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged, TextBox1.Click
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\your_path\Desktop\Northwind_2012.mdb"
Dim selectCommand As String
Dim connection As New OleDbConnection(connectionString)
'selectCommand = "Select * From MyExcelTable where Fname = '" & TextBox1.Text & "'"
'"SELECT * FROM Customers WHERE Address LIKE '" & strAddressSearch & "%'"
'or ending with:
'"SELECT * FROM Customers WHERE Address LIKE '%" & strAddressSearch & "'"
selectCommand = "Select * From MyExcelTable where Fname Like '" & TextBox1.Text & "%'"
Me.dataAdapter = New OleDbDataAdapter(selectCommand, connection)
With DataGridView1
.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
End With
Dim commandBuilder As New OleDbCommandBuilder(Me.dataAdapter)
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(table)
Me.bindingSource1.DataSource = table
Dim data As New DataSet()
data.Locale = System.Globalization.CultureInfo.InvariantCulture
DataGridView1.DataSource = Me.bindingSource1
Me.DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Aqua
Me.DataGridView1.AutoResizeColumns( _
DataGridViewAutoSizeColumnsMode.AllCells)
End Sub

show multiple data on rcihtextbox from database column error

What's wrong with my code? the error happens on UPDATE block "
If reader1.Read() Then
rtbURThirdMolar.Text = reader1.Item("Up_Right_3rd_Molar")" Conversion from type 'DBNull' to type 'String' is not valid
Private Sub txtURThirdMolar_KeyDown(sender As Object, e As KeyEventArgs) Handles txtURThirdMolar.KeyDown
MySqlConn.open()
If e.KeyCode = Keys.Enter Then
query1 = "SELECT * FROM teethhistory WHERE Patient_ID_Number ='" & lblID.Text & "'"
cmd1 = New MySqlCommand(query1, MySqlConn)
reader = cmd1.ExecuteReader
If reader.HasRows Then
Dim i As Integer
With cmd
.Connection = MySqlConn
.CommandText = "UPDATE teethhistory SET Up_Right_3rd_Molar = concat('" & txtURThirdMolar.Text & Environment.NewLine & "',Up_Right_3rd_Molar) WHERE Patient_ID_Number = " & lblID.Text
reader.Close()
i = .ExecuteNonQuery
End With
If i > 0 Then
MsgBox("Updated!", MsgBoxStyle.Information, "Success")
txtURThirdMolar.Text = ""
Dim query2 As String
Dim reader1 As MySqlDataReader
Dim cmd2 As MySqlCommand
query2 = "SELECT * FROM teethhistory WHERE Patient_ID_Number ='" & lblID.Text & "'"
cmd2 = New MySqlCommand(query2, MySqlConn)
reader1 = cmd2.ExecuteReader
If reader1.Read() Then
rtbURThirdMolar.Text = reader1.Item("Up_Right_3rd_Molar") 'THIS IS WHERE THE ERROR OCCURS
End If
Else
MsgBox("Failed", MsgBoxStyle.Information, "Failed")
End If
Else
Dim cmd As MySqlCommand = MySqlConn.CreateCommand
cmd.CommandText = String.Format("INSERT INTO teethhistory (Patient_ID_Number, Fullname, Up_Right_3rd_Molar )" &
"VALUES ('{0}' ,'{1}' ,'{2}')",
lblID.Text,
lblFullname.Text,
txtURThirdMolar.Text)
reader.Close()
Dim affectedrows As Integer = cmd.ExecuteNonQuery()
If affectedrows > 0 Then
MsgBox("Saved!", MsgBoxStyle.Information, "Success")
txtURThirdMolar.Text = ""
Dim query2 As String
Dim reader2 As MySqlDataReader
Dim cmd2 As MySqlCommand
query2 = "SELECT * FROM teethhistory WHERE Patient_ID_Number ='" & lblID.Text & "'"
cmd2 = New MySqlCommand(query2, MySqlConn)
reader2 = cmd2.ExecuteReader
If reader2.Read() Then
rtbURThirdMolar.Text = reader2.Item("Up_Right_3rd_Molar")
End If
Else
MsgBox("Saving failed.", MsgBoxStyle.Critical, "Failed")
End If
End If
End If
MySqlConn.close()
End Sub
use
rtbURThirdMolar.Text = reader1.Item("Up_Right_3rd_Molar").ToString
this is because the item you are referencing is NULL.

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

Input array is longer than the number of columns

In the event dragdrop of a datagridview I got this error:
Here's the whole code of my dragdrop event :
Private Sub DataGridView1_DragDrop(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragDrop
Dim clientPoint As Point = DataGridView1.PointToClient(New Point(e.X, e.Y))
Dim hit As DataGridView.HitTestInfo = DataGridView1.HitTest(clientPoint.X, clientPoint.Y)
Dim dgvr As DataGridViewRow = DirectCast(e.Data.GetData(GetType(DataGridViewRow)), DataGridViewRow)
Dim celldata As Object() = New Object(dgvr.Cells.Count) {}
For col As Integer = 0 To dgvr.Cells.Count - 1
celldata(col) = dgvr.Cells(col).Value
Next
Dim dt As New DataTable()
dt = ds_data.Tables(0)
Dim colCheckbox As DataColumn = dt.Columns.Add("Column1", GetType(Boolean))
Dim row As DataRow = dt.NewRow()
row.ItemArray = celldata
dt.Rows.InsertAt(row, hit.RowIndex)
dgvr.DataGridView.Rows.Remove(dgvr)
Dim sqlCmd As SqlCommand
sqlCmd = con.CreateCommand()
sqlCmd.CommandText = "update megatom_data_commande set ordre='" & hit.RowIndex & "' where id='" & DataGridView1.Rows(hit.RowIndex).Cells("ID").Value.ToString & "'"
Try
sqlCmd.ExecuteNonQuery()
DataGridView2.DataSource = ds_data2.Tables(0).DefaultView
DataGridView1.DataSource = ds_data.Tables(0).DefaultView
Dim CMD As New SqlCommand("PLANNIFIER")
CMD.Parameters.Add("#CHAINE", SqlDbType.VarChar).Value = cboChaine.SelectedItem.ToString
ExecuteCMD(CMD)
Catch ex As SqlException
End Try
End Sub
In fact my datatable have 15 columns but I added manually a checkbox column to select rows so I think i have a problem of indexes but I dont know how to resolve that problem.
My ds_data is defined like the code below:
requestPlanifie = "select megatom_data_commande.id as ID,numéro,observation,moule,commande,id_etat,programme,ordre,moule,glav,Qté_commandée_Totale," _
& " Qté_coupée_cuir, Qté_coupée_synthétique, Qté_piquée, Qté_finie from megatom_data_commande" _
& " inner join dbo.MEGATOM_DATA_MOULE on megatom_data_moule.id=megatom_data_commande.id_moule " _
& " where id_chaine='" & cboChaine.Text & "' and ( id_etat='3' or id_etat='4') order by numéro asc,ordre asc"
Dim dataAdapter As New SqlDataAdapter(requestPlanifie, con)
Try
dataAdapter.Fill(ds_data, "ds_data")
dataAdapter2.Fill(ds_data2, "ds_data2")
Catch ex As SqlException
End Try
DataGridView1.DataSource = ds_data.Tables(0).DefaultView

Code getting stuck in BackgroundWorker

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.