How to show download progress in progressbar? Visual Basic - vb.net

im so confused because this code didn't work. It downloaded the file successfully but don't report the progress to the ProgressBar. I already started Timer1 using Timer1.Start() before BackgroundWorker2.RunWorkerAsync() .
Dim size As Double
Private Sub BackgroundWorker2_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker2.DoWork
Try
Dim G As Integer = 150
Dim Increase As Boolean = True
Do Until Clicked = True
If Increase = True Then
If Not G = 255 Then
G += 1
Threading.Thread.Sleep(10)
Else
Increase = False
End If
Else
If Not G = 150 Then
G -= 1
Threading.Thread.Sleep(10)
Else
Increase = True
End If
End If
Label6.ForeColor = Color.FromArgb(0, G, 0)
Loop
Label6.Cursor = Cursors.Default
Label6.Text = "Initializing"
Label6.ForeColor = Color.Lime
MessageBox.Show("Description :" & Environment.NewLine & Description & Environment.NewLine & Environment.NewLine & "Total Size: " & Environment.NewLine & TotalSize & Environment.NewLine & Environment.NewLine & "Download Link (Global): " & Environment.NewLine & DownlaodLink, "BIOS Update Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
'WebBrowser1.Navigate(DownlaodLink)
'BackgroundWorker1.RunWorkerAsync()
ProgressBar1.Visible = True
size = TotalSize.Replace(" MBytes", "")
Me.Refresh()
Dim wc As New WebClient
wc.DownloadFileAsync(New Uri(DownlaodLink), My.Computer.FileSystem.SpecialDirectories.Desktop & "\A55BM-E BIOS " & LatestVersion.ToString.Replace(" ", "") & ".zip")
Catch ex As Exception
MsgBox(ex.Message)
End Try
And the code to show me the progress of my download
Dim cursize As Double
Dim finsize As Double
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If System.IO.File.Exists(My.Computer.FileSystem.SpecialDirectories.Desktop & "\A55BM-E BIOS " & LatestVersion.ToString.Replace(" ", "") & ".zip") Then
cursize = My.Computer.FileSystem.GetFileInfo(My.Computer.FileSystem.SpecialDirectories.Desktop & "\A55BM-E BIOS " & LatestVersion.ToString.Replace(" ", "") & ".zip").Length
finsize = cursize / size * 100
If Not ProgressBar1.Value = ProgressBar1.Maximum Then
ProgressBar1.Value = finsize
ProgressBar1.Refresh()
Else
ProgressBar1.Value = finsize
ProgressBar1.Refresh()
Timer1.Stop()
MsgBox("Finished Downloading")
End If
End If
End Sub
I can't figure out how to make this work. Can someone help me?

Finally! I made it work but didn't go with the BackgroundWorker. The code below is what I've used to make this thing work. And it's so efficient and easy to use too.
Public WithEvents downloader As WebClient
Public Sub DownloadStart()
Label6.Cursor = Cursors.Default
Label6.Text = "Initializing"
Label6.ForeColor = Color.Lime
MessageBox.Show("Description :" & Environment.NewLine & Description & Environment.NewLine & Environment.NewLine & "Total Size: " & Environment.NewLine & TotalSize & Environment.NewLine & Environment.NewLine & "Download Link (Global): " & Environment.NewLine & DownlaodLink, "BIOS Update Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
ProgressBar1.Visible = True
downloader = New WebClient
downloader.DownloadFileAsync(New Uri(DownlaodLink), My.Computer.FileSystem.SpecialDirectories.Desktop & "\A55BM-E BIOS " & LatestVersion.ToString.Replace(" ", "") & ".zip")
End Sub
Private Sub downloader_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs) Handles downloader.DownloadProgressChanged
ProgressBar1.Value = e.ProgressPercentage
End Sub
Thanks everyone for helping me!

Related

no value given for one or more required parameters insert into error

I am receiving error while inserting data into a table. The error is on below:
no value given for one or more required parameters.
I tried to fix the problem but was unsuccessful. I appreciate if you help.
Imports System.Data.OleDb
Public Class Generate
Private Sub Generate_Load(sender As Object, e As EventArgs) Handles MyBase.Load
txtEmId.Enabled = False
txtEmName.Enabled = False
txtIdCtm.Enabled = False
txtNameCtm.Enabled = False
btnAddEp.Enabled = False
btnAddMT.Enabled = False
btnprintG.Enabled = False
btnccc.Enabled = False
sql = "SELECT รหัสวัสดุ FROM วัสดุ "
If (Connection.State = ConnectionState.Open) Then
Connection.Close()
End If
Connection.Open()
Adapter = New OleDbDataAdapter(sql, Connection)
Dataset = New DataSet
Adapter.Fill(Dataset, "IDMT")
CbIDMt.DataSource = Dataset.Tables("IDMT")
CbIDMt.DisplayMember = "รหัสวัสดุ"
CbIDMt.ValueMember = "รหัสวัสดุ"
Connection.Close()
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles btnCancelg.Click
Dim exg As MsgBoxResult
exg = MessageBox.Show("ต้องการยกเลิกการผลิตใช่หรือไม่", "ตรวจสอบ", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
If exg = MsgBoxResult.Yes Then
Me.Close()
End If
End Sub
Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
sql = "SELECT * FROM ลูกค้า INNER JOIN (พนักงาน INNER JOIN คำสั่งซื้อ ON พนักงาน.รหัสพนักงาน = คำสั่งซื้อ.รหัสพนักงาน) ON ลูกค้า.รหัสลูกค้า = คำสั่งซื้อ.รหัสลูกค้า WHERE เลขที่คำสั่งซื้อ = '" & TextBox1.Text & "'"
'sql = "SELECT * FROM พนักงาน INNER JOIN (ลูกค้า INNER JOIN คำสั่งซื้อ ON ลูกค้า.รหัสลูกค้า = คำสั่งซื้อ.รหัสลูกค้า) ON พนักงาน.รหัสพนักงาน = คำสั่งซื้อ.รหัสพนักงาน WHERE เลขที่คำสั่งซื้อ = '" & TextBox1.Text & "'"
If (Connection.State = ConnectionState.Open) Then
Connection.Close()
End If
Connection.Open()
Command = New OleDbCommand(sql, Connection)
Reader = Command.ExecuteReader
Do While Reader.Read
txtEmId.Text = (Reader(6)).ToString
txtEmName.Text = (Reader("ชื่อพนักงาน")).ToString
txtIdCtm.Text = (Reader(0)).ToString
txtNameCtm.Text = (Reader("ชื่อลูกค้า")).ToString
TextBox1.Enabled = False
Loop
'txtEmId.Text = String.Empty
'txtEmId.Focus()
'MessageBox.Show("กรุณากรอกรหัสพนักงานให้ถูกต้อง", "แจ้งเตือน", MessageBoxButtons.OK)
Reader.Close()
Connection.Close()
btnAddMT.Enabled = True
End Sub
Private Sub txtunitMt_TextChanged(sender As Object, e As EventArgs) Handles txtunitMt.TextChanged
txtttMt.Text = txtprMt.Text * txtunitMt.Text
End Sub
Private Sub txtunitMt_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtunitMt.KeyPress
If (e.KeyChar < Chr(48) Or e.KeyChar > Chr(57)) And e.KeyChar <> Chr(8) Then
e.Handled = True
MessageBox.Show("กรุณาใส่เฉพาะตัวเลข", "เตือน!", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End Sub
Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs)
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CbIDMt.SelectedIndexChanged
CbIDMt.Text = String.Empty
Try
sql = "SELECT รหัสวัสดุ, ชื่อวัสดุ, ราคาต่อหน่วย, ยอดคงเหลือ FROM วัสดุ WHERE รหัสวัสดุ = '" & CbIDMt.SelectedValue & "'"
If (Connection.State = ConnectionState.Open) Then
Connection.Close()
End If
Connection.Open()
Command = New OleDbCommand(sql, Connection)
Reader = Command.ExecuteReader
Do While Reader.Read
CbIDMt.SelectedValue = Reader(0).ToString
txtNameMt.Text = Reader(1).ToString
txtprMt.Text = Reader(2).ToString
txtBalance.Text = Reader(3).ToString
Loop
Reader.Close()
Catch ex As Exception
Finally
Connection.Close()
End Try
End Sub
Private Sub btnAddMT_Click(sender As Object, e As EventArgs) Handles btnAddMT.Click
If (String.IsNullOrEmpty(IdGenerate.Text)) Or
(String.IsNullOrWhiteSpace(IdGenerate.Text)) Then
MessageBox.Show("กรุณาใส่รหัสใบผลิต")
Exit Sub
End If
Connection.Open()
Dim unitss As Int64 = CInt(IIf(Not (String.IsNullOrEmpty(txtunitMt.Text)),
txtunitMt.Text, 0))
Dim prtotal As Int32 = CInt(IIf(Not (String.IsNullOrEmpty(txtprMt.Text)),
txtprMt.Text, 0))
Dim totalf As Double = CDbl(IIf(Not (String.IsNullOrEmpty(txtttf.Text)),
txtttf.Text, 0))
Dim totalcr As Double = CDbl(IIf(Not (String.IsNullOrEmpty(txtttcr.Text)),
txtttcr.Text, 0))
Dim totalsss As Double = CDbl(IIf(Not (String.IsNullOrEmpty(totalss.Text)),
totalss.Text, 0))
Dim totalmttt As Int32 = CInt(IIf(Not (String.IsNullOrEmpty(txtttMts.Text)),
txtttMts.Text, 0))
Dim avgtt As Double = CDbl(IIf(Not (String.IsNullOrEmpty(txtavgtotal.Text)),
txtavgtotal.Text, 0))
Dim MySql As String = String.Empty
'------------- INSERT -------------'
MySql &= "INSERT INTO ใบสั่งผลิต(เลขที่ใบสั่งผลิต, วันที่สั่งผลิต, รหัสวัสดุ, จำนวน, ราคารวม, ราคารวมทั้งหมดวัสดุ, รหัสพนักงาน, รหัสลูกค้า, เลขที่ใบแจ้งเงินเดือน, จำนวนเงินเดือน, เลขที่ค่าใช้จ่าย, จำนวนเงินค่าใช้จ่าย, รวมทั้งหมด, ราคาต้นทุนเฉลี่ย )"
MySql &= "VALUES ('" & TextBox1.Text & "'"
MySql &= ",'" & DateTimePicker1.Text & "'"
MySql &= "," & CbIDMt.SelectedValue.ToString & ""
MySql &= "," & Convert.ToInt64(unitss)
MySql &= "," & Convert.ToInt32(prtotal)
MySql &= "," & Convert.ToInt32(totalmttt)
MySql &= ",'" & txtEmId.Text & "'"
MySql &= ",'" & txtIdCtm.Text & "'"
MySql &= ",'" & txtIdf.Text & "'"
MySql &= "," & Convert.ToDouble(totalf)
MySql &= ",'" & txtidcr.Text & "'"
MySql &= "," & Convert.ToDouble(totalcr)
MySql &= "," & Convert.ToDouble(totalsss)
MySql &= "," & Convert.ToDouble(avgtt) & ")"
Command.CommandText = MySql
Command.ExecuteNonQuery()
MessageBox.Show("เพิ่มข้อมูลสำเร็จ", "แจ้งเตือน", MessageBoxButtons.OK, MessageBoxIcon.Information)
Connection.Close()
End Sub
Private Sub Label19_Click(sender As Object, e As EventArgs) Handles Label19.Click
End Sub
End Class
Please focus on the code part below. Check your table:ใบสั่งผลิต and see what columns are not "nullable" and make sure that some value is set for those fields. Also, make sure the order of rows are matching while inserting. It should be like:
Insert into table (col1,col2,...col50) values (col1,col2,...,col50);
The code part you need to debug on below. I specified which line goes for which column, please match. If matching is OK, make sure "not null" columns will have a value after execution.
MySql &= "INSERT INTO ใบสั่งผลิต (เลขที่ใบสั่งผลิต, วันที่สั่งผลิต, รหัสวัสดุ, จำนวน, ราคารวม, ราคารวมทั้งหมดวัสดุ, รหัสพนักงาน, รหัสลูกค้า, เลขที่ใบแจ้งเงินเดือน, จำนวนเงินเดือน, เลขที่ค่าใช้จ่าย, จำนวนเงินค่าใช้จ่าย, รวมทั้งหมด, ราคาต้นทุนเฉลี่ย )"
MySql &= "VALUES ('" & TextBox1.Text & "'" //เลขที่ใบสั่งผลิต
MySql &= ",'" & DateTimePicker1.Text & "'" //วันที่สั่งผลิต
MySql &= "," & CbIDMt.SelectedValue.ToString & "" //รหัสวัสดุ
MySql &= "," & Convert.ToInt64(unitss) //จำนวน
MySql &= "," & Convert.ToInt32(prtotal) //ราคารวม
MySql &= "," & Convert.ToInt32(totalmttt) //ราคารวมทั้งหมดวัสดุ
MySql &= ",'" & txtEmId.Text & "'" //รหัสพนักงาน
MySql &= ",'" & txtIdCtm.Text & "'" //รหัสลูกค้า
MySql &= ",'" & txtIdf.Text & "'" //เลขที่ใบแจ้งเงินเดือน
MySql &= "," & Convert.ToDouble(totalf) //จำนวนเงินเดือน
MySql &= ",'" & txtidcr.Text & "'" //เลขที่ค่าใช้จ่าย
MySql &= "," & Convert.ToDouble(totalcr) //จำนวนเงินค่าใช้จ่าย
MySql &= "," & Convert.ToDouble(totalsss) //รวมทั้งหมด
MySql &= "," & Convert.ToDouble(avgtt) & ")" //ราคาต้นทุนเฉลี่ย

real-time output of process in vb.net

I have the following class for diskparting and imaging a pc. The form has a regular text box (tb1) that lists each step of the process (output) and a rich text box (rtb1) that outputs real time process info. The problem I'm having is the app isn't waiting for the real time output to finish before starting the next sub routine. See attached code:
Imports System
Imports System.IO
Imports System.Management
Imports System.Text.RegularExpressions
Public Class Form1
Private Property pcSerial As Object = GetBiosSerialNumber()
Private Property title As String = "Ross PC Imaging"
Private Property pcModel As Object
Private Property wkstn As String
Private Property srvr As Object
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Call ross()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Call ross()
End Sub
Private Sub ross()
Dim objCS As ManagementObjectSearcher
Dim objMgmt As ManagementObject
objCS = New ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem")
For Each objMgmt In objCS.Get
pcModel = objMgmt("model").ToString()
Next
Output(pcModel)
Output(pcSerial)
'Map network drive
Call MapDrive()
'Diskpart
Output("[ " & Now & " ] PC - " & pcSerial & " physical drives being partitioned and formatted")
If pcModel = "Server" Then
Call diskpart("srvr")
Else
Call diskpart("wkstn")
End If
Output("[ " & Now & " ] PC - " & pcSerial & " physical drives have been partitioned and formatted")
Dim msgDiskPart As String : msgDiskPart = ("[ " & Now & " ] PC - " & pcSerial & " physical drives partitioned and formatted")
Call WriteToLog(title, msgDiskPart)
'Dism
Output("[ " & Now & " ] PC - " & pcSerial & " imaging started")
If pcModel = "Server" Then
Call dism("srvr")
Else
Call dism("wkstn")
End If
Output("[ " & Now & " ] PC - " & pcSerial & " imaging completed")
Dim msgImgStop As String : msgImgStop = ("[ " & Now & " ] PC - " & pcSerial & " imaged")
Call WriteToLog(title, msgImgStop)
'Reboot
'Call reboot()
End Sub
Private Sub MapDrive()
'Map network drive
Dim map As New Process()
map.StartInfo.FileName = "net.exe"
map.StartInfo.Arguments = " use t: \\172.47.3.254\wims"
map.StartInfo.CreateNoWindow = True
map.StartInfo.UseShellExecute = False
map.StartInfo.RedirectStandardOutput = True
map.Start()
map.WaitForExit()
End Sub
Private Sub diskpart(ByVal pctype As String)
'Diskpart disk partitioning
Dim dp As New Process()
dp.StartInfo.FileName = "diskpart.exe"
dp.StartInfo.Arguments = " /s x:\" & pctype & "_diskpart.txt"
dp.StartInfo.CreateNoWindow = True
dp.StartInfo.UseShellExecute = False
dp.StartInfo.RedirectStandardOutput = True
dp.StartInfo.RedirectStandardError = True
dp.EnableRaisingEvents = True
Application.DoEvents()
AddHandler dp.ErrorDataReceived, AddressOf proc_OutputDataReceived
AddHandler dp.OutputDataReceived, AddressOf proc_OutputDataReceived
dp.Start()
dp.BeginErrorReadLine()
dp.BeginOutputReadLine()
End Sub
Private Sub dism(ByVal imgFile As String)
'Image C Drive
Dim dismC As New Process
dismC.StartInfo.FileName = "dism.exe"
dismC.StartInfo.Arguments = " /Apply-Image /ImageFile:t:\" & imgFile & ".wim /index:1 /ApplyDir:c:\"
dismC.StartInfo.CreateNoWindow = True
dismC.StartInfo.UseShellExecute = False
dismC.StartInfo.RedirectStandardOutput = True
dismC.StartInfo.RedirectStandardError = True
dismC.EnableRaisingEvents = True
Application.DoEvents()
AddHandler dismC.ErrorDataReceived, AddressOf proc_OutputDataReceived
AddHandler dismC.OutputDataReceived, AddressOf proc_OutputDataReceived
dismC.Start()
dismC.BeginErrorReadLine()
dismC.BeginOutputReadLine()
dismC.Close()
'Image D Drive
Dim dismD As New Process
dismD.StartInfo.FileName = "dism.exe"
dismD.StartInfo.Arguments = " /Apply-Image /ImageFile:t:\" & imgFile & ".wim /index:2 /ApplyDir:d:\"
dismD.StartInfo.CreateNoWindow = True
dismD.StartInfo.UseShellExecute = False
dismD.StartInfo.RedirectStandardOutput = True
dismD.StartInfo.RedirectStandardError = True
dismD.EnableRaisingEvents = True
Application.DoEvents()
AddHandler dismD.ErrorDataReceived, AddressOf proc_OutputDataReceived
AddHandler dismD.OutputDataReceived, AddressOf proc_OutputDataReceived
dismD.Start()
dismD.BeginErrorReadLine()
dismD.BeginOutputReadLine()
dismD.Close()
End Sub
Private Sub reboot()
'Reboots a pc while in WinPE
Dim reset As New Process
reset.StartInfo.FileName = "wpeutils.exe"
reset.StartInfo.Arguments = " reboot"
reset.Start()
End Sub
Private Sub WriteToLog(ByVal title As String, ByVal msg As String)
'Check and make directory
If Not System.IO.Directory.Exists("t:\logs\") Then
System.IO.Directory.CreateDirectory("t:\logs\")
End If
'Check and make file
Dim fs As FileStream = New FileStream("t:\logs\" & pcSerial & ".log", FileMode.OpenOrCreate, FileAccess.ReadWrite)
Dim s As StreamWriter = New StreamWriter(fs)
s.Close()
fs.Close()
'Logging
Dim fs1 As FileStream = New FileStream("t:\logs\" & pcSerial & ".log", FileMode.Append, FileAccess.Write)
Dim s1 As StreamWriter = New StreamWriter(fs1)
s1.Write("Title: " & title & vbCrLf)
s1.Write("Message: " & msg & vbCrLf)
s1.Write("================================================" & vbCrLf)
s1.Close()
fs1.Close()
End Sub
Private Sub Output(s As String)
'Output to form window
If s <> "" Then
tb1.AppendText(vbCrLf & ">> " & s)
End If
End Sub
Public ReadOnly Property Model()
Get
Model = pcModel
End Get
End Property
Public Function GetBiosSerialNumber() As String
Dim OutputString As String = String.Empty
Using Process As New Process
AddHandler Process.OutputDataReceived,
Sub(sender As Object, e As DataReceivedEventArgs)
OutputString = OutputString & e.Data & vbCrLf
End Sub
With Process.StartInfo
.FileName = "cmd"
.UseShellExecute = False
.CreateNoWindow = True
.RedirectStandardInput = True
.RedirectStandardOutput = True
.RedirectStandardError = True
End With
With Process
.Start()
.BeginOutputReadLine()
End With
Using InputStream As System.IO.StreamWriter = Process.StandardInput
With InputStream
.AutoFlush = True
.Write("wmic bios get serialnumber" & vbCrLf)
End With
End Using
Do
Application.DoEvents()
Loop Until Process.HasExited
End Using
Return Replace(OutputString.Split(CChar(vbCrLf)).ToList(6).Substring(1), " ", "")
End Function
Delegate Sub UpdateTextBoxDelg(text As String)
Public myDelegate As UpdateTextBoxDelg = New UpdateTextBoxDelg(AddressOf UpdateTextBox)
Public Sub UpdateTextBox(text As String)
rtb1.Text += text & Environment.NewLine
rtb1.SelectionStart = rtb1.Text.Length
rtb1.ScrollToCaret()
End Sub
Public Sub proc_OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
If Me.InvokeRequired = True Then
Me.Invoke(myDelegate, e.Data)
Else
UpdateTextBox(e.Data)
End If
End Sub
End Class
I appreciate any advice.
Imports System
Imports System.IO
Imports System.Management
Imports System.Text.RegularExpressions
Public Class Form1
Delegate Sub UpdateTextBoxDelg(text As String)
Public myDelegate As UpdateTextBoxDelg = New UpdateTextBoxDelg(AddressOf UpdateTextBox)
Private Property pcSerial As Object = GetBiosSerialNumber()
Private Property title As String = "Ross PC Imaging"
Private Property pcModel As Object
Private Property wkstn As String
Private Property srvr As Object
Private Property pctype As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call ross()
End Sub
Private Sub ross()
Dim objCS As ManagementObjectSearcher
Dim objMgmt As ManagementObject
objCS = New ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem")
For Each objMgmt In objCS.Get
pcModel = objMgmt("model").ToString()
Next
Output(pcModel)
Output(pcSerial)
'Map network drive
DriveMap.RunWorkerAsync()
End Sub
Private Sub DriveMap_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles DriveMap.DoWork
'Map network drive
Dim map As New Process()
map.StartInfo.FileName = "net.exe"
map.StartInfo.Arguments = " use t: \\172.47.3.254\wims"
map.StartInfo.CreateNoWindow = True
map.StartInfo.UseShellExecute = False
map.StartInfo.RedirectStandardOutput = True
map.Start()
map.WaitForExit()
End Sub
Private Sub DriveMap_RunWorkerCompleted(sender As Object, e As ComponentModel.RunWorkerCompletedEventArgs) Handles DriveMap.RunWorkerCompleted
Output("[ " & Now & " ] PC - *" & pcSerial & "* - partitioning and formatting drives")
Dim msgDiskPart As String : msgDiskPart = ("[ " & Now & " ] PC - *" & pcSerial & "* - partitioning and formatting drives")
Call WriteToLog(title, msgDiskPart)
DiskPart.RunWorkerAsync()
End Sub
Private Sub DiskPart_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles DiskPart.DoWork
If pcModel = "Server" Then
pctype = "srvr"
Else
pctype = "wkstn"
End If
'Diskpart disk partitioning
Dim dp As New Process()
dp.StartInfo.FileName = "diskpart.exe"
dp.StartInfo.Arguments = " /s x:\" & pctype & "_diskpart.txt"
dp.StartInfo.CreateNoWindow = True
dp.StartInfo.UseShellExecute = False
dp.StartInfo.RedirectStandardOutput = True
dp.StartInfo.RedirectStandardError = True
dp.EnableRaisingEvents = True
Application.DoEvents()
AddHandler dp.ErrorDataReceived, AddressOf proc_OutputDataReceived
AddHandler dp.OutputDataReceived, AddressOf proc_OutputDataReceived
dp.Start()
dp.BeginErrorReadLine()
dp.BeginOutputReadLine()
dp.WaitForExit()
End Sub
Private Sub DiskPart_RunWorkerCompleted(sender As Object, e As ComponentModel.RunWorkerCompletedEventArgs) Handles DiskPart.RunWorkerCompleted
Output("[ " & Now & " ] PC - *" & pcSerial & "* - drives have been partitioned and formatted")
Dim msgDiskPart As String : msgDiskPart = ("[ " & Now & " ] PC - *" & pcSerial & "* - drives have been partitioned and formatted")
Call WriteToLog(title, msgDiskPart)
Output("[ " & Now & " ] PC - *" & pcSerial & "* - running disk check on drive C")
Dim msgChkDskC As String : msgChkDskC = ("[ " & Now & " ] PC - *" & pcSerial & "* - running disk check on drive C")
Call WriteToLog(title, msgChkDskC)
ChkDskC.RunWorkerAsync()
End Sub
Private Sub ChkDskC_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles ChkDskC.DoWork
Dim dc As New Process
dc.StartInfo.FileName = "chkdsk.exe"
dc.StartInfo.Arguments = " c: /f"
dc.StartInfo.CreateNoWindow = True
dc.StartInfo.UseShellExecute = False
dc.StartInfo.RedirectStandardOutput = True
dc.StartInfo.RedirectStandardError = True
dc.EnableRaisingEvents = True
Application.DoEvents()
AddHandler dc.ErrorDataReceived, AddressOf proc_OutputDataReceived
AddHandler dc.OutputDataReceived, AddressOf proc_OutputDataReceived
dc.Start()
dc.BeginErrorReadLine()
dc.BeginOutputReadLine()
dc.WaitForExit()
End Sub
Private Sub ChkDskC_RunWorkerCompleted(sender As Object, e As ComponentModel.RunWorkerCompletedEventArgs) Handles ChkDskC.RunWorkerCompleted
Output("[ " & Now & " ] PC - *" & pcSerial & "* - drive C had no errors")
Dim msgChkDskC As String : msgChkDskC = ("[ " & Now & " ] PC - *" & pcSerial & "* - drive C had no errors")
Call WriteToLog(title, msgChkDskC)
Output("[ " & Now & " ] PC - *" & pcSerial & "* - running disk check on drive D")
Dim msgChkDskD As String : msgChkDskD = ("[ " & Now & " ] PC - *" & pcSerial & "* - running disk check on drive D")
Call WriteToLog(title, msgChkDskD)
ChkDskD.RunWorkerAsync()
End Sub
Private Sub ChkDskD_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles ChkDskD.DoWork
Dim dc As New Process
dc.StartInfo.FileName = "chkdsk.exe"
dc.StartInfo.Arguments = " d: /f"
dc.StartInfo.CreateNoWindow = True
dc.StartInfo.UseShellExecute = False
dc.StartInfo.RedirectStandardOutput = True
dc.StartInfo.RedirectStandardError = True
dc.EnableRaisingEvents = True
Application.DoEvents()
AddHandler dc.ErrorDataReceived, AddressOf proc_OutputDataReceived
AddHandler dc.OutputDataReceived, AddressOf proc_OutputDataReceived
dc.Start()
dc.BeginErrorReadLine()
dc.BeginOutputReadLine()
dc.WaitForExit()
End Sub
Private Sub ChkDskD_RunWorkerCompleted(sender As Object, e As ComponentModel.RunWorkerCompletedEventArgs) Handles ChkDskD.RunWorkerCompleted
Output("[ " & Now & " ] PC - *" & pcSerial & "* - drive D had no errors")
Dim msgChkDskD As String : msgChkDskD = ("[ " & Now & " ] PC - *" & pcSerial & "* - drive D had no errors")
Call WriteToLog(title, msgChkDskD)
Output("[ " & Now & " ] PC - *" & pcSerial & "* - imaging C drive")
Dim msgDismC As String : msgDismC = ("[ " & Now & " ] PC - *" & pcSerial & "* - imaging C drive")
Call WriteToLog(title, msgDismC)
DismC.RunWorkerAsync()
End Sub
Private Sub DismC_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles DismC.DoWork
If pcModel = "Server" Then
pctype = "srvr"
Else
pctype = "wkstn"
End If
'Image C Drive
Dim dismC As New Process
dismC.StartInfo.FileName = "dism.exe"
dismC.StartInfo.Arguments = " /Apply-Image /ImageFile:t:\" & pctype & ".wim /index:1 /ApplyDir:c:\"
dismC.StartInfo.CreateNoWindow = True
dismC.StartInfo.UseShellExecute = False
dismC.StartInfo.RedirectStandardOutput = True
dismC.StartInfo.RedirectStandardError = True
dismC.EnableRaisingEvents = True
Application.DoEvents()
AddHandler dismC.ErrorDataReceived, AddressOf proc_OutputDataReceived
AddHandler dismC.OutputDataReceived, AddressOf proc_OutputDataReceived
dismC.Start()
dismC.BeginErrorReadLine()
dismC.BeginOutputReadLine()
dismC.WaitForExit()
End Sub
Private Sub DismC_RunWorkerCompleted(sender As Object, e As ComponentModel.RunWorkerCompletedEventArgs) Handles DismC.RunWorkerCompleted
Output("[ " & Now & " ] PC - *" & pcSerial & "* - drive C imaged")
Dim msgDismC As String : msgDismC = ("[ " & Now & " ] PC - *" & pcSerial & "* - drive C imaged")
Call WriteToLog(title, msgDismC)
Output("[ " & Now & " ] PC - *" & pcSerial & "* - imaging D drive")
Dim msgDismD As String : msgDismD = ("[ " & Now & " ] PC - *" & pcSerial & "* - imaging D drive")
Call WriteToLog(title, msgDismD)
DismD.RunWorkerAsync()
End Sub
Private Sub DismD_DoWork(sender As Object, e As ComponentModel.DoWorkEventArgs) Handles DismD.DoWork
If pcModel = "Server" Then
pctype = "srvr"
Else
pctype = "wkstn"
End If
'Image D Drive
Dim dismD As New Process
dismD.StartInfo.FileName = "dism.exe"
dismD.StartInfo.Arguments = " /Apply-Image /ImageFile:t:\" & pctype & ".wim /index:2 /ApplyDir:d:\"
dismD.StartInfo.CreateNoWindow = True
dismD.StartInfo.UseShellExecute = False
dismD.StartInfo.RedirectStandardOutput = True
dismD.StartInfo.RedirectStandardError = True
dismD.EnableRaisingEvents = True
Application.DoEvents()
AddHandler dismD.ErrorDataReceived, AddressOf proc_OutputDataReceived
AddHandler dismD.OutputDataReceived, AddressOf proc_OutputDataReceived
dismD.Start()
dismD.BeginErrorReadLine()
dismD.BeginOutputReadLine()
dismD.WaitForExit()
End Sub
Private Sub DismD_RunWorkerCompleted(sender As Object, e As ComponentModel.RunWorkerCompletedEventArgs) Handles DismD.RunWorkerCompleted
Output("[ " & Now & " ] PC - *" & pcSerial & "* - drive D imaged")
Dim msgDismD As String : msgDismD = ("[ " & Now & " ] PC - *" & pcSerial & "* - drive D imaged")
Call WriteToLog(title, msgDismD)
Output("[ " & Now & " ] PC - *" & pcSerial & "* - imaging complete, rebooting")
'Call reboot()
End Sub
Private Sub reboot()
'Reboots a pc while in WinPE
Dim reset As New Process
reset.StartInfo.FileName = "wpeutils.exe"
reset.StartInfo.Arguments = " shutdown"
reset.Start()
End Sub
Private Sub WriteToLog(ByVal title As String, ByVal msg As String)
'Check and make directory
If Not System.IO.Directory.Exists("t:\logs\") Then
System.IO.Directory.CreateDirectory("t:\logs\")
End If
'Check and make file
Dim fs As FileStream = New FileStream("t:\logs\" & pcSerial & ".log", FileMode.OpenOrCreate, FileAccess.ReadWrite)
Dim s As StreamWriter = New StreamWriter(fs)
s.Close()
fs.Close()
'Logging
Dim fs1 As FileStream = New FileStream("t:\logs\" & pcSerial & ".log", FileMode.Append, FileAccess.Write)
Dim s1 As StreamWriter = New StreamWriter(fs1)
s1.Write("Title: " & title & vbCrLf)
s1.Write("Message: " & msg & vbCrLf)
s1.Write("================================================" & vbCrLf)
s1.Close()
fs1.Close()
End Sub
Private Sub Output(s As String)
'Output to form window
If s <> "" Then
tb1.AppendText(vbCrLf & ">> " & s)
End If
End Sub
Public ReadOnly Property Model()
Get
Model = pcModel
End Get
End Property
Public Function GetBiosSerialNumber() As String
Dim OutputString As String = String.Empty
Using Process As New Process
AddHandler Process.OutputDataReceived,
Sub(sender As Object, e As DataReceivedEventArgs)
OutputString = OutputString & e.Data & vbCrLf
End Sub
With Process.StartInfo
.FileName = "cmd"
.UseShellExecute = False
.CreateNoWindow = True
.RedirectStandardInput = True
.RedirectStandardOutput = True
.RedirectStandardError = True
End With
With Process
.Start()
.BeginOutputReadLine()
End With
Using InputStream As System.IO.StreamWriter = Process.StandardInput
With InputStream
.AutoFlush = True
.Write("wmic bios get serialnumber" & vbCrLf)
End With
End Using
Do
Application.DoEvents()
Loop Until Process.HasExited
End Using
Return Replace(OutputString.Split(CChar(vbCrLf)).ToList(6).Substring(1), " ", "")
End Function
Public Sub UpdateTextBox(text As String)
rtb1.Text += text & Environment.NewLine
rtb1.SelectionStart = rtb1.Text.Length
rtb1.ScrollToCaret()
End Sub
Public Sub proc_OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
If Me.InvokeRequired = True Then
Me.Invoke(myDelegate, e.Data)
Else
UpdateTextBox(e.Data)
End If
End Sub
End Class

Form is sent to back after function runs

I've got the following section of code:
Public Sub SendTestEmail()
Try
Dim Mail As New MailMessage
Mail.Subject = "Test email"
Mail.To.Add(smtpTXTsendto.Text)
Mail.From = New MailAddress(smtpTXTusername.Text)
Mail.Body = "This is a test message"
Dim SMTP As New SmtpClient(smtpTXTserver.Text)
If smtpCHECKssl.Checked = True Then
SMTP.EnableSsl = True
Else
SMTP.EnableSsl = False
End If
SMTP.Credentials = New System.Net.NetworkCredential(smtpTXTusername.Text, smtpTXTpassword.Text)
SMTP.Port = smtpTXTport.Text
SMTP.Send(Mail)
MessageBox.Show("A test email has been sent." & Environment.NewLine & Environment.NewLine & "To: " & smtpTXTsendto.Text & Environment.NewLine & "From: " & smtpTXTusername.Text & "." & Environment.NewLine & Environment.NewLine & "If you did not recieve an email, please check your settings and try again.", "Test Email")
Catch ex1 As Exception
MessageBox.Show(ex1.Message)
Return
End Try
End Sub
The Sub SendTestEmail is called inside of a Background worker.
The odd issue I'm having, as that when a MessageBox appears, and I click OK the form gets sent to the back of the screen, behind all applications ...
I've tried adding a Me.focus, but it gives me issues about Cross Tread violations.
Any ideas why this is happening?
Background Worker Code:
Private Sub BGWSendTestEmail_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BGWSendTestEmail.DoWork
SendTestEmail()
End Sub
Private Sub BGWSendTestEmail_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BGWSendTestEmail.RunWorkerCompleted
If (e.Cancelled) Then
MsgBox("Something went wrong!")
Else
GroupBoxTesting.Visible = False
Me.Enabled = True
End If
End Sub
Private Sub SMTPButtonTest_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SMTPButtonTest.Click
GroupBoxTesting.Visible = True
Me.Enabled = False
BGWSendTestEmail.RunWorkerAsync()
End Sub
Change BGWSendTestEmail_RunWorkerCompleted to something like this and remove exception handling from SendTestEmail
Me.Enabled = True ' Always enable form first after completed
If e.Error Is Nothing Then
If Not e.Cancelled Then
MessageBox.Show("A test email has been sent." _
& Environment.NewLine _
& Environment.NewLine _
& "To: " & smtpTXTsendto.Text _
& Environment.NewLine _
& "From: " & smtpTXTusername.Text _
& "." & Environment.NewLine _
& Environment.NewLine _
& "If you did not recieve an email, please check your settings and try again.", _
"Test Email")
GroupBoxTesting.Visible = False 'Maybe put this also into start of method?
Else
MsgBox("Something went wrong!")
End If
Else
MessageBox.Show("Email sending failed. Exception: " & e.Error.Message)
End If
If you debug this program your debugger will attach exceptions in do_work method, but if you run it without debugger then exceptions are handled at completed method.

'Else' must be preceded by a matching 'If' or 'ElseIf'

I cant run my program due to this error. Can somebody help me? Thanks.
Public Class Login
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
If tbx_username.Text <> "" And tbx_pass.Text <> "" Then
Dim SM As New SubjectMaintenance
Dim dr = SM.openSel(SqlString.getSQLSelect(Account.tablename, Account.si_data_username & "='" & tbx_username.Text & "' and " & Account.si_data_pwd & "='" & tbx_pass.Text & "'"), CommandType.Text)
While dr.Read
GUI.accnt.pData_id = dr(Account.si_data_id)
Me.Hide()
GUI.Show()
**Else**
GUI.accnt.pData_pwd = dr(Account.si_data_pwd)
GUI.accnt.pData_username = dr(Account.si_data_username)
GUI.accnt.pData_lname = dr(Account.si_data_lname)
GUI.accnt.pData_fname = dr(Account.si_data_fname)
GUI.accnt.pData_mname = dr(Account.si_data_mname)
End While
SM.closeConDr()
If GUI.accnt.pData_id > 0 Then
MessageBox.Show("Login Failed!")
End If
End If
End Sub
End Class
You cannot put an else inside while end-while, the if-else-end if and while-end while are standalone statements, so you can mix them as follows:
while
if
else
end if
end while
or
if
while
end while
else
while
end while
end if
The only way to break into a nested statement is the GoTo statement, it moves the instruction pointer unconditionally to the specified label.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
If tbx_username.Text <> "" And tbx_pass.Text <> "" Then
Dim SM As New SubjectMaintenance
Dim dr = SM.openSel(SqlString.getSQLSelect(Account.tablename, Account.si_data_username & "='" & tbx_username.Text & "' and " & Account.si_data_pwd & "='" & tbx_pass.Text & "'"), CommandType.Text)
While dr.Read
GUI.accnt.pData_id = dr(Account.si_data_id)
Me.Hide()
GUI.Show()
End While
**Else** 'Try moving the else below the end while or above the while
GUI.accnt.pData_pwd = dr(Account.si_data_pwd)
GUI.accnt.pData_username = dr(Account.si_data_username)
GUI.accnt.pData_lname = dr(Account.si_data_lname)
GUI.accnt.pData_fname = dr(Account.si_data_fname)
GUI.accnt.pData_mname = dr(Account.si_data_mname)
SM.closeConDr()
If GUI.accnt.pData_id > 0 Then
MessageBox.Show("Login Failed!")
End If
End If
End Sub
'Try moving the else below the end while or above the while

IMAPI2 in VB 2008 progress bar

I start making program that will burn CD/DVDs, and everything is okay.
I found way to burn with IMAPI2 API, but now I have problem:
I can't get progress bar of that burning.
Here is code:
Dim CDD1 As New IMAPI2.MsftDiscMaster2
Dim CDD2 As New IMAPI2.MsftDiscRecorder2
Dim FSI As New IMAPI2FS.MsftFileSystemImage
Dim CDD3 As New IMAPI2.MsftDiscFormat2Data
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Index = 0
Dim UniqueID = ""
Dim Directory
Dim Path = "C:\lll"
Dim result
Dim Stream
Label1.Text = "----- Started -----."
UniqueID = CDD1.Item(Index)
Label1.Text = Label1.Text & vbCrLf & "ID found: " & UniqueID
CDD2.InitializeDiscRecorder(UniqueID)
Label1.Text = Label1.Text & vbCrLf & "Recorder selected!"
Directory = FSI.Root
Label1.Text = Label1.Text & vbCrLf & "Directory is here: " & Directory.ToString
CDD3.Recorder = CDD2
Label1.Text = Label1.Text & vbCrLf & "Recorder 2 selected!"
CDD3.ClientName = "IMAPI2 TEST"
Label1.Text = Label1.Text & vbCrLf & "Client Name Selected!"
FSI.ChooseImageDefaults(CDD2)
Label1.Text = Label1.Text & vbCrLf & "Default selected!"
Directory.AddTree(Path, False)
Label1.Text = Label1.Text & vbCrLf & "Directory added!"
result = FSI.CreateResultImage()
Stream = result.ImageStream
Label1.Text = Label1.Text & vbCrLf & "Writing content to disc..."
If (CDD3.IsCurrentMediaSupported(CDD2) = True) Then
If (CDD3.IsRecorderSupported(CDD2) = True) Then
CDD3.Write(Stream)
Else
MsgBox("Not Suported Recorder!")
End If
Else
MsgBox("Not Suported Media!")
End If
Label1.Text = Label1.Text & vbCrLf & "----- Finished -----"
End Sub
When command
CDD3.Write(Stream)
is triggered, program freeze, and don't respond until data is burned completely.
Is there any way to stop this, to stop program freezing and enabling progress bar?
Thanks.
You need to use threading. So in your button click event handler you start off a new thread that does the actual burning and while that's going on in it's separate thread, the main thread can continue to update the GUI (including your progress bar).
See Thread.Start for a simple sample and if you want further information I'd suggest starting here: Managed Threading