Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
lblProgress.Text = String.Empty
txtURL.Text = URL_MESSAGE
txtDownloadTo.Text = DIR_MESSAGE
cmdGetFolder.Focus()
txtURL.Hide()
Show()
Timer2.Start()
cmdDownload.Enabled = False
cmdDownload.Enabled = False
cmdClose.Enabled = False
'DO THE DOWNLOAD
Try
_Downloader = New WebFileDownloader
_Downloader.DownloadFileWithProgress(txtURL.Text, ("") & filename)
Catch ex As Exception
MessageBox.Show("ERROR: " & ex.Message)
cmdClose.Enabled = True
cmdDownload.Enabled = True
End Try
End Sub
'returns all text from last "/" in URL, but puts a "\" in front of the file name..
Private Function GetFileNameFromURL(ByVal URL As String) As String
If URL.IndexOf("/"c) = -1 Then Return String.Empty
Return "\" & URL.Substring(URL.LastIndexOf("/"c) + 1)
End Function
'GET A FOLDER TO DOWNLOAD THE FILE TO
Private Sub cmdGetFolder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdGetFolder.Click
If dlgFolderBrowse.ShowDialog(Me) <> DialogResult.Cancel Then
txtDownloadTo.Text = dlgFolderBrowse.SelectedPath
End If
End Sub
'FIRES WHEN WE HAVE GOTTEN THE DOWNLOAD SIZE, SO WE KNOW WHAT BOUNDS TO GIVE THE PROGRESS BAR
Private Sub _Downloader_FileDownloadSizeObtained(ByVal iFileSize As Long) Handles _Downloader.FileDownloadSizeObtained
ProgBar.Value = 0
ProgBar.Maximum = Convert.ToInt32(iFileSize)
End Sub
'FIRES WHEN DOWNLOAD IS COMPLETE
Private Sub _Downloader_FileDownloadComplete() Handles _Downloader.FileDownloadComplete
ProgBar.Value = ProgBar.Maximum
My.Settings.Save()
'download.Show()
yourlogo.Close()
Process.Start(filename)
cmdClose.Text = "Close"
cmdClose.Enabled = True
ProgBar.Value = ProgBar.Minimum
lblProgress.Text = String.Empty
End Sub
'FIRES WHEN DOWNLOAD FAILES. PASSES IN EXCEPTION INFO
Private Sub _Downloader_FileDownloadFailed(ByVal ex As System.Exception) Handles _Downloader.FileDownloadFailed
MessageBox.Show("Error: " & ex.Message)
cmdClose.Enabled = True
cmdDownload.Enabled = True
End Sub
'FIRES WHEN MORE OF THE FILE HAS BEEN DOWNLOADED
Private Sub _Downloader_AmountDownloadedChanged(ByVal iNewProgress As Long) Handles _Downloader.AmountDownloadedChanged
ProgBar.Value = Convert.ToInt32(iNewProgress)
lblProgress.Text = WebFileDownloader.FormatFileSize(iNewProgress) & " of " & WebFileDownloader.FormatFileSize(ProgBar.Maximum) & " Downloaded."
Application.DoEvents()
End Sub
Here is second set of code. I'd like to convert it to c# too .
This set of code will detects if the file version is the same , if it does not match , it will goto patcher form or else it will continue the application.
Private Sub CheckUpdata(ByVal url As String)
WebClient1.DownloadFileAsync(New Uri(url), "updateinfo.ver")
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
yourlogo.Show()
CheckUpdata("http://127.0.0.1/updateinfo.txt")
End Sub
Private Sub WebClient1_DownloadFileCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs) Handles WebClient1.DownloadFileCompleted
ProgressBar1.Value = ProgressBar1.Maximum
Dim version As New TextBox
version.Text = My.Computer.FileSystem.ReadAllText("updateinfo.ver")
Label2.Text = version.Text
Dim new_ver As Double = version.Text
Dim cur_ver As Double = Application.ProductVersion
If new_ver > cur_ver Then
On Error Resume Next
If My.Computer.FileSystem.FileExists("updateinfo.ver") Then
My.Computer.FileSystem.DeleteFile("updateinfo.ver")
End If
MsgBox("New version detected!", MsgBoxStyle.Information, "Updater")
frmDLMain.Show()
Me.Close()
Else
If My.Computer.FileSystem.FileExists("updateinfo.ver") Then
My.Computer.FileSystem.DeleteFile("updateinfo.ver")
End If
yourlogo.Close()
yourapp.Show()
Me.Close()
End If
End Sub
The last set of codes.
This code bascially detects if a file is existed in the same directory and if it does not , it will download from a webpage.
- We use the HttpUtility class from the System.Web namespace
- Imports System.Web
- Dim request As HttpWebRequest
- Dim response As HttpWebResponse = Nothing
- Dim reader As StreamReader
- Dim address As Uri
- Dim appId As String
- Dim context As String
- Dim query As String
- Dim data As StringBuilder
- Dim byteData() As Byte
- Dim postStream As Stream = Nothing
- address = New Uri("http://api.search.yahoo.com/ContentAnalysisService/V1/termExtraction")
- ' Create the web request
- request = DirectCast(WebRequest.Create(address), HttpWebRequest)
- ' Set type to POST
- request.Method = "POST"
- request.ContentType = "application/x-www-form-urlencoded"
- ' Create the data we want to send
- appId = "YahooDemo"
- context = "Italian sculptors and painters of the renaissance" _
- & "favored the Virgin Mary for inspiration"
- query = "madonna"
- data = New StringBuilder()
- data.Append("appid=" + HttpUtility.UrlEncode(appId))
- data.Append("&context=" + HttpUtility.UrlEncode(context))
- data.Append("&query=" + HttpUtility.UrlEncode(query))
- ' Create a byte array of the data we want to send
- byteData = UTF8Encoding.UTF8.GetBytes(data.ToString())
- ' Set the content length in the request headers
- request.ContentLength = byteData.Length
- ' Write data
- Try
- postStream = request.GetRequestStream()
- postStream.Write(byteData, 0, byteData.Length)
- Finally
- If Not postStream Is Nothing Then postStream.Close()
- End Try
- Try
- ' Get response
- response = DirectCast(request.GetResponse(), HttpWebResponse)
- ' Get the response stream into a reader
- reader = New StreamReader(response.GetResponseStream())
- ' Console application output
- Console.WriteLine(reader.ReadToEnd())
- Finally
- If Not response Is Nothing Then response.Close()
- End Try
HTTP Authenticated requests
The del.icio.us API requires you to make authenticated requests, passing your del.icio.us username and password using HTTP authentication. This is easily accomplished by adding an instance ofNetworkCredentials
to the request.
VB.NET HTTP Authentication
- Dim request As HttpWebRequest
- Dim response As HttpWebResponse = Nothing
- Dim reader As StreamReader
- Try
- ' Create the web request
- request = DirectCast(WebRequest.Create("https://api.del.icio.us/v1/posts/recent"), _
- HttpWebRequest)
- ' Add authentication to request
- request.Credentials = New NetworkCredential("username", "password")
- ' Get response
- response = DirectCast(request.GetResponse(), HttpWebResponse)
- ' Get the response stream into a reader
- reader = New StreamReader(response.GetResponseStream())
- ' Console application output
- Console.WriteLine(reader.ReadToEnd())
- Finally
- If Not response Is Nothing Then response.Close()
- End Try
Error Handling
Yahoo! offers many REST based web services but they don't all use the same error handling. Some web services return status code 200 (OK) and a detailed error message in the returned XML data while others return a standard HTTP status code to indicate an error. Please read the documentation for the web services you are using to see what type of error response you should expect. Remember that HTTP Authentication is different from the Yahoo! Browser-Based Authentication.Calling
HttpRequest.GetResponse()
will raise an exception if the server does not
return the status code 200 (OK), the request times out or there is a network error.
Redirects are, however, handled automatically.
Here is a more full featured sample method that prints the contents of a web page and has basic error handling for HTTP error codes.
VB.NET GET Sample 2
- Public Shared Sub PrintSource(ByVal address As Uri)
- Dim request As HttpWebRequest
- Dim response As HttpWebResponse = Nothing
- Dim reader As StreamReader
- Dim sbSource As StringBuilder
- If address Is Nothing Then Throw New ArgumentNullException("address")
- Try
- ' Create and initialize the web request
- request = DirectCast(WebRequest.Create(address), HttpWebRequest)
- request.UserAgent = ".NET Sample"
- request.KeepAlive = False
- request.Timeout = 15 * 1000
- ' Get response
- response = DirectCast(request.GetResponse(), HttpWebResponse)
- If request.HaveResponse = True AndAlso Not (response Is Nothing) Then
- ' Get the response stream
- reader = New StreamReader(response.GetResponseStream())
- ' Read it into a StringBuilder
- sbSource = New StringBuilder(reader.ReadToEnd())
- ' Console application output
- Console.WriteLine(sbSource.ToString())
- End If
- Catch wex As WebException
- ' This exception will be raised if the server didn't return 200 - OK
- ' Try to retrieve more information about the network error
- If Not wex.Response Is Nothing Then
- Dim errorResponse As HttpWebResponse = Nothing
- Try
- errorResponse = DirectCast(wex.Response, HttpWebResponse)
- Console.WriteLine( _
- "The server returned '{0}' with the status code {1} ({2:d}).", _
- errorResponse.StatusDescription, errorResponse.StatusCode, _
- errorResponse.StatusCode)
- Finally
- If Not errorResponse Is Nothing Then errorResponse.Close()
- End Try
- End If
- Finally
- If Not response Is Nothing Then response.Close()
- End Try