Syntax error in update query in VB .NET - sql

I'm trying to run a SQL command in VB .NET but it returns a error message of syntax error in my string variable which I just not able to figure out by myself since this is my first experience for programming with SQL command.The specific message is:
Syntax error (missing operator) in query express '= '045617123'.
Where "045617123" is the data stored in one of the data fields
Can someone please help me out from this? Thank You
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim constr As String = "Provider = Microsoft.ACE.OLEDB.12.0;" & "Data Source = C:\Users\JohnnyCheng\Documents\GradeBook.accdb"
Dim conobj As New OleDb.OleDbConnection(constr)
Dim da1 As New OleDb.OleDbDataAdapter()
Dim da2 As New OleDb.OleDbDataAdapter()
Dim sqlstr1 As String = ""
Dim sqlstr2 As String = ""
conobj.Open()
For i As Integer = 0 To vt1.Rows.Count - 1
sqlstr1 = "UPDATE Students SET LastName = '" & vt1.Rows(i)(1) & "', FirstName = '" & vt1.Rows(i)(2) & "', StreetAddress = '" & vt1.Rows(i)(3) & "', City = '" & vt1.Rows(i)(4) & "', State = '" & vt1.Rows(i)(5) & "', ZipCode = '" & vt1.Rows(i)(6) & "' WHERE = '" & vt1.Rows(i)(0) & "'"
da1.UpdateCommand = New OleDb.OleDbCommand(sqlstr1, conobj)
da1.UpdateCommand.ExecuteNonQuery()
Next
'For i As Integer = 0 To vt2.Rows.Count - 1
'sqlstr2 = "UPDATE Grades SET FirstExam = " & vt2.Rows(i)(1) & ", SecondExam = " & vt2.Rows(i)(2) & ", FinalExam = " & vt2.Rows(i)(3) & "WHERE StID = " & vt1.Rows(i)(0)
'da2.UpdateCommand = New OleDb.OleDbCommand(sqlstr2, conobj)
'da2.UpdateCommand.ExecuteNonQuery()
'Next
conobj.Close()
End Sub

Use SqlParameters. If some of your datafields contain ' charachter then sql query return a syntax error. Or users can create a Sql injection query.
Your syntax error in the WHERE = '" & vt1.Rows(i)(0) & "'" There are no column name which must be same as datafield value
Here example of using parameters:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim constr As String = "Provider = Microsoft.ACE.OLEDB.12.0;" & "Data Source = C:\Users\JohnnyCheng\Documents\GradeBook.accdb"
Dim query as New StringBuilder()
With query
.AppendLine("UPDATE Students SET LastName = #LastName")
.AppendLine(", FirstName = #FirstName")
.AppendLine(", StreetAddress = #StreetAddress")
.AppendLine(", City = #City")
.AppendLine(", State = #State")
.AppendLine(", ZipCode = #ZipCode")
.AppendLine("WHERE YourIDField = #ID;")
End With
Using conobj As New OleDb.OleDbConnection(constr)
conobj.Open()
Dim da1 As New OleDb.OleDbDataAdapter()
For i As Integer = 0 To vt1.Rows.Count - 1
Using updCommand As New OleDb.OleDbCommand(query.ToString(), New OleDb.OleDbConnection(""))
updCommand.Parameters.AddWithValue("#LastName", vt1.Rows(i)(1))
updCommand.Parameters.AddWithValue("#FirstName ", vt1.Rows(i)(2))
updCommand.Parameters.AddWithValue("#StreetAddress ", vt1.Rows(i)(3))
updCommand.Parameters.AddWithValue("#City ", vt1.Rows(i)(4))
updCommand.Parameters.AddWithValue("#State ", vt1.Rows(i)(5))
updCommand.Parameters.AddWithValue("#ZipCode", vt1.Rows(i)(6))
updCommand.Parameters.AddWithValue("#ID", vt1.Rows(i)(0))
da1.UpdateCommand = updCommand
da1.UpdateCommand.ExecuteNonQuery()
End Using
Next
End Using
End Sub

Related

Multiselection in vb.net ListBox

I have a list of student names in a listBox,(studentList)I click on a name in the box and get all the students details up ie name, course, subject etc.The code then gets the details from the database(in my case it's access) then displays it in a datagridview.
The code works fine if I just select one item from one(or all)List Boxes.My question is, can I select more than one item per LitsBox.I know I can use SelectedMode property to allow the highlighting but that wont draw the required data from the database.Here is the code I am using vb.10
`Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim tables As DataTableCollection = ds.Tables
Dim source1 As New BindingSource()
Dim da As New OleDb.OleDbDataAdapter
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
dbSource = "Data Source = C:\Documents and Settings\Desktop \studentmarks.accdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim isFirstColumn As Boolean = True
Dim student As String = ""
Dim course As String = ""
Dim grade As String = ""
Dim x As String = studentList.Text
Dim y As String = courseList.Text
Dim z As String = gradeList.Text
Dim defaultSQL As String = "SELECT * FROM studentfile "
If studentList.SelectedIndex > -1 Then
If isFirstColumn Then
student = "WHERE student = '" & x & "' "
Else
student = "AND student = '" & x & "' "
End If
isFirstColumn = False
End If
If courseList.SelectedIndex > -1 Then
If isFirstColumn Then
course = "WHERE course = '" & y & "' "
Else
course = "AND course = '" & y & "' "
End If
isFirstColumn = False
End If
If gradeList.SelectedIndex > -1 Then
If isFirstColumn Then
grade = "WHERE grade = '" & z & "' "
Else
grade = "AND grade = '" & z & "' "
End If
isFirstColumn = False
End If
Dim sql As String = defaultSQL & student & course & grade
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "topclass")
Dim view1 As New DataView(tables(0))
source1.DataSource = view1
DataGridView1.DataSource = view1
DataGridView1.Refresh()
DataGridView1.DataSource = view1
DataGridView1.Refresh()
Dim cnt As Integer
cnt = DataGridView1.Rows.Count
TextBox1.Text = cnt - 1
Dim dayclass As String = TextBox1.Text
TextBox8.Text = dayclass
con.Close()
End Sub`
many thanks
grey
Using the .SelectedItems (and a lot of jiggery with the where clause.... you should be able to use this to EITHER have multi-select of single select accross all three listboxes as well as not selecting anything from any of them too...
The only question I would have would be whether you want all the 'AND's as this would mean if you selected two students, you wouldnt get any results... as no two students are the same right? Unless you selected two 'Dave's in which it would return both. For example!
Might suggest changing some for 'OR's or look at what the end result might be? Either way comment and let us know if need any further help
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim tables As DataTableCollection = ds.Tables
Dim source1 As New BindingSource()
Dim da As New OleDb.OleDbDataAdapter
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
dbSource = "Data Source = C:\Documents and Settings\Desktop \studentmarks.accdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim student As String = ""
Dim course As String = ""
Dim grade As String = ""
Dim defaultSQL As String = "SELECT * FROM studentfile "
Dim WhereClause As String = ""
Dim StudentCourseGrade As String
'Students---------------------------------------------
For Each stu In studentList.SelectedItems
StudentCourseGrade = "(student='" & stu & "'"
For Each crs In courselist.SelectedItems
StudentCourseGrade = StudentCourseGrade & " AND course = '" & crs & "'"
For Each grd In gradeList.SelectedItems
StudentCourseGrade = StudentCourseGrade & " AND grade = '" & crs & "'"
Next
Next
StudentCourseGrade = StudentCourseGrade & ")"
If WhereClause.Length = 0 Then
WhereClause = "WHERE " & StudentCourseGrade
Else
WhereClause = " OR " & StudentCourseGrade
End If
Next
'Students---------------------------------------------
Dim SQL As String = defaultSQL & WhereClause
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "topclass")
Dim view1 As New DataView(tables(0))
source1.DataSource = view1
DataGridView1.DataSource = view1
DataGridView1.Refresh()
DataGridView1.DataSource = view1
DataGridView1.Refresh()
Dim cnt As Integer
cnt = DataGridView1.Rows.Count
TextBox1.Text = cnt - 1
Dim dayclass As String = TextBox1.Text
TextBox8.Text = dayclass
con.Close()
End Sub
Hth
Chicken

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

VB.NET SQL Filter doesnt show NULL

Sub KlantenFilterZoeken(ByVal DataGridI As DataGridView, ByVal Tbl As String, ByVal NaamStraatHuisnummerBusnummerPostcodePlaatsTelefoon As String, ByVal DBCON As String)
Dim Delen() As String = NaamStraatHuisnummerBusnummerPostcodePlaatsTelefoon.Split("|")
Dim objConnection As New SqlConnection(DBCON)
Dim objDt As New DataTable
DataGridI.DataSource = Nothing
objConnection.Open()
Dim sSQL As String = "SELECT * FROM " & Tbl & " Where " & "KlantID Like #KlantID AND naam Like #naam AND straat Like #straat AND huisnummer Like #huisnummer AND postcode LIKE #postcode AND plaats LIKE #plaats AND telefoon LIKE #telefoon"
Dim objCommand As SqlCommand = New SqlCommand(sSQL, objConnection)
'Parameters
objCommand.Parameters.AddWithValue("#KlantID", "%" & Delen(0) & "%")
objCommand.Parameters.AddWithValue("#naam", "%" & Delen(1) & "%")
objCommand.Parameters.AddWithValue("#straat", "%" & Delen(2) & "%")
objCommand.Parameters.AddWithValue("#huisnummer", "%" & Delen(3) & "%")
objCommand.Parameters.AddWithValue("#postcode", "%" & Delen(4) & "%")
objCommand.Parameters.AddWithValue("#plaats", "%" & Delen(5) & "%")
objCommand.Parameters.AddWithValue("#telefoon", "%" & Delen(6) & "%")
Dim objAdapter = New SqlDataAdapter(objCommand)
Dim objAdap As SqlDataAdapter = New SqlDataAdapter(sSQL, objConnection)
objAdapter.Fill(objDt)
DataGridI.DataSource = objDt
DataGridI.Columns(0).Visible = True
objConnection.Close()
objConnection.Dispose()
End Sub
This is my code to filter a datagridview, It works but the problem is telephone numbers that have value NULL are "hidden" by this code and I don't want this:
http://i.stack.imgur.com/VpXra.png
How can I fix this
I'm not sure what you would like to do exactly. But if you are trying to avoid empty cells, you could do something like this.
Dim objAdapter = New SqlDataAdapter(objCommand)
Dim objAdap As SqlDataAdapter = New SqlDataAdapter(sSQL, objConnection
objAdapter.Fill(objDt)
Dim i As Integer = objDt.Rows.Count
For i = 0 To objDt.Rows.Count Step 1
If (String.IsNullOrEmpty(objDt.Rows(i)("telefoon"))) Then
Dim phValue = "NULL"
objDt.Rows(i)("telefoon") = phValue
End If
Next
DataGridI.DataSource = objDt
DataGridI.Columns(0).Visible = True
objConnection.Close()
objConnection.Dispose()

How to add multiple prdoucts including their id, qty and price as a single transaction to a Access database?

I have a shopping cart page which lists 12 books with 12 buttons assigned each to a book item, the user is able to click each button and add the price and qty to a Session in VB. So if a customer wants to order all 12 books they would click all twelve buttons and the price and qty of each product would be added to a Session. My problem is when the customer completes the form validation how do I assign all 12 items with their sessions to a MS Access database in a single transaction using session.id?
Protected Sub order_Click(ByVal sender As Object, ByVal e As System.EventArgs)
If (Page.IsValid) Then
Dim strSessionID As String
strSessionID = Session.SessionID
Dim strFullname As String
Dim strAddress As String
Dim strPostcode As String
Dim intCardNo As Long
Dim strCardType As String
Dim dateOfOrder As Date
dateOfOrder = Session("dateOfOrder")
Dim dblTotalCost As String
dblTotalCost = Session("dblTotalCost")
Dim intProduct001 As String
intProduct001 = Session("product001")
Dim intProduct002 As Integer
intProduct002 = Session("product002")
Dim intProduct003 As Integer
intProduct003 = Session("product003")
Dim intProduct004 As Integer
intProduct004 = Session("product004")
Dim intProduct005 As Integer
intProduct005 = Session("product005")
Dim intProduct006 As Integer
intProduct006 = Session("product006")
Dim intProduct007 As Integer
intProduct007 = Session("product007")
Dim intProduct008 As Integer
intProduct008 = Session("product008")
Dim intProduct009 As Integer
intProduct009 = Session("product009")
Dim intProduct010 As Integer
intProduct010 = Session("product010")
Dim intProduct011 As Integer
intProduct011 = Session("product011")
Dim intProduct012 As Integer
intProduct012 = Session("product012")
strFullname = fullname.Text
Session("fullname") = strFullname
strAddress = address.Text
Session("address") = strAddress
strPostcode = postcode.Text
Session("postcode") = strPostcode
intCardNo = cardN0.Text
Session("CardN0") = intCardNo
strCardType = cardType.Text
Session("CardType") = strCardType
Dim strDatabaseNameAndLocation As String
strDatabaseNameAndLocation = Server.MapPath("ecommerceDatabase.mdb")
Dim strSQLCommand As String
strSQLCommand = "INSERT INTO Orders(SessionID, orderDate, orderTotal ) " & _
"Values ('" & strSessionID & "','" & dateOfOrder & "','" & dblTotalCost & "');"
Dim objOleDbConnection As System.Data.OleDb.OleDbConnection
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
Dim objOleDbCommand As System.Data.OleDb.OleDbCommand
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
objOleDbCommand.ExecuteNonQuery()
objOleDbConnection.Close()
Dim strDatabaseNameAndLocation2 As String
strDatabaseNameAndLocation2 = Server.MapPath("ecommerceDatabase.mdb")
Dim strSQLCommand2 As String
strSQLCommand2 = "INSERT INTO Customers(SessionID, Fullname, Address, Postcode, CardNo, CardType) " & _
"Values ('" & strSessionID & "', '" & strFullname & "', '" & strAddress & "', '" & strPostcode & "', '" & intCardNo & "', '" & strCardType & "');"
Dim objOleDbConnection2 As System.Data.OleDb.OleDbConnection
objOleDbConnection2 = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation2)
objOleDbConnection2.Open()
Dim objOleDbCommand2 As System.Data.OleDb.OleDbCommand
objOleDbCommand2 = New System.Data.OleDb.OleDbCommand(strSQLCommand2, objOleDbConnection2)
objOleDbCommand2.ExecuteNonQuery()
objOleDbConnection2.Close()
Response.Redirect("validate.aspx")
End If
You will need to run all of your SQL commands using a single connection, and call OleDbConnection.BeginTransaction on the connection, and OleDbTransaction.Commit on the returned transaction object. You should put your product IDs into a List(Of String) to minimize the code, and you should parameterize your queries to avoid SQL injections issues.
The following pseudocode illustrates the general idea:
Dim productIDs = New List(Of String)()
productIDs.Add(Session("product001")) ' Should be in a loop!
' etc.
Using cn = New OleDbConnection(...)
cn.Open()
Using tran = cn.BeginTransaction(IsolationLevel.Serializable) ' or other isolation level
Using cmd = new OleDbCommand(sql1, cn, tran) ' Customers
' Set command parameters
cmd.ExecuteNonQuery()
End Using
Using cmd = new OleDbCommand(sql2, cn, tran) ' Orders
' Set command parameters
cmd.ExecuteNonQuery()
End Using
For Each productID In productIDs
Using cmd = new OleDbCommand(sql3, cn, tran) ' OrderProducts?
' Set command parameters
cmd.ExecuteNonQuery()
End Using
Next
tran.Commit()
End Using
End Using

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.