Solved

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

Posted on 2011-03-01
1
405 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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
Microsoft Reports are based on a report definition, which is an XML file that describes data and layout for the report, with a different extension. You can create a client-side report definition language (*.rdlc) file with Visual Studio, and build g…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

820 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