Here is my program for auto email with manual attachments on certain time using config.ini for email username and password
Imports System.Net.Mail
Imports System.Timers
Public Class Form1
Dim file(2) As String
Dim pesan As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = "Water Monitoring"
Timer1.Start()
End Sub
Public Sub kirim() 'step send e-mail manual'
Try
Dim Smtp_Server As New SmtpClient
Dim e_mail As New MailMessage()
Dim txtEmail As String
Dim txtPassword As String
txtEmail = Module1.Read_INI("GENERAL", "Email")
txtPassword = Module1.Read_INI("GENERAL", "Password")
Smtp_Server.UseDefaultCredentials = False
Smtp_Server.Credentials = New Net.NetworkCredential(txtEmail, txtPassword) 'login email'
Smtp_Server.Port = 587
Smtp_Server.Timeout = 3000000
Smtp_Server.EnableSsl = True
Smtp_Server.Host = "smtp.gmail.com"
e_mail = New MailMessage()
e_mail.From = New MailAddress(txtEmail)
e_mail.To.Add(txtTo.Text)
e_mail.Subject = txtSubject.Text
e_mail.IsBodyHtml = False
e_mail.Body = pesan
If Not txtFile1.Text = Nothing Then
Dim attach As New Attachment(txtFile1.Text)
e_mail.Attachments.Add(attach) 'attach attachment 1
End If
If Not txtFile2.Text = Nothing Then
Dim attach As New Attachment(txtFile2.Text)
e_mail.Attachments.Add(attach) 'attach attachment 2
End If
If Not txtFile3.Text = Nothing Then
Dim attach As New Attachment(txtFile3.Text)
e_mail.Attachments.Add(attach) 'attach attachment 3
End If
Smtp_Server.Send(e_mail)
MsgBox("Mail Sent")
Catch error_t As Exception
MsgBox(error_t.ToString) 'message box error
End Try
End Sub
Private Sub chckboxAuto30s_CheckedChanged(sender As Object, e As EventArgs) Handles chckboxAuto30s.CheckedChanged
If chckboxAuto30s.Checked = True Then
btnSend.Visible = False
Else
btnSend.Visible = True
End If
End Sub
Private Sub txtMessage_TextChanged(sender As Object, e As EventArgs) Handles txtMessage.TextChanged
pesan = txtMessage.Text
End Sub
Private Sub btnCancelAllAttachments_Click(sender As Object, e As EventArgs) Handles btnCancelAllAttachments.Click
txtFile1.Text = ""
txtFile2.Text = ""
txtFile3.Text = ""
file = Nothing
End Sub
Private Sub btnAddAttachments_Click(sender As Object, e As EventArgs) Handles btnAddAttachments.Click
file = Nothing
OpenFileDialog1.ShowDialog()
file = OpenFileDialog1.FileNames
txtFile1.Text = file(0)
Try
txtFile2.Text = file(1)
Catch ex As IndexOutOfRangeException
End Try
Try
txtFile3.Text = file(2)
Catch ex As IndexOutOfRangeException 'attach file attachment'
End Try
End Sub
Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
kirim() 'send e-mail manual'
End Sub
Private Sub btnClearText_Click(sender As Object, e As EventArgs) Handles btnClearText.Click
txtTo.Text = ""
txtSubject.Text = ""
txtMessage.Text = ""
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim timerforAuto As Date
timerforAuto = CDate(timeAuto.Text)
If timerforAuto.Hour = Now.Hour And timerforAuto.Minute = Now.Minute And timerforAuto.Second = Now.Second Then
kirim()
End If
End Sub
End Class
My question is, how to setting the attachments is choosed automatically? I want to attach file automatically based on current time.
For example : i want to attach
C:\testing1.xlsx
C:\testing2.xlsx
automatically. And refresh the file if the file contents in the xlsx have changed every day.
Change your kirim() call in the timer1_tick to accept a date parameter.
Public Sub kirim(TimeKickedOff as Date) 'step send e-mail manual'
Try
Dim Smtp_Server As New SmtpClient
Dim e_mail As New MailMessage()
Dim txtEmail As String
Dim txtPassword As String
txtEmail = Module1.Read_INI("GENERAL", "Email")
txtPassword = Module1.Read_INI("GENERAL", "Password")
Smtp_Server.UseDefaultCredentials = False
Smtp_Server.Credentials = New Net.NetworkCredential(txtEmail, txtPassword) 'login email'
Smtp_Server.Port = 587
Smtp_Server.Timeout = 3000000
Smtp_Server.EnableSsl = True
Smtp_Server.Host = "smtp.gmail.com"
e_mail = New MailMessage()
e_mail.From = New MailAddress(txtEmail)
e_mail.To.Add(txtTo.Text)
e_mail.Subject = txtSubject.Text
e_mail.IsBodyHtml = False
e_mail.Body = pesan
If Not txtFile1.Text = Nothing Then
Dim attach As New Attachment(txtFile1.Text)
e_mail.Attachments.Add(attach) 'attach attachment 1
End If
If Not txtFile2.Text = Nothing Then
Dim attach As New Attachment(txtFile2.Text)
e_mail.Attachments.Add(attach) 'attach attachment 2
End If
If Not txtFile3.Text = Nothing Then
Dim attach As New Attachment(txtFile3.Text)
e_mail.Attachments.Add(attach) 'attach attachment 3
End If
Smtp_Server.Send(e_mail)
MsgBox("Mail Sent")
Catch error_t As Exception
MsgBox(error_t.ToString) 'message box error
End Try
End Sub
Change the call in timer1_tick to pass the time it was kicked off to kirim.
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim timerforAuto As Date
timerforAuto = CDate(timeAuto.Text)
If timerforAuto.Hour = Now.Hour And timerforAuto.Minute = Now.Minute And timerforAuto.Second = Now.Second Then
kirim(timerforAuto)
End If
End Sub
In the kirim(TimeKickedOff as Date) sub add code that tests the TimeKickedOff to the datetime you want each attachment attached to the email, for example, in the kirim sub where SomeTime = the datetime you want the file attached:
If Not txtFile3.Text = Nothing Then
if TimeKickedOff.Hour = SomeTime.Hour And TimeKickedOff.Minute = SomeTime.Minute And TimeKickedOff.Second = SomeTime.Second Then
Dim attach As New Attachment(txtFile3.Text)
e_mail.Attachments.Add(attach) 'attach attachment 3
End If
End If
To test if a file has changed, you can handle this in the timer event. Dim a static variable that contains the content of the file and check to see if the content changes every so often and if the content changes do what you need to do when that happens and load the new content into the static variable so you can keep checking for newer changes.
I am trying to load a datatable async so that the UI remains responsive. I've used the dt.RowChanged event to handle reporting progress back to the progress bar and label. But when the Stop button is clicked, it causes the following error:
An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll.
I'm not sure how to find my way around this issue. Any guidance is appreciated. The following is code from sample project using AdventureWorks DB
Imports System.Threading
Imports System.Threading.Tasks
Public Class AsyncProgressCancel
Public strConnectionString As String = "data source=010XXX01;initial catalog=AdventureWorks2012;integrated security=SSPI;"
Private dt As DataTable
Private ds As DataSet
Dim dataset
Dim RecordCount As Integer = 1000000
Dim Counter As Integer
Dim myProgress As Progress(Of Integer)
Private Delegate Sub AsyncDelegate(ByVal value As Integer)
Private ProgressUpdater As New AsyncDelegate(AddressOf UpdateProgress)
Private TargetCounter As Integer = 1000
Private cts As CancellationTokenSource
Private Cancelled As Boolean
Private Sub AsyncProgressCancel_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ProgressBar1.Visible = False
lblProgress.Visible = False
btnStop.Enabled = False
End Sub
Private Async Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click
btnStart.Enabled = False
btnStop.Enabled = True
Cancelled = False
ProgressBar1.Value = 0
ProgressBar1.Maximum = RecordCount
ProgressBar1.Visible = True
lblProgress.Visible = True
DataGridView1.Enabled = False
cts = New CancellationTokenSource()
Try
Dim completed As Boolean = Await LoadDataAsync(myProgress, cts.Token)
Catch ex As OperationCanceledException
lblProgress.Text = "Retrieve cancelled."
DataGridView1.DataSource = Nothing
DataGridView1.Enabled = True
btnStop.Enabled = False
btnStart.Enabled = True
ProgressBar1.Visible = False
Catch ex As Exception
MsgBox(ex)
End Try
End Sub
Private Sub UpdateProgress(ByVal value As Integer)
If Cancelled = True Then
cts.Cancel()
Else
If ProgressBar1.InvokeRequired Then
ProgressBar1.Invoke(ProgressUpdater, New Object() {value})
ElseIf value > ProgressBar1.Maximum Then
value = ProgressBar1.Maximum
ProgressBar1.Value = value
End If
lblProgress.Text = Math.Round((value / RecordCount) * 100).ToString & "% complete" '"Step Number: " & myInt.ToString
ProgressBar1.Value = value
End If
End Sub
Private Async Function LoadDataAsync(ByVal myProgress As IProgress(Of Integer), token As CancellationToken) As Task(Of Boolean)
Dim comSQL As SqlClient.SqlCommand
Dim strSQL As String
Dim da As SqlClient.SqlDataAdapter
Dim dt As New DataTable
Dim ReturnValue As Boolean
Try
DataGridView1.Enabled = Await Task(Of Boolean).Run(Function()
Using conn As SqlClient.SqlConnection = New SqlClient.SqlConnection(strConnectionString)
conn.Open()
strSQL = "SELECT * FROM (SELECT TOP 1000000 PRODUCTION.PRODUCT.* FROM sales.SalesOrderDetail CROSS JOIN production.Product) A"
comSQL = New SqlClient.SqlCommand(strSQL, conn)
da = New SqlClient.SqlDataAdapter(comSQL)
AddHandler dt.RowChanged, Sub(obj, e)
If e.Action.Add Then
Counter = obj.Rows.Count
If Counter > RecordCount Then
Counter = RecordCount
Else
Counter = Counter + 1 ' Math.Ceiling(0.1 * RecordCount)
End If
End If
If token.IsCancellationRequested = True Then
token.ThrowIfCancellationRequested()
Else
If Counter = TargetCounter Then
UpdateProgress(Counter)
TargetCounter = TargetCounter + 1000
End If
End If
End Sub
If Counter > 0 Then
myProgress.Report(Counter)
End If
da.Fill(dt)
dataset = dt
ReturnValue = True
Return ReturnValue
End Using
End Function, token)
Catch ex As Exception
MsgBox(ex)
End Try
End Function
Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click
Try
If Not cts Is Nothing Then
cts.Cancel()
End If
Catch ex As Exception
MsgBox(ex)
End Try
End Sub
End Class
i have a CyberCafe Software Program with a code that sends a message by the client(socket) and received by the server(also a socket) using Network Stream. (i'm somewhat new about sockets and network stream)
Server Side:
'receive msg from client
Private Sub OnRecieve(ByVal ar As IAsyncResult)
Try
Dim ns As NetworkStream = CType(ar.AsyncState, NetworkStream)
ns.BeginRead(byteData, 0, byteData.Length, New AsyncCallback(AddressOf OnRecieve), ns)
Dim bytesRec As Byte() = byteData
Dim message As String = System.Text.ASCIIEncoding.ASCII.GetString(bytesRec)
Invoke(New _Read(AddressOf Read), message)
ns.Flush()
ns.Close()
Catch ex As Exception
'check for Disconnection or Force Disconnection
Invoke(New _dc(AddressOf dc))
End Try
End Sub
Client Side:
'send msg to server
Private Sub Send(ByVal msg As String, ByVal client As Socket)
Try
Dim sendBytes As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(msg)
NetStream = New NetworkStream(client)
NetStream.BeginWrite(sendBytes, 0, sendBytes.Length, New AsyncCallback(AddressOf OnSend), NetStream)
Catch ex As Exception
If Not clientSocket.Connected Then 'if connection was forcibly disconnected
'reconnecting to the server
Invoke(New _status(AddressOf status), clientSocket)
Connect()
End If
End Try
End Sub
The scenario is, there are 2 clients waiting to connect to the server(the other one is a Virtual Machine), and when i finally run the server, simultaneous connection had no problems, but receiving a message simultaneously didn't worked out. Sometimes it received one message only. Sometimes the message is wrong. Maybe a deadlock.
So, how can i implement this kind of situation? i asked Brother Google :P and he told me about AsyncTask, but i dunno how to do it :(
Any help would be obliged ^_^ Apologies for any bad english.
Update:
Sorry for my incomplete question.
I've added the EndRead/EndWrite method, but i'm not sure if i used the EndRead method right... I just inserted the EndRead before the BeginRead, but it still works though.
Thank you for the help Visual Vincent ^_^.
Also, my sockets are stored in the ListView as tag after they connect. And their IPAddress and HostName are stored in the database (MSAccess). And i don't have any TCP used in this code. Just Sockets and NetworkStreams. IDK if that is ok, but it works.
Server Side(Full):
Imports System.Net, System.Net.Sockets
Imports System.Data.OleDb
Public Class Server
Dim serverSocket As Socket
Dim clientSocket As Socket
Dim netstream As NetworkStream
Dim byteData(1023) As Byte
Dim ipEndPoint As IPEndPoint
Dim myList As New List(Of String)
Dim myList2 As New List(Of String)
Dim txt As String
'listening to clients from port 8800
Private Sub frmServer_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Invoke(New _AddExistingClient(AddressOf AddExistingClient))
Listen()
End Sub
Delegate Sub _AddExistingClient()
Private Sub AddExistingClient()
Try
If conn.State = ConnectionState.Open Then conn.Close()
conn.Open()
query = "select * from Clients_tbl"
comm = New OleDbCommand(query, conn)
reader = comm.ExecuteReader
While reader.Read
Dim lvi As New ListViewItem(reader("HostName").ToString)
lvi.Text = reader("HostName")
lvi.SubItems.Add("P00.00") 'price 1
lvi.SubItems.Add("00:00:00") 'time 2
lvi.ImageKey = "Grey.ico"
lsvClients.Items.Add(lvi)
End While
lsvClients.Sort()
conn.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub Listen()
Try
serverSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
ipEndPoint = New IPEndPoint(IPAddress.Any, 8800)
serverSocket.Bind(ipEndPoint)
serverSocket.Listen(1)
serverSocket.BeginAccept(New AsyncCallback(AddressOf OnAccept), Nothing)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub OnAccept(ByVal ar As IAsyncResult)
Try
clientSocket = serverSocket.EndAccept(ar)
serverSocket.BeginAccept(New AsyncCallback(AddressOf OnAccept), Nothing)
CheckIfExist(clientSocket)
netstream = New NetworkStream(clientSocket)
netstream.BeginRead(byteData, 0, byteData.Length, New AsyncCallback(AddressOf OnRecieve), netstream)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Delegate Sub _CheckIfExist(ByVal client As Socket)
Private Sub CheckIfExist(ByVal client As Socket)
Try
If InvokeRequired Then
Invoke(New _CheckIfExist(AddressOf CheckIfExist), client)
Exit Sub
End If
Dim RemoteIP As String = IPAddress.Parse(CType(client.RemoteEndPoint, IPEndPoint).Address.ToString).ToString
Dim host As String = Dns.GetHostEntry(RemoteIP).HostName.ToString
If conn.State = ConnectionState.Open Then conn.Close()
conn.Open()
query = "select * from Clients_tbl where HostName = '" + host + "'"
comm = New OleDbCommand(query, conn)
reader = comm.ExecuteReader
While reader.Read
If reader("IPAddress").ToString <> RemoteIP Then 'if socket do exist in the database but IPAddress was changed
ChangeIP(RemoteIP, host)
End If
count += 1
End While
If count = 0 Then 'if socket do not exist in the database
Add2DB(RemoteIP, host)
AddNewClient(client)
ElseIf count = 1 Then 'if socket do exist in the database and in the listview
For Each item As ListViewItem In lsvClients.Items
If item.Text = host Then
item.Tag = client
item.ImageKey = "Red.ico"
End If
Next
ElseIf count > 1 Then
MsgBox("Duplicate found")
End If
count = 0
conn.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Delegate Sub _ChangeIP(ByVal RemoteIP As String, ByVal host As String)
Private Sub ChangeIP(ByVal RemoteIP As String, ByVal host As String) 'connection is still opened
Try
If InvokeRequired Then
Invoke(New _ChangeIP(AddressOf ChangeIP), RemoteIP, host)
Exit Sub
End If
query = "update Clients_tbl set IPAddress = '" + RemoteIP + "' where HostName = '" + host + "'"
comm = New OleDbCommand(query, conn)
reader = comm.ExecuteReader
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Delegate Sub _Add2DB(ByVal RemoteIP As String, ByVal host As String)
Private Sub Add2DB(ByVal RemoteIP As String, ByVal host As String) 'connection is still opened
Try
If InvokeRequired Then
Invoke(New _Add2DB(AddressOf Add2DB), RemoteIP, host)
Exit Sub
End If
query = "insert into Clients_tbl values('" + RemoteIP + "', '" + host + "')"
comm = New OleDbCommand(query, conn)
reader = comm.ExecuteReader
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
'add client to ListView
Delegate Sub _AddNewClient(ByVal client As Socket)
Private Sub AddNewClient(ByVal client As Socket)
Try
If InvokeRequired Then
Invoke(New _AddNewClient(AddressOf AddNewClient), client)
Exit Sub
End If
Dim lvi As New ListViewItem(client.LocalEndPoint.ToString)
Dim RemoteIP As String = IPAddress.Parse(CType(client.RemoteEndPoint, IPEndPoint).Address.ToString).ToString
Dim host As String = Dns.GetHostEntry(RemoteIP).HostName.ToString
lvi.Text = host
lvi.Tag = client
lvi.SubItems.Add("P00.00") 'price 1
lvi.SubItems.Add("00:00:00") 'time 2
lvi.ImageKey = "Red.ico"
lsvClients.Items.Add(lvi)
lsvClients.Sort()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
'Send msg to specific client
Private Sub Send(ByVal msg As String, ByVal client As Socket)
Try
netstream = New NetworkStream(client)
Dim sendBytes As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(msg)
netstream.BeginWrite(sendBytes, 0, sendBytes.Length, New AsyncCallback(AddressOf OnSend), netstream)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub OnSend(ByVal ar As IAsyncResult)
Try
Dim ns As NetworkStream = CType(ar.AsyncState, NetworkStream)
ns.EndWrite(ar)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Delegate Sub _dc()
Private Sub dc()
For Each lvi As ListViewItem In lsvClients.Items
If Not lvi.Tag Is Nothing Then
Dim S As Socket = lvi.Tag
If Not S.Connected Then lvi.ImageKey = "Grey.ico"
End If
Next
End Sub
'receive msg from client
Private Sub OnRecieve(ByVal ar As IAsyncResult)
Try
Dim ns As NetworkStream = CType(ar.AsyncState, NetworkStream)
ns.EndRead(ar)
ns.BeginRead(byteData, 0, byteData.Length, New AsyncCallback(AddressOf OnRecieve), ns)
Dim bytesRec As Byte() = byteData
Dim message As String = System.Text.ASCIIEncoding.ASCII.GetString(bytesRec)
Invoke(New _Read(AddressOf Read), message)
ns.Flush()
ns.Close()
Catch ex As Exception
'check for Disconnection or Force Disconnection
Invoke(New _dc(AddressOf dc))
End Try
End Sub
Delegate Sub _Read(ByVal msg As String)
Private Sub Read(ByVal msg As String)
Try
myList2 = msg.Split("~").ToList
'mylist.Add("0") 'command number
'mylist.Add(host) 'host name of this client
'mylist.Add(lblState.Text)
'mylist.Add(lblTime.Tag.ToString)
Select Case Integer.Parse(myList2(0))
Case 0
For Each lvi As ListViewItem In lsvClients.Items
If lvi.Text = myList2(1) Then
If myList2(2) = "Timed" Then
lvi.ImageKey = "Green.ico"
ElseIf myList2(2) = "Open"
lvi.ImageKey = "Blue.ico"
End If
lvi.SubItems(2).Tag = Integer.Parse(myList2(3))
End If
Next
End Select
myList2.Clear()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
Invoke(New _Counter(AddressOf Counter))
End Sub
Delegate Sub _Counter()
Private Sub Counter()
Try
If lsvClients.Items.Count > 0 Then
For Each time As ListViewItem In lsvClients.Items
'//////////////
If time.ImageKey = "Green.ico" Then
time.SubItems(2).Tag -= 1
time.SubItems(2).Text = GetTime(time.SubItems(2).Tag)
If time.SubItems(2).Tag = 0 Then time.ImageKey = "Red.ico"
ElseIf time.ImageKey = "Blue.ico" Then
time.SubItems(2).Tag += 1
time.SubItems(2).Text = GetTime(time.SubItems(2).Tag)
End If
'//////////////
Next
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Function GetTime(ByVal time As Integer) As String
Dim Hrs As Integer 'number of hours '
Dim Min As Integer 'number of Minutes '
Dim Sec As Integer 'number of Sec '
'Seconds'
Sec = time Mod 60
'Minutes'
Min = ((time - Sec) / 60) Mod 60
'Hours'
Hrs = ((time - (Sec + (Min * 60))) / 3600) Mod 60
Return Format(Hrs, "00") & ":" & Format(Min, "00") & ":" & Format(Sec, "00")
End Function
Private Sub btnStartTime_Click(sender As Object, e As EventArgs) Handles btnStartTime.Click
Try
If lsvClients.SelectedItems.Count <> 0 Then
myList.Add("0")
myList.Add("10") 'time
myList.Add("15") 'price
txt = String.Join("~", myList)
Send(txt, lsvClients.SelectedItems(0).Tag)
lsvClients.SelectedItems(0).SubItems(2).Tag = myList(1)
lsvClients.SelectedItems(0).ImageKey = "Green.ico"
myList.Clear()
Else
MsgBox("Select first")
End If
Catch ex As Exception
Dim client As Socket = lsvClients.SelectedItems(0).Tag
If Not client.Connected Then
MsgBox("Disconnected")
End If
End Try
End Sub
Private Sub btnOpenTime_Click(sender As Object, e As EventArgs) Handles btnOpenTime.Click
Try
If lsvClients.SelectedItems.Count <> 0 Then
myList.Add("2")
myList.Add("0") 'time
myList.Add("0") 'price
txt = String.Join("~", myList)
Send(txt, lsvClients.SelectedItems(0).Tag)
lsvClients.SelectedItems(0).SubItems(2).Tag = myList(1)
lsvClients.SelectedItems(0).ImageKey = "Blue.ico"
myList.Clear()
Else
MsgBox("Select first")
End If
Catch ex As Exception
Dim client As Socket = lsvClients.SelectedItems(0).Tag
If Not client.Connected Then
MsgBox("Disconnected")
End If
End Try
End Sub
Private Sub btnExtendTime_Click(sender As Object, e As EventArgs) Handles btnExtendTime.Click
Try
If lsvClients.SelectedItems.Count <> 0 Then
myList.Add("1")
myList.Add("10") 'time
myList.Add("15") 'price
txt = String.Join("~", myList)
Send(txt, lsvClients.SelectedItems(0).Tag)
lsvClients.SelectedItems(0).SubItems(2).Tag += myList(1)
lsvClients.SelectedItems(0).ImageKey = "Green.ico"
myList.Clear()
Else
MsgBox("Select first")
End If
Catch ex As Exception
Dim client As Socket = lsvClients.SelectedItems(0).Tag
If Not client.Connected Then
MsgBox("Disconnected")
End If
End Try
End Sub
Private Sub btnPauseTime_Click(sender As Object, e As EventArgs) Handles btnPauseTime.Click
Try
If lsvClients.SelectedItems.Count <> 0 Then
myList.Add("3")
myList.Add("00:00:00") 'time
myList.Add("0") 'price
txt = String.Join("~", myList)
Send(txt, lsvClients.SelectedItems(0).Tag)
If lsvClients.SelectedItems(0).ImageKey = "Green.ico" Then
lsvClients.SelectedItems(0).ImageKey = "Green2Yellow.ico"
ElseIf lsvClients.SelectedItems(0).ImageKey = "Blue.ico"
lsvClients.SelectedItems(0).ImageKey = "Blue2Yellow.ico"
End If
myList.Clear()
Else
MsgBox("Select first")
End If
Catch ex As Exception
Dim client As Socket = lsvClients.SelectedItems(0).Tag
If Not client.Connected Then
MsgBox("Disconnected")
End If
End Try
End Sub
Private Sub btnResumeTime_Click(sender As Object, e As EventArgs) Handles btnResumeTime.Click
Try
If lsvClients.SelectedItems.Count <> 0 Then
myList.Add("4")
myList.Add("00:00:00") 'time
myList.Add("0") 'price
txt = String.Join("~", myList)
Send(txt, lsvClients.SelectedItems(0).Tag)
If lsvClients.SelectedItems(0).ImageKey = "Green2Yellow.ico" Then
lsvClients.SelectedItems(0).ImageKey = "Green.ico"
ElseIf lsvClients.SelectedItems(0).ImageKey = "Blue2Yellow.ico"
lsvClients.SelectedItems(0).ImageKey = "Blue.ico"
End If
myList.Clear()
Else
MsgBox("Select first")
End If
Catch ex As Exception
Dim client As Socket = lsvClients.SelectedItems(0).Tag
If Not client.Connected Then
MsgBox("Disconnected")
End If
End Try
End Sub
End Class
Client Side(full):
Imports System.Net, System.Net.Sockets, System.IO
Public Class Client
Dim clientSocket As Socket
Dim NetStream As NetworkStream
Dim byteData(1023) As Byte
Dim ipEndpoint As IPEndPoint
Dim host As String = Dns.GetHostName
Dim ip As IPAddress = IPAddress.Parse("192.168.56.1") 'Dns.GetHostEntry(host).AddressList(0)
Dim AppPath As String = Application.StartupPath
Dim writer As StreamWriter
Dim reader As StreamReader
Dim mylist As New List(Of String)
Dim txt As String
'/////////////////////connecting to server at port 8800
Private Sub Client_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
Try
Invoke(New _readtext(AddressOf readtext))
Connect()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub Connect()
Try
clientSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
ipEndpoint = New IPEndPoint(ip, 8800)
clientSocket.BeginConnect(ipEndpoint, New AsyncCallback(AddressOf OnConnect), Nothing)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub OnConnect(ByVal ar As IAsyncResult)
Try
Invoke(New _status(AddressOf status), clientSocket)
clientSocket.EndConnect(ar)
'Invoke(New _SendTimeState(AddressOf SendTimeState))
NetStream = New NetworkStream(clientSocket)
NetStream.BeginRead(byteData, 0, byteData.Length, New AsyncCallback(AddressOf Recieve), NetStream)
'Invoke(New _SendTimeState(AddressOf SendTimeState))
Catch ex As Exception
If Not clientSocket.Connected Then
Invoke(New _status(AddressOf status), clientSocket)
Connect()
End If
End Try
End Sub
Delegate Sub _SendTimeState()
Private Sub SendTimeState()
Try
mylist.Add("0") 'command number
mylist.Add(host) 'host name of this client
mylist.Add(lblState.Text)
mylist.Add(lblTime.Tag.ToString)
txt = String.Join("~", mylist)
Send(txt, clientSocket)
txt = ""
mylist.Clear()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Delegate Sub _readtext()
Private Sub readtext()
Try
reader = New StreamReader(AppPath & "\time.txt")
Dim x As Integer = reader.ReadLine
reader.Close()
If x <> 0 Then
lblTime.Tag = x
reader = New StreamReader(AppPath & "\state.txt")
Dim state As String = reader.ReadLine
reader.Close()
lblState.Text = state
Timer1.Start()
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Delegate Sub _writetext(ByVal file As String, ByVal txt As String)
Private Sub writetext(ByVal file As String, ByVal txt As String)
Try
If InvokeRequired Then
Invoke(New _writetext(AddressOf writetext), file, txt)
Exit Sub
End If
writer = New StreamWriter(AppPath & file, False)
writer.WriteLine(txt)
writer.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Delegate Sub _status(ByVal client As Socket)
Private Sub status(ByVal client As Socket)
lblConnection.Text = client.Connected.ToString
End Sub
'receive msg from server
Private Sub Recieve(ByVal ar As IAsyncResult)
Try
Dim ns As NetworkStream = CType(ar.AsyncState, NetworkStream)
ns.EndRead(ar)
ns.BeginRead(byteData, 0, byteData.Length, New AsyncCallback(AddressOf Recieve), ns)
Dim bytesRec As Byte() = byteData
Dim message As String = System.Text.ASCIIEncoding.ASCII.GetString(bytesRec)
Invoke(New _Read(AddressOf Read), message)
Catch ex As Exception
If Not clientSocket.Connected Then 'if connection was forcibly disconnected
'reconnecting to the server
Invoke(New _status(AddressOf status), clientSocket)
Connect()
End If
End Try
End Sub
Delegate Sub _Read(ByVal msg As String)
Private Sub Read(ByVal msg As String)
Try
mylist = msg.Split("~").ToList
'mylist(0) is command
'mylist(1) is time
'mylist(2) price
Select Case Integer.Parse(mylist(0))
Case 0 'timed
lblState.Text = "Timed"
lblTime.Tag = Integer.Parse(mylist(1))
lblTime.Text = GetTime(lblTime.Tag)
lblPrice.Text = Integer.Parse(lblPrice.Text) + Integer.Parse(mylist(2))
lblState.Tag = lblState.Text
writetext("\time.txt", lblTime.Tag.ToString)
writetext("\state.txt", "Timed")
Timer1.Start()
Case 1 'extend time
lblTime.Tag += Integer.Parse(mylist(1))
lblTime.Text = GetTime(lblTime.Tag)
lblPrice.Text = Integer.Parse(lblPrice.Text) + Integer.Parse(mylist(2))
If Not Timer1.Enabled Then Timer1.Start()
Case 2 'open time
lblState.Text = "Open"
lblTime.Tag = Integer.Parse(mylist(1))
lblTime.Text = GetTime(lblTime.Tag)
lblPrice.Text = mylist(2)
lblState.Tag = lblState.Text
writetext("\time.txt", lblTime.Tag.ToString)
writetext("\state.txt", "Open")
Timer1.Start()
Case 3 'pause time
lblState.Text = "Paused"
Timer1.Stop()
Case 4 'resume time
lblState.Text = lblState.Tag
Timer1.Start()
Case 5 'stop time
lblState.Text = "Stop"
writetext("\time.txt", "0")
writetext("\state.txt", "Stop")
Timer1.Stop()
Case 6 'shutdown
Case 7 'reset
Case 8 'send msg
End Select
mylist.Clear()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
'send msg to server
Private Sub Send(ByVal msg As String, ByVal client As Socket)
Try
Dim sendBytes As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(msg)
NetStream = New NetworkStream(client)
NetStream.BeginWrite(sendBytes, 0, sendBytes.Length, New AsyncCallback(AddressOf OnSend), NetStream)
Catch ex As Exception
If Not clientSocket.Connected Then 'if connection was forcibly disconnected
'reconnecting to the server
Invoke(New _status(AddressOf status), clientSocket)
Connect()
End If
End Try
End Sub
Private Sub OnSend(ByVal ar As IAsyncResult)
Try
Dim ns As NetworkStream = CType(ar.AsyncState, NetworkStream)
ns.EndWrite(ar)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
Try
Select Case lblState.Text
Case "Timed"
lblTime.Tag -= 1
lblTime.Text = GetTime(lblTime.Tag)
writetext("\time.txt", lblTime.Tag.ToString)
If lblTime.Tag = 0 Then Timer1.Stop()
Case "Open"
lblTime.Tag += 1
lblTime.Text = GetTime(lblTime.Tag)
writetext("\time.txt", lblTime.Tag.ToString)
End Select
Catch ex As Exception
If Not clientSocket.Connected Then 'if connection was forcibly disconnected
'reconnecting to the server
Invoke(New _status(AddressOf status), clientSocket)
Connect()
End If
MsgBox(ex.ToString)
End Try
End Sub
Private Function GetTime(ByVal time As Integer) As String
Dim Hrs As Integer 'number of hours '
Dim Min As Integer 'number of Minutes '
Dim Sec As Integer 'number of Sec '
'Seconds'
Sec = time Mod 60
'Minutes'
Min = ((time - Sec) / 60) Mod 60
'Hours'
Hrs = ((time - (Sec + (Min * 60))) / 3600) Mod 60
Return Format(Hrs, "00") & ":" & Format(Min, "00") & ":" & Format(Sec, "00")
End Function
End Class
OleDb Module:
Imports System.Data.OleDb
Module oledb
Dim AppPath As String = Application.StartupPath
Public conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + AppPath + "\ServerDatabase.mdb;User Id=Admin;Password=")
Public comm As OleDbCommand
Public reader As OleDbDataReader
Public query As String
Public count As Integer
End Module
(Can't add this post on my first post because it reached it's max capacity :P)
Here's the slightly changed Received function:
'receive msg from client
Private Sub Recieve(ByVal ar As IAsyncResult)
Try
Dim ns As NetworkStream = CType(ar.AsyncState, NetworkStream)
Dim message As String = ""
ByteSize = ns.EndRead(ar)
message = String.Concat(message, System.Text.ASCIIEncoding.ASCII.GetString(byteData, 0, ByteSize))
ns.BeginRead(byteData, 0, byteData.Length, New AsyncCallback(AddressOf Recieve), ns)
'if there are still data left in the network stream
While ns.DataAvailable
ns.BeginRead(byteData, 0, byteData.Length, New AsyncCallback(AddressOf Recieve), ns)
End While
Invoke(New _Read(AddressOf Read), message)
Catch ex As Exception
'check for Disconnection or Force Disconnection
Invoke(New _dc(AddressOf dc))
End Try
End Sub
I saw on the MS Documentation about NetworkStream.EndRead that the EndRead comes first before BeginRead. Maybe it is only applicable on Read.
NetworkStream.EndRead Method (IAsyncResult)
But the problem still persist :(
I started working with MailKit and have run into an issue where no body is returned for any of the fetched messages. I've tried both a fetch and a search, without luck.
My code is below:
Private strErrMsg As String
Private objClient As ImapClient
Private objDataTable As DataTable
Private Sub frmEmalTest2_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
If objClient IsNot Nothing Then
If objClient.IsConnected Then
objClient.Disconnect(True)
objClient.Dispose()
End If
End If
End Sub
Private Sub frmEmalTest2_Load(sender As Object, e As EventArgs) Handles Me.Load
objDataTable = New DataTable
With objDataTable.Columns
.Add("msgdate", Type.GetType("System.String"))
.Add("sender", Type.GetType("System.String"))
.Add("subject", Type.GetType("System.String"))
.Add("msgid", Type.GetType("System.String"))
.Add("attachments", Type.GetType("System.Int32"))
End With
grdMessages.DataSource = objDataTable
End Sub
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Try
If txtUserName.Text = "" Then
Exit Sub
End If
If txtPassword.Text = "" Then
Exit Sub
End If
Dim logger = New ProtocolLogger(Console.OpenStandardError())
objClient = New ImapClient(logger)
Dim credentials = New NetworkCredential(txtUserName.Text, txtPassword.Text)
Dim uri = New Uri("imaps://imap.gmail.com")
With objClient
.Connect(uri)
.AuthenticationMechanisms.Remove("XOAUTH2")
.Authenticate(credentials)
End With
lblMsg.Text = "Connected"
Catch ex As Exception
strErrMsg = ex.Message
lblMsg.Text = "Connection failed!"
End Try
End Sub
Private Sub btnMessages_Click(sender As Object, e As EventArgs) Handles btnMessages.Click
Dim objRow As DataRow
Dim objMultipart As BodyPartMultipart
Dim objBasic As BodyPartBasic
Dim objMessage As IMessageSummary
Dim intAttachments As Integer = 0
Dim objMessages As IList(Of IMessageSummary) = Nothing
Try
If Not objClient.IsConnected Then
Exit Sub
End If
objClient.Inbox.Open(FolderAccess.[ReadOnly])
objMessages = objClient.Inbox.Fetch(0, -1, MessageSummaryItems.All).ToList()
If objMessages.Count > 0 Then
lblRecCnt.Text = objMessages.Count.ToString + " message(s)"
Else
lblRecCnt.Text = "(no messages)"
End If
objDataTable.Rows.Clear()
If objMessages.Count > 0 Then
For Each objMessage In objMessages
intAttachments = 0
objBasic = TryCast(objMessage.Body, BodyPartBasic)
objMultipart = TryCast(objMessage.Body, BodyPartMultipart)
objRow = objDataTable.NewRow
objRow("msgid") = objMessage.UniqueId
objRow("msgdate") = objMessage.Date.ToString("M/d/yyyy h:mmtt")
objRow("subject") = objMessage.Envelope.Subject
objRow("sender") = objMessage.Envelope.From.Mailboxes(0).Name + " (" + objMessage.Envelope.From.Mailboxes(0).Address + ")"
If objMultipart Is Nothing Then
If objBasic IsNot Nothing AndAlso objBasic.IsAttachment Then
intAttachments += 1
End If
Else
For Each objItem As BodyPartBasic In objMultipart.BodyParts.OfType(Of BodyPartBasic)()
Select Case objItem.ContentType.MediaType
Case "APPLICATION", "IMAGE"
intAttachments += 1
End Select
Next objItem
End If
objRow("attachments") = intAttachments
objDataTable.Rows.Add(objRow)
If objRow("attachments") > 0 Then
grdMessages.Rows(objDataTable.Rows.Count - 1).Cells(0).Value = My.Resources.attach
End If
Next
End If
Catch ex As Exception
strErrMsg = ex.Message
End Try
End Sub
My fault!!
If I change MessageSummaryItems.All to MessageSummaryItems.Full I can see the body. However, it adds about 5 seconds to the fetch time.
I was wondering if anyone knew an easy way to have .pdf files trigger the readystate when loaded. I'm building a program to open url's and take screenshots, then put them in excel.
The web browser will load html documents correctly, but gets stuck in While Not pageready when loading .pdf files. The browser control correctly renders the .pdf.
Private Sub btngo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btngo.Click
Dim file As String
Dim Obj As New Object
Dim result As String
Dim sheet As String = "sheet1"
Dim xlApp As New Excel.Application
If lblpath.Text <> "" Then
file = lblpath.Text
Dim xlWorkBook = xlApp.Workbooks.Open(file)
Dim xlWorkSheet = xlWorkBook.Worksheets(sheet)
Dim range = xlWorkSheet.UsedRange
ProgressBar1.Value = 0
For rCnt = 4 To range.Rows.Count
'url cell
Obj = CType(range.Cells(rCnt, 2), Excel.Range)
' Obj.value now contains the value in the cell..
Try
' Creates an HttpWebRequest with the specified URL.
Dim myHttpWebRequest As HttpWebRequest = CType(WebRequest.Create(Obj.value), HttpWebRequest)
' Sends the request and waits for a response.
Dim myHttpWebResponse As HttpWebResponse = CType(myHttpWebRequest.GetResponse(), HttpWebResponse)
If myHttpWebResponse.StatusCode = HttpStatusCode.OK Then
result = myHttpWebResponse.StatusCode
WebBrowser1.ScrollBarsEnabled = False
WebBrowser1.Navigate(myHttpWebRequest.RequestUri)
WaitForPageLoad()
CaptureWebBrowser(WebBrowser1)
End If
' Release the resources of the response.
myHttpWebResponse.Close()
Catch ex As WebException
result = (ex.Message)
Catch ex As Exception
result = (ex.Message)
End Try
RichTextBox1.AppendText(result & " " & Obj.value & vbNewLine)
If radpre.Checked = True Then
range.Cells(rCnt, 3).value = result
ElseIf radcob.Checked = True Then
range.Cells(rCnt, 4).value = result
ElseIf radpost.Checked = True Then
range.Cells(rCnt, 5).value = result
End If
ProgressBar1.Value = rCnt / range.Rows.Count * 100
Next
With xlApp
.DisplayAlerts = False
xlWorkBook.SaveAs(lblpath.Text.ToString)
.DisplayAlerts = True
End With
xlWorkBook.Close()
xlApp.Quit()
'reclaim memory
Marshal.ReleaseComObject(xlApp)
xlApp = Nothing
End If
End Sub
Private Function CaptureWebBrowser(ByVal wb As WebBrowser) As Image
Try
Dim hBitmap As Bitmap = New Bitmap(wb.Width, wb.Height)
wb.DrawToBitmap(hBitmap, wb.Bounds)
Dim img As Image = hBitmap
Return img
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Return Nothing
End Function
Private Sub WaitForPageLoad()
AddHandler WebBrowser1.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
While Not pageready
Application.DoEvents()
End While
pageready = False
End Sub
Private Sub PageWaiter(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)
If WebBrowser1.ReadyState = WebBrowserReadyState.Complete Then
pageready = True
RemoveHandler WebBrowser1.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
End If
End Sub
update to resolved
I'm very happy with the feedback. I really like like the answer Noseratio provided. I was not aware using the code pattern as not in best practices. When opening a .pdf or any other document not web based readyState will never change from 0. Seeing how this program is simply a way for me not to work at work, I'm satisfied with only capturing .html and .htm.
My requirements were
open excel document
parse links located in excel document
determine response code
write response code and if possible screenshot to excel
The program parses and retrieves feedback far faster then I would be able to do manually. Screenshots of .html and .htm provide non-technical viewers of the excel file proof of successful migration from production to COB, and back to production environments.
This code as stated by Noseratio does not follow best practices, nor is it high quality. This is a quick and dirty implementation.
Option Infer On
Imports Microsoft.Office.Interop
Imports System.Net
Imports System.Runtime.InteropServices
Public Class Form1
Public Property pageready As Boolean
Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
OpenFileDialog1.ShowDialog()
End Sub
Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
lblpath.Text = OpenFileDialog1.FileName.ToString
End Sub
Private Sub btngo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btngo.Click
Dim file As String
Dim Obj As New Object
Dim result As String
Dim sheet As String = "sheet1"
Dim xlApp As New Excel.Application
Dim img As Bitmap
Dim path As String = "C:\Documents and Settings\user\My Documents\Visual Studio 2010\Projects\COB-HTML-Tool\COB-HTML-Tool\bin\Debug\tmp.bmp"
If lblpath.Text <> "" Then
file = lblpath.Text
Dim xlWorkBook = xlApp.Workbooks.Open(file)
Dim xlWorkSheet = xlWorkBook.Worksheets(sheet)
Dim range = xlWorkSheet.UsedRange
ProgressBar1.Value = 0
For rCnt = 4 To range.Rows.Count
'url cell
Obj = CType(range.Cells(rCnt, 2), Excel.Range)
' Obj.value now contains the value in the cell..
Try
' Creates an HttpWebRequest with the specified URL.
Dim myHttpWebRequest As HttpWebRequest = CType(WebRequest.Create(Obj.value), HttpWebRequest)
' Sends the request and waits for a response.
Dim myHttpWebResponse As HttpWebResponse = CType(myHttpWebRequest.GetResponse(), HttpWebResponse)
If myHttpWebResponse.StatusCode = HttpStatusCode.OK Then
result = myHttpWebResponse.StatusCode
Dim len As Integer = myHttpWebRequest.RequestUri.ToString.Length - 4
If myHttpWebRequest.RequestUri.ToString.Substring(len) = ".htm" Or
myHttpWebRequest.RequestUri.ToString.Substring(len - 1) = ".html" Or
myHttpWebRequest.RequestUri.ToString.Substring(len) = ".asp" Then
WebBrowser1.Navigate(myHttpWebRequest.RequestUri)
WaitForPageLoad()
img = CaptureWebBrowser(WebBrowser1)
img.Save(path)
End If
End If
' Release the resources of the response.
myHttpWebResponse.Close()
Catch ex As WebException
result = (ex.Message)
Catch ex As Exception
result = (ex.Message)
End Try
RichTextBox1.AppendText(result & " " & Obj.value & vbNewLine)
If radpre.Checked = True Then
range.Cells(rCnt, 3).value = result
If img Is Nothing Then
Else
If Dir(path) <> "" Then
range.Cells(rCnt, 4).Select()
Dim opicture As Object
opicture = xlApp.ActiveSheet.Pictures.Insert(path)
opicture.ShapeRange.LockAspectRatio = True
opicture.ShapeRange.width = 170
opicture.ShapeRange.height = 170
My.Computer.FileSystem.DeleteFile(path)
End If
End If
ElseIf radcob.Checked = True Then
range.Cells(rCnt, 5).value = result
If img Is Nothing Then
Else
If Dir(path) <> "" Then
range.Cells(rCnt, 6).Select()
Dim opicture As Object
opicture = xlApp.ActiveSheet.Pictures.Insert(path)
opicture.ShapeRange.LockAspectRatio = True
opicture.ShapeRange.width = 170
opicture.ShapeRange.height = 170
My.Computer.FileSystem.DeleteFile(path)
End If
End If
ElseIf radpost.Checked = True Then
range.Cells(rCnt, 7).value = result
If img Is Nothing Then
Else
If Dir(path) <> "" Then
range.Cells(rCnt, 8).Select()
Dim opicture As Object
opicture = xlApp.ActiveSheet.Pictures.Insert(path)
opicture.ShapeRange.LockAspectRatio = True
opicture.ShapeRange.width = 170
opicture.ShapeRange.height = 170
My.Computer.FileSystem.DeleteFile(path)
End If
End If
End If
ProgressBar1.Value = rCnt / range.Rows.Count * 100
Next
With xlApp
.DisplayAlerts = False
xlWorkBook.SaveAs(lblpath.Text.ToString)
.DisplayAlerts = True
End With
xlWorkBook.Close()
xlApp.Quit()
'reclaim memory
Marshal.ReleaseComObject(xlApp)
xlApp = Nothing
End If
End Sub
Private Function CaptureWebBrowser(ByVal wb As WebBrowser) As Image
Try
wb.ScrollBarsEnabled = False
Dim hBitmap As Bitmap = New Bitmap(wb.Width, wb.Height)
wb.DrawToBitmap(hBitmap, wb.Bounds)
Dim img As Image = hBitmap
Return img
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Return Nothing
End Function
Private Sub WaitForPageLoad()
AddHandler WebBrowser1.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
While Not pageready
Application.DoEvents()
System.Threading.Thread.Sleep(200)
End While
pageready = False
End Sub
Private Sub PageWaiter(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)
If WebBrowser1.ReadyState = WebBrowserReadyState.Complete Then
pageready = True
RemoveHandler WebBrowser1.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
End If
End Sub
End Class
Unfortunately, you won't be able to use webBrowser.DrawToBitmap to get a snapshot of the PDF view. At the time of writing this, Adobe Acrobat Reader ActiveX control doesn't support rendering on a custom device context, so this method won't work, as well as sending WM_PRINT or calling IViewObject::Draw, either directly on the Reader ActiveX object on via WebBrowser (I tried that, and I'm not alone). The proper solution would be to use a 3rd party PDF rendering component.
On a side note, you should avoid using code pattern like this:
While Not pageready
Application.DoEvents()
End While
It's a busy waiting tight loop, consuming CPU cycles in vain. At least, put some Thread.Sleep(200) inside the loop, but overall you should avoid using Application.DoEvents too.