Imports System.Text
Imports System.Net
Imports System.IO

Public Class HTTPUploader



    Public Shared Function UploadFile(ByVal url As String, ByVal credentials As Net.NetworkCredential, ByVal localPathFilename As String, ByVal nvc As System.Collections.Specialized.NameValueCollection, ByRef LogMessage As String) As Boolean
        Try
            'Return True
            Dim length As Long = 0
            'Dim boundary As String = "----------------------------" & Date.Now.Ticks.ToString("x")
            Dim boundary As String = "----------------------------061366199019971999"

            Dim httpWebRequest2 As HttpWebRequest = WebRequest.Create(url)
            httpWebRequest2.ContentType = "multipart/form-data; boundary=" & boundary
            httpWebRequest2.Method = "POST"
            httpWebRequest2.KeepAlive = True
            httpWebRequest2.Credentials = credentials
            httpWebRequest2.Timeout = 900000


            Dim memStream As New System.IO.MemoryStream()

            Dim boundarybytes() As Byte = System.Text.Encoding.ASCII.GetBytes(vbCrLf & "--" & boundary & vbCrLf)


            Dim formdataTemplate As String = vbCrLf & "--" + boundary & vbCrLf & "Content-Disposition: form-data; name=""{0}"";" & vbCrLf & vbCrLf & "{1}"

            For Each key As String In nvc.Keys
                Dim formitem As String = String.Format(formdataTemplate, key, nvc(key))
                Dim formitembytes() As Byte = System.Text.Encoding.UTF8.GetBytes(formitem)
                memStream.Write(formitembytes, 0, formitembytes.Length)
            Next


            memStream.Write(boundarybytes, 0, boundarybytes.Length)

            Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}"" " & _
                                            "Content-Type: application/octet-stream" & vbCrLf & vbCrLf

            'Content-Type: application/octet-stream


            'string header = string.Format(headerTemplate, "file" + i, files[i]);
            Dim header As String = String.Format(headerTemplate, "file1", localPathFilename)

            Dim headerbytes() As Byte = System.Text.Encoding.UTF8.GetBytes(header)

            memStream.Write(headerbytes, 0, headerbytes.Length)



            Dim byteArray As Byte() = File.ReadAllBytes(localPathFilename)
            memStream.Write(byteArray, 0, byteArray.Length)

            memStream.Write(boundarybytes, 0, boundarybytes.Length)



            httpWebRequest2.ContentLength = memStream.Length + 1

            Dim requestStream As Stream = httpWebRequest2.GetRequestStream()

            memStream.Position = 0
            Dim tempBuffer(memStream.Length) As Byte
            memStream.Read(tempBuffer, 0, tempBuffer.Length)
            memStream.Close()
            requestStream.Write(tempBuffer, 0, tempBuffer.Length)
            requestStream.Close()

            Dim webResponse2 As WebResponse = httpWebRequest2.GetResponse()

            Dim stream2 As Stream = webResponse2.GetResponseStream()
            Dim reader2 As New StreamReader(stream2)

            Dim xmlResponse As String = reader2.ReadToEnd

            webResponse2.Close()
            httpWebRequest2 = Nothing
            webResponse2 = Nothing


            Dim ds As New DataSet
            ds.ReadXml(New System.Xml.XmlTextReader(New StringReader(xmlResponse)))

            Dim responseMessage As String = ds.Tables("Result").Rows(0)("Message")
            If responseMessage = "SUCCESS" Then
                Dim uploadedFilesize As Long = ds.Tables("Result").Rows(0)("SavedFileSize")
                If My.Computer.FileSystem.GetFileInfo(localPathFilename).Length = uploadedFilesize Then
                    'we are done
                    Return True
                Else
                    LogMessage = "Uploaded filesize (" & uploadedFilesize & ") does not match local filesize (" & My.Computer.FileSystem.GetFileInfo(localPathFilename).Length & ")"
                End If
            Else
                LogMessage = "Dataforth Service Upload Error: " & ds.Tables("Result").Rows(0)("ErrorMessage")
            End If
            Return False
        Catch ex As Exception
            LogMessage = "Exception while uploading to Dataforth Service: " & ex.ToString
            Return False
        End Try
    End Function



    'Public Shared Sub _UploadVideo_(ByVal url As String, ByVal credentials As Net.NetworkCredential, ByVal localPathFilename As String, ByVal nvc As System.Collections.Specialized.NameValueCollection)
    '    Try
    '        Dim client As New WebClient
    '        client.Credentials = credentials
    '        Dim bogus As Integer = -1
    '        Dim requestURL As String = url & "?ecsId=" & nvc.Get("ecsId")
    '        'requestURL = requestURL.Replace("https://", "http://")

    '        Dim response() As Byte = client.UploadFile(requestURL, localPathFilename)
    '        MsgBox(System.Text.Encoding.Unicode.GetString(response))
    '    Catch webEx As WebException
    '        Dim thisE As String = webEx.ToString

    '    Catch ex As Exception

    '    End Try
    'End Sub


    'Public Shared Sub UploadVideo__(ByVal url As String, ByVal credentials As Net.NetworkCredential, ByVal localPathFilename As String, ByVal nvc As System.Collections.Specialized.NameValueCollection)

    '    Dim requestURL As String = url
    '    Dim boundary As String = "----------------------------" & Date.Now.Ticks.ToString("x")

    '    'Create Request
    '    Dim webRequest As System.Net.HttpWebRequest = CType(System.Net.WebRequest.Create(requestURL), System.Net.HttpWebRequest)
    '    webRequest.Credentials = credentials
    '    webRequest.Timeout = 120000
    '    'System.Net.ServicePointManager.ServerCertificateValidationCallback = (Function(sender, certificate, chain, sslPolicyErrors) True)
    '    'webRequest.ContentType = "application/x-www-form-urlencoded"
    '    webRequest.ContentType = "multipart/form-data; boundary=" & boundary
    '    webRequest.Method = "POST"


    '    Dim byteArray As Byte() = File.ReadAllBytes(localPathFilename)
    '    webRequest.ContentLength = byteArray.Length
    '    Dim dataStream As Stream = webRequest.GetRequestStream
    '    dataStream.Write(byteArray, 0, byteArray.Length)
    '    dataStream.Close()


    '    ' Retrieve data from Response
    '    Dim webResponse As System.Net.HttpWebResponse = CType(webRequest.GetResponse(), System.Net.HttpWebResponse)
    '    Dim sr As New System.IO.StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.UTF8)
    '    Dim responseString As String = sr.ReadToEnd()
    '    MsgBox(responseString)

    'End Sub

End Class
