Solved

Visual Basic .net - Percentage Complete on Posting data via HTTPWebRequest

Posted on 2011-03-01
1
392 Views
Last Modified: 2012-05-11
How can I do progress bar while the following code is posting my data?  

Also what is the proper way to show a gif image while the below process is running?  If I just do a picturebox and set to visible, that event never happens as I guess the below code takes precedence?

The below process can take 5-20 seconds, depending on attachment size.

Dim myReq1 As HttpWebRequest = DirectCast(WebRequest.Create(Urlstr), HttpWebRequest)
            myReq1.Method = "POST"
            myReq1.ContentType = "application/json; charset=utf-8"
            Dim mylogin As String
            Dim bytes1 As Byte()
            bytes1 = Encoding.UTF8.GetBytes(myAttachment)

            mylogin = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(myloginDetails))
            myReq1.Headers.Add(HttpRequestHeader.Authorization, mylogin)
            objRequestStream = myReq1.GetRequestStream()
            objRequestStream.Write(bytes1, 0, bytes1.Length)
            objRequestStream.Close()

            Dim myRep1 As HttpWebResponse = DirectCast(myReq1.GetResponse(), HttpWebResponse)
            Dim respStreamReader1 As New System.IO.StreamReader(myRep1.GetResponseStream())
            Dim responseString1 As String = respStreamReader1.ReadToEnd()

            respStreamReader1.Close()
            myRep1.Close()

Open in new window

0
Comment
Question by:keith1001
1 Comment
 
LVL 12

Accepted Solution

by:
Hairbrush earned 500 total points
ID: 35016450
Hi Keith

The following code is adapted from some code that I use that uploads a file to a form and has a progress bar.  I have tried to merge my code with yours to do what you are trying to achieve, but what you will need to do is use something like Fiddler2 to inspect a working request and generate the headers that are correct for your site.

As regards showing a GIF, you could try this one: http://mattberseth.com/blog/2008/05/aspnet_ajax_progress_bar_contr.html or Google for "AJAX progress bar"

Hope this helps get you started...
Event UploadPercentCompelete(PercentComplete As Integer) 'handle this event to drive your progress bar

    Private Sub UploadUsingHTTP(ByVal FileName As String, ByVal Urlstr As String, ByVal Credentials As NetworkCredential)

        Try


            Dim strFileFormName As String = "file"
            Dim strBoundary As String = "----------" & DateTime.Now.Ticks.ToString("x")

            ' The trailing boundary string
            Dim boundaryBytes As Byte() = Encoding.ASCII.GetBytes(Constants.vbCrLf & "--" & strBoundary & Constants.vbCrLf)

            ' The post message header
            Dim sb As StringBuilder = New StringBuilder()
            sb.Append("--")
            sb.Append(strBoundary)
            sb.Append(Constants.vbCrLf)
            sb.Append("Content-Disposition: form-data; name=""")
            sb.Append(strFileFormName)
            sb.Append("""; filename=""")
            sb.Append(System.IO.Path.GetFileName(FileName))
            sb.Append("""")
            sb.Append(Constants.vbCrLf)
            sb.Append("Content-Type: ")
            sb.Append("application/json; charset=utf-8")
            sb.Append(Constants.vbCrLf)
            sb.Append(Constants.vbCrLf)

            Dim strPostHeader As String = sb.ToString()

            Dim postHeaderBytes As Byte() = Encoding.UTF8.GetBytes(strPostHeader)

            ' The WebRequest
            Dim oWebrequest As HttpWebRequest = CType(WebRequest.Create(Urlstr), HttpWebRequest)
            Dim oWResponse As WebResponse
            Dim objRequestStream As Stream
            With oWebrequest
                .Credentials = Credentials
                .ContentType = "application/json; boundary=" & strBoundary
                .Method = "POST"
                .Timeout = System.Threading.Timeout.Infinite
                .AllowWriteStreamBuffering = False ' This is important, otherwise the whole file will be read to memory anyway...

                ' Get a FileStream and set the final properties of the WebRequest
                Using oFileStream As New FileStream(FileName, FileMode.Open, FileAccess.Read)

                    oWebrequest.ContentLength = postHeaderBytes.Length + oFileStream.Length + boundaryBytes.Length
                    objRequestStream = oWebrequest.GetRequestStream()

                    objRequestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length) ' Write the post header

                    Const ChunckSize As Integer = 4096
                    ' Stream the file contents in small pieces (4096 bytes, max).
                    Dim buffer As Byte() = New [Byte](CInt(Math.Min(ChunckSize, oFileStream.Length))) {}
                    Dim bytesRead As Integer = oFileStream.Read(buffer, 0, buffer.Length)
                    Dim FileSize As Long = oFileStream.Length
                    Dim TotalBytesRead As Long
                    Dim PercentComplete As Integer = CInt((bytesRead / FileSize) * 100)
                    Dim LastPercentComplete As Integer
                    Do While bytesRead <> 0
                        LastPercentComplete = PercentComplete
                        objRequestStream.Write(buffer, 0, bytesRead)
                        bytesRead = oFileStream.Read(buffer, 0, buffer.Length)
                        TotalBytesRead += bytesRead
                        PercentComplete = CInt((TotalBytesRead / FileSize) * 100)
                        If PercentComplete > LastPercentComplete Then RaiseEvent UploadPercentCompelete(PercentComplete)
                    Loop

                    oFileStream.Close()
                End Using

                objRequestStream.Write(boundaryBytes, 0, boundaryBytes.Length) ' Add the trailing boundary

                oWResponse = .GetResponse()
            End With

            Dim s As Stream = Nothing
            Dim respStreamReader1 As StreamReader = Nothing
            Try
                s = oWResponse.GetResponseStream()
                respStreamReader1 = New StreamReader(s)
                Dim responseString1 As String = respStreamReader1.ReadToEnd()

                If responseString1.Length > 0 Then
                    'parse strResponse and handle success or error occordingly
                End If
            Finally
                s.Close()
                respStreamReader1.Close()
                objRequestStream.Close()
            End Try

        Catch ex As Exception
            Throw
        End Try

    End Sub

Open in new window

0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial demonstrates one way to create an application that runs without any Forms but still has a GUI presence via an Icon in the System Tray. The magic lies in Inheriting from the ApplicationContext Class and passing that to Application.Ru…
Article by: Kraeven
Introduction Remote Share is a simple remote sharing tool, enabling you to see, add and remove remote or local shares. The application is written in VB.NET targeting the .NET framework 2.0. The source code and the compiled programs have been in…
Internet Business Fax to Email Made Easy - With  eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, f…
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now