Solved

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

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

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

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

A while ago, I was working on a Windows Forms application and I needed a special label control with reflection (glass) effect to show some titles in a stylish way. I've always enjoyed working with graphics, but it's never too clever to re-invent …
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…
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

717 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