Solved

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

Posted on 2011-03-01
1
410 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

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…
Introduction When many people think of the WebBrowser (http://msdn.microsoft.com/en-us/library/2te2y1x6%28v=VS.85%29.aspx) control, they immediately think of a control which allows the viewing and navigation of web pages. While this is true, it's a…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

734 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