Rabu, 07 Desember 2011

5 posting vb net

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.

  1. We use the HttpUtility class from the System.Web namespace  
  2. Imports System.Web  
  3.   
  4. Dim request As HttpWebRequest  
  5. Dim response As HttpWebResponse = Nothing  
  6. Dim reader As StreamReader  
  7. Dim address As Uri  
  8. Dim appId As String  
  9. Dim context As String  
  10. Dim query As String  
  11. Dim data As StringBuilder  
  12. Dim byteData() As Byte  
  13. Dim postStream As Stream = Nothing  
  14.   
  15. address = New Uri("http://api.search.yahoo.com/ContentAnalysisService/V1/termExtraction")  
  16.   
  17. ' Create the web request  
  18. request = DirectCast(WebRequest.Create(address), HttpWebRequest)  
  19.   
  20. ' Set type to POST  
  21. request.Method = "POST"  
  22. request.ContentType = "application/x-www-form-urlencoded"  
  23.   
  24. ' Create the data we want to send  
  25. appId = "YahooDemo"  
  26. context = "Italian sculptors and painters of the renaissance" _  
  27.    & "favored the Virgin Mary for inspiration"  
  28. query = "madonna"  
  29.   
  30. data = New StringBuilder()  
  31. data.Append("appid=" + HttpUtility.UrlEncode(appId))  
  32. data.Append("&context=" + HttpUtility.UrlEncode(context))  
  33. data.Append("&query=" + HttpUtility.UrlEncode(query))  
  34.   
  35. ' Create a byte array of the data we want to send  
  36. byteData = UTF8Encoding.UTF8.GetBytes(data.ToString())  
  37.   
  38. ' Set the content length in the request headers  
  39. request.ContentLength = byteData.Length  
  40.   
  41. ' Write data  
  42. Try  
  43.     postStream = request.GetRequestStream()  
  44.     postStream.Write(byteData, 0, byteData.Length)  
  45. Finally  
  46.     If Not postStream Is Nothing Then postStream.Close()  
  47. End Try  
  48.   
  49. Try  
  50.     ' Get response  
  51.     response = DirectCast(request.GetResponse(), HttpWebResponse)  
  52.   
  53.     ' Get the response stream into a reader  
  54.     reader = New StreamReader(response.GetResponseStream())  
  55.   
  56.     ' Console application output  
  57.     Console.WriteLine(reader.ReadToEnd())  
  58. Finally  
  59.     If Not response Is Nothing Then response.Close()  
  60. 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 of NetworkCredentials to the request.

VB.NET HTTP Authentication

  1. Dim request As HttpWebRequest  
  2. Dim response As HttpWebResponse = Nothing  
  3. Dim reader As StreamReader  
  4.   
  5. Try  
  6.     ' Create the web request  
  7.     request = DirectCast(WebRequest.Create("https://api.del.icio.us/v1/posts/recent"), _  
  8.        HttpWebRequest)  
  9.   
  10.     ' Add authentication to request  
  11.     request.Credentials = New NetworkCredential("username""password")  
  12.   
  13.     ' Get response  
  14.     response = DirectCast(request.GetResponse(), HttpWebResponse)  
  15.   
  16.     ' Get the response stream into a reader  
  17.     reader = New StreamReader(response.GetResponseStream())  
  18.   
  19.     ' Console application output  
  20.     Console.WriteLine(reader.ReadToEnd())  
  21. Finally  
  22.     If Not response Is Nothing Then response.Close()  
  23. 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

  1. Public Shared Sub PrintSource(ByVal address As Uri)  
  2.   
  3.     Dim request As HttpWebRequest  
  4.     Dim response As HttpWebResponse = Nothing  
  5.     Dim reader As StreamReader  
  6.     Dim sbSource As StringBuilder  
  7.   
  8.     If address Is Nothing Then Throw New ArgumentNullException("address")  
  9.   
  10.     Try  
  11.         ' Create and initialize the web request  
  12.         request = DirectCast(WebRequest.Create(address), HttpWebRequest)  
  13.         request.UserAgent = ".NET Sample"  
  14.         request.KeepAlive = False  
  15.         request.Timeout = 15 * 1000  
  16.   
  17.         ' Get response  
  18.         response = DirectCast(request.GetResponse(), HttpWebResponse)  
  19.   
  20.         If request.HaveResponse = True AndAlso Not (response Is NothingThen  
  21.   
  22.             ' Get the response stream  
  23.             reader = New StreamReader(response.GetResponseStream())  
  24.   
  25.             ' Read it into a StringBuilder  
  26.             sbSource = New StringBuilder(reader.ReadToEnd())  
  27.   
  28.             ' Console application output  
  29.             Console.WriteLine(sbSource.ToString())  
  30.         End If  
  31.     Catch wex As WebException  
  32.         ' This exception will be raised if the server didn't return 200 - OK  
  33.         ' Try to retrieve more information about the network error  
  34.         If Not wex.Response Is Nothing Then  
  35.             Dim errorResponse As HttpWebResponse = Nothing  
  36.             Try  
  37.                 errorResponse = DirectCast(wex.Response, HttpWebResponse)  
  38.                 Console.WriteLine( _  
  39.                   "The server returned '{0}' with the status code {1} ({2:d}).", _  
  40.                   errorResponse.StatusDescription, errorResponse.StatusCode, _  
  41.                   errorResponse.StatusCode)  
  42.             Finally  
  43.                 If Not errorResponse Is Nothing Then errorResponse.Close()  
  44.             End Try  
  45.         End If  
  46.     Finally  
  47.         If Not response Is Nothing Then response.Close()  
  48.     End Try  
  49.  

Minggu, 04 Desember 2011

posting vb net

' Simple class that encapsulates the HTTP post sample.
Public Class HttpPostRequest
    ' Displays simple usage information.       
    Shared Sub usage()
        Console.WriteLine("Executable_file_name [-u URL] [-d data] [-s file] [-p proxy]")
        Console.WriteLine("Available options:")
        Console.WriteLine("     -u URL          URL to post data to")
        Console.WriteLine("     -d data         Data to post")
        Console.WriteLine("     -s file         File name to save response to")