Solved

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

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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Article by: jpaulino
XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String (http://msdn.microsoft.com/en-us/library/system.string.aspx) Literal, only instead of starting and ending with w…
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…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

746 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

13 Experts available now in Live!

Get 1:1 Help Now