Classes and textbox is not a member of class generate - vb.net

Hello i'm trying to move my code to difrent classes so i can keep everything organized.
What i have now:
Public Async Sub GenButton_Click(sender As Object, e As EventArgs) Handles GenButton.Click
Dim tasks As New List(Of Task)()
tasks.Add(Task.Run(AddressOf generate))
Await Task.WhenAll(tasks)
generatedlines.Text = My.Computer.FileSystem.ReadAllText(Application.StartupPath & "\Generated" & Me.NumericUpDown3.Value & ".txt")
Me.generatedlines.Lines = Me.generatedlines.Lines.Distinct.ToArray
generatedlines.SaveFile(Application.StartupPath & "\Generated" & Me.NumericUpDown3.Value & ".txt", RichTextBoxStreamType.PlainText)
MessageBox.Show("lines generated in Generated" & Me.NumericUpDown3.Value & ".txt", "Task Completed!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
End Sub
What i want:
Public Class Form1
Public Async Sub GenButton_Click(sender As Object, e As EventArgs) Handles GenButton.Click
//run code of class generate
end sub
end class
public class generate
Dim tasks As New List(Of Task)()
tasks.Add(Task.Run(AddressOf generate))
Await Task.WhenAll(tasks)
generatedlines.Text = My.Computer.FileSystem.ReadAllText(Application.StartupPath & "\Generated" & Me.NumericUpDown3.Value & ".txt")
Me.generatedlines.Lines = Me.generatedlines.Lines.Distinct.ToArray
generatedlines.SaveFile(Application.StartupPath & "\Generated" & Me.NumericUpDown3.Value & ".txt", RichTextBoxStreamType.PlainText)
MessageBox.Show("lines generated in Generated" & Me.NumericUpDown3.Value & ".txt", "Task Completed!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
end class
I tried this before but it will give errors like "generatedlines is not a member of class generated"

Related

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

Read String From Serial port Visual Basic

Imports System.IO.Ports
Imports System.Text
Public Class Form4
Dim myStringBuilder As String
Dim insert As New OleDb.OleDbCommand
Dim cnn As New OleDb.OleDbConnection
Public user As String
Private Sub Serialport2_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort2.DataReceived
myStringBuilder = SerialPort2.ReadExisting()
Me.Invoke(New EventHandler(AddressOf UpdateControls))
End Sub
Private Sub UpdateControls(ByVal sender As Object, ByVal e As EventArgs)
Dim A As String = myStringBuilder
Dim Sqql As String
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
insert.Connection = cnn
Dim dt As New DataTable
Sqql = "SELECT * FROM `FileInfo` WHERE `File ID`='" & A & "'"
Dim cmd As New OleDb.OleDbDataAdapter(Sqql, cnn)
cmd.Fill(dt)
Dim i As Integer = dt.Rows.Count
Dim todaysdate As String = String.Format("{0:dd/MM/yyyy}", DateTime.Now)
If i = 1 Then
insert.CommandText = "INSERT INTO `File Log`(File ID,Name,Information,Time,Date) " & _
" VALUES('" & A & "','" & dt.Rows(0).Item("Name") & "','" & user & " telah" & dt.Rows(0).Item("Status") & "File" & "','" &
_
TimeOfDay & "','" & todaysdate & "')"
textBox1.Text += dt.Rows(0).Item("Name") & " " & TimeOfDay & " " & todaysdate &
Environment.NewLine
textBox1.Select(textBox1.TextLength, 0)
textBox1.ScrollToCaret()
insert.ExecuteNonQuery()
myStringBuilder = ""
Else
myStringBuilder = ""
textBox1.Text += A & Environment.NewLine
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cnn = New OleDb.OleDbConnection
cnn.ConnectionString = "Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & Application.StartupPath & "\data.mdb"
If SerialPort2 IsNot Nothing Then
SerialPort2.Close()
End If
SerialPort2 = My.Computer.Ports.OpenSerialPort("COM27", 9600, Parity.None, 8, StopBits.One)
textBox1.Text = "-- Door Have Open -- " & Environment.NewLine & Environment.NewLine
End Sub
Private Sub textBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles textBox1.TextChanged
End Sub End Class
in my serial monitor view it will appear correctly but in visual basic it will auto break line and not display the string in one line.
I Tried other method like serialport.readline() but nothing happen.
If you are having issues with extracting data from your serial port you could try this:
Sub SerialPort_DataReceived(sender As Object, e As SerialDataReceivedEventArgs)
Dim currentSP As SerialPort = Convert.ChangeType(sender, GetType(SerialPort))
Dim strBuilder As System.Text.StringBuilder = New System.Text.StringBuilder()
For index = 1 To currentSP.BytesToRead
strBuilder.Append(Convert.ChangeType(currentSP.ReadByte(), GetType(Char)))
Next
' Have a global string to allow the threads to have a shared resource
myString = strBuilder.ToString()
Me.Invoke(New EventHandler(AddressOf UpdateControls))
End Sub
It should work the same way as the SerialPort.ReadLine(), this approach also lets you manipulate the data however you want. Instead of working with a string you could always work the data like this:
Dim buffer As Byte() = New Byte(currentSP.BytesToRead) {}
buffer(index) = Convert.ChangeType(currentSP.ReadByte(), GetType(Byte))
So instead of appending the Char to the String you can add the Byte to the buffer
Dim str As String = MyCOMPort.ReadExisting()
If Me.InvokeRequired Then
Me.Invoke(New dlUpdateText(AddressOf updatetext), str)
Else
updatetext(str)
End If

Retrieve errors from MySQLDataAdapter.update()

I'm deliberately trying to change my dataset to have a duplicate primary key with the expectation that this action would throw a mysql error.
How can I retrieve such errors from MySQLDataAdapter.Update()??
I've had a brief look at event handlers but I can't seem to find where to get the error anywhere. Although I did notice that MySqlRowUpdatingEventArgs.Status = SkipCurrentRow
Code snippet:
Private Sub UpdateTable()
Dim MyCommandBuilder As New MySqlCommandBuilder(MyDataadapter)
txtConsole.AppendText(vbNewLine & MyDataSet.HasErrors.ToString)
AddHandler MyDataadapter.RowUpdating, AddressOf OnRowUpdating
AddHandler MyDataadapter.RowUpdated, AddressOf OnRowUpdated
If MyDataSet.GetChanges() Is Nothing Then
MessageBox.Show("The table contains no changes to save.")
Else
' Without the MySqlCommandBuilder this line would fail.
Try
Dim rowsAffected As Integer = MyDataadapter.Update(MyDataTable)
If rowsAffected = 0 Then
MessageBox.Show("No rows were affected by the save operation.")
Else
MessageBox.Show(rowsAffected & " rows were affected by the save operation.")
End If
Catch ex As MySqlException
txtConsole.AppendText(vbNewLine & "Error: " & ex.ToString())
End Try
End If
RemoveHandler MyDataadapter.RowUpdating, AddressOf OnRowUpdating
RemoveHandler MyDataadapter.RowUpdated, AddressOf OnRowUpdated
End Sub
' handler for RowUpdating event
Private Shared Sub OnRowUpdating(sender As Object, e As MySqlRowUpdatingEventArgs)
PrintEventArgs(e)
End Sub
' handler for RowUpdated event
Private Shared Sub OnRowUpdated(sender As Object, e As MySqlRowUpdatedEventArgs)
PrintEventArgs(e)
End Sub
Private Overloads Shared Sub PrintEventArgs(args As MySqlRowUpdatingEventArgs)
Console.WriteLine("OnRowUpdating")
Console.WriteLine(" event args: (" & " command=" & args.Command.CommandText & _
" commandType=" & args.StatementType & " status=" & args.Status & ")")
End Sub
Private Overloads Shared Sub PrintEventArgs(args As MySqlRowUpdatedEventArgs)
Console.WriteLine("OnRowUpdated")
Console.WriteLine(" event args: (" & " command=" & args.Command.CommandText & _
" commandType=" & args.StatementType & " recordsAffected=" & _
args.RecordsAffected & " status=" & args.Status & ")")
End Sub

How to solve this . The process cannot access the file

The process cannot access the file 'F:\copy back up\system\HRM 2-5-2013\HRM\HRM\lanbased.txt' because it is being used by another process.
This is my code in sub main
Public localhost As String
Public username As String
Public port As String
Public database As String
Public conn As New MySqlConnection
Public NAME1 As String = "F:\copy back up\system\HRM 2-5-2013\HRM\HRM\lanbased.txt"
Public Sub main()
Dim frm As New Form1
Dim frm1 As New create
If System.IO.File.Exists(NAME1) = True Then
Try
Dim objReader As New System.IO.StreamReader(NAME1)
localhost = objReader.ReadLine() & vbNewLine
username = objReader.ReadLine() & vbNewLine
port = objReader.ReadLine() & vbNewLine
database = objReader.ReadLine() & vbNewLine
conn.ConnectionString = "server=" & Trim(localhost) & ";user id=" & Trim(username) & "; password=" & Trim(port) & "; database=" & Trim(database) & ""
conn.Open()
Application.Run(New Form1())
Catch ex As Exception
MsgBox("Unable to connect to database", vbCritical)
Application.Run(New create())
End Try
End If
Exit Sub
End Sub
and this is my code in my form create.
How do I access the file when it is being used by another process?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim FILE_NAME As String = "F:\copy back up\system\HRM 2-5-2013\HRM\HRM\lanbased.txt"
If TextBox1.Text = Nothing Or TextBox2.Text = Nothing Or TextBox3.Text = Nothing Or TextBox4.Text = Nothing Then
MsgBox("fill up mo pa ngot")
ElseIf System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
objWriter.Write(TextBox1.Text + vbCrLf)
objWriter.Write(TextBox2.Text + vbCrLf)
objWriter.Write(TextBox3.Text + vbCrLf)
objWriter.Write(TextBox4.Text + vbCrLf)
objWriter.Close()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
ElseIf conn.State = True Then
MsgBox("maka connect naka")
End If
End Sub
first you open your file for reading here :
Dim objReader As New System.IO.StreamReader(NAME1) //1st open
Second you call the form1 : Application.Run(New Form1())
in that Form you have : Dim objWriter As New System.IO.StreamWriter(FILE_NAME) //2nd open
But wait you didn't close your file so you can't open it 2nd time for writing.
So you need to close the file before calling create form 1 like objReader.close()
conn.Open()
objReader.close() <----- this one
Application.Run(New Form1())
Looks like you need to close your streamReader before opening the new form:
objReader.Close()
That will free the file.

Saving an Image in VB.NET

I have a little code for saving an image from an URL in VB.NET but im not finding the location where it saves the image, i added a location string but i dont know how to use it in the code.
How do i change the location whre my code saves the image ( Imports System.Drawing
Public Class Form1)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim MyImage As System.Drawing.Image
Dim URL As String = TextBox1.Text
Dim FileName As String, URLpieces As String()
Dim location As String = "C:/SaveIMGURL/"
URLpieces = Split(URL, "/")
FileName = URLpieces.GetValue(UBound(URLpieces))
MyImage = GetImage(URL)
MyImage.Save(FileName)
MyImage = Nothing
End Sub
Function GetImage(ByVal URL As String) As System.Drawing.Image
Dim Request As System.Net.HttpWebRequest
Dim Response As System.Net.HttpWebResponse
Request = System.Net.WebRequest.Create(URL)
Response = CType(Request.GetResponse, System.Net.WebResponse)
If Request.HaveResponse Then
If Response.StatusCode = Net.HttpStatusCode.OK Then
GetImage = System.Drawing.Image.FromStream(Response.GetResponseStream)
End If
End If
Try
Catch e As System.Net.WebException
MsgBox("A web exception has occured [" & URL & "]." & vbCrLf & " System returned: " & e.Message, MsgBoxStyle.Exclamation, "Error!")
Exit Try
Catch e As System.Net.ProtocolViolationException
MsgBox("A protocol violation has occured [" & URL & "]." & vbCrLf & " System returned: " & e.Message, MsgBoxStyle.Exclamation, "Error!")
Exit Try
Catch e As System.Net.Sockets.SocketException
MsgBox("Socket error [" & URL & "]." & vbCrLf & " System returned: " & e.Message, MsgBoxStyle.Exclamation, "Error!")
Exit Try
Catch e As System.IO.EndOfStreamException
MsgBox("An IO stream exception has occured. System returned: " & e.Message, MsgBoxStyle.Exclamation, "Error!")
Exit Try
Finally
End Try
End Function
End Class