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.
Related
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!
So I have 4 check boxes and if one of them is checked, I would like to put that text into a label.
My problem is when one box is checked, it just has that text in the label but not the other checked ones. I want it to have a new line for each box that is checked to put new line text into the label.
How would I be able to have the program go through the check boxes, and if they are checked put that text into a label and for the next box checked start a new line and put that text there?
To be put under a button click event.
Quick and dirty, but if I understand what you are asking for this should work.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Label1.Text = ""
If (CheckBox1.Checked) Then
Label1.Text &= CheckBox1.Text & vbCrLf
End If
If (CheckBox2.Checked) Then
Label1.Text &= CheckBox2.Text & vbCrLf
End If
If (CheckBox3.Checked) Then
Label1.Text &= CheckBox3.Text & vbCrLf
End If
If (CheckBox4.Checked) Then
Label1.Text &= CheckBox4.Text & vbCrLf
End If
End Sub
Put all your CheckBoxes in the same container. In this example, they are all contained within Panel1. This gets all the Text properties of the CheckBoxes which are checked, and puts the Text in Label1.Text. When nothing is selected, an Exception is thrown (Sequence contains no elements).
Try
Label1.Text = Panel1.Controls.OfType(Of CheckBox). _
Where(Function(arg) arg.Checked). _
Select(Function(arg) arg.Text). _
Aggregate(Function(aggregate, nextItem) aggregate & Environment.NewLine & nextItem)
Catch ex As Exception
Label1.Text = "Nothing selected"
End Try
Try this code,
[Note: Tested with IDE]
Private Sub Common_Cheked_Change_Handler(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles _
CheckBox1.CheckedChanged, CheckBox2.CheckedChanged, _
CheckBox3.CheckedChanged, CheckBox4.CheckedChanged
Label1.Text = String.Empty
Label1.Text = If(CheckBox1.Checked = True, CheckBox1.Text & vbCrLf, String.Empty) & _
If(CheckBox2.Checked = True, CheckBox2.Text & vbCrLf, String.Empty) & _
If(CheckBox3.Checked = True, CheckBox3.Text & vbCrLf, String.Empty) & _
If(CheckBox4.Checked = True, CheckBox4.Text, String.Empty)
End Sub
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
Using the following code:
Private Sub Button12_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsubmit.Click
'see if it already exists
If DirectoryEntry.Exists("LDAP://CN=" & AdEntry.Text & ",OU=" & Machinetype.Text & ",OU=Computers,OU=" & USlocation.Text & ",OU=North America,DC=company,DC=com") = True Then
MsgBox("Object already exists")
Else
Try
'Set the directory entry
Dim de As New DirectoryEntry("LDAP://OU=" & Machinetype.Text & ",OU=Computers,OU=" & USlocation.Text & ",OU=North America,DC=company,DC=com")
Dim newComputer As DirectoryEntry = de.Children.Add("CN=TESTER", "computer")
newComputer.CommitChanges()
MsgBox("Computer added!")
Catch ex As Exception
MsgBox("Error adding computer")
End Try
End If
End Sub
End Class
According to http://msdn.microsoft.com/en-us/library/ms180851(v=VS.80).aspx this should work, but it returns an exception. Is there something I'm missing?
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