Vb.net webapi file download troubles - vb.net

We've been using an IIS filehandler to download files that are stored in a database such as PowerPoint. Now we're trying to switch to webapi. File uploads are working fine but downloads are not.
Using the filehandler the url is like: http://localhost:57851/docmgr?id=6202 which returns a valid file with the following info from Fiddler:
Using the same code in a webapi controller having a url of: http://localhost:57851/webapi/file/GetFile?id=6202 returns a file with additional bytes added. Fiddler data:
Note the change in content-type as well even though the content-type is expressly set to "application/vnd.ms-powerpoint".
I must be missing something....
Here is the controller code:
<HttpGet>
Public Function GetFile()
Dim dbConn As New SqlConnection(DigsConnStr)
Dim dbCmd As New SqlCommand
Dim dbRdr As SqlDataReader
Dim id As String = HttpContext.Current.Request.QueryString("id")
Dim bytes As Byte()
Dim contentType As String
Dim fileName As String
Dim fileExt As String
Try
dbConn.Open()
dbCmd.Connection = dbConn
dbCmd.CommandText = "GET_FileForDownload"
dbCmd.CommandType = CommandType.StoredProcedure
dbCmd.Parameters.AddWithValue("#VirtualFileRecID", id)
dbRdr = dbCmd.ExecuteReader
dbRdr.Read()
contentType = dbRdr("ContentType")
bytes = dbRdr("FileBytes")
fileExt = dbRdr("FileExtension")
If contentType <> "" Then
fileName = dbRdr("Title") & fileExt
HttpContext.Current.Response.ContentType = contentType
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" & fileName)
HttpContext.Current.Response.BinaryWrite(bytes)
'HttpContext.Current.Response.Flush()
End If
dbConn.Close()
Catch ex As Exception
dbConn.Close()
Finally
If Not (dbConn Is Nothing) Then dbConn.Close()
End Try
End Function

WebAPI is going to wrap your response in XML (or whatever formatter you have in your webapiconfig class)
You really shouldn't access the response stream directly with WebAPI but you can return a HttpResponseMessage object with the file stream
Check this out
<HTTPGET>
Public Function GetFile(FileID as Integer) As HttpResponseMessage
Dim path = "C:\Temp\test.exe"
Dim result As New HttpResponseMessage(HttpStatusCode.OK)
Dim stream = New FileStream(path, FileMode.Open)
result.Content = New StreamContent(stream)
result.Content.Headers.ContentType = New MediaTypeHeaderValue("application/octet-stream")
Return result
End Function
Then you should really access it like this: http://localhost:57851/docmgr/6202

Related

Send file from one endpoint to another in VB.NET

I need to send a file that I receive in 'testFile1' to 'testFile2'. I don't know if the stream I am creating is the right way to do it or if I have to retrieve the file on 'testFile2' in another way. Any help?
<HttpPost>
<Route("testFile1")>
Function postTestFile1() As IHttpActionResult
Try
Dim files = HttpContext.Current.Request.Files
If files.Count = 0 Then Throw New Exception("No file")
Dim file = files(0)
Dim req As HttpWebRequest = WebRequest.Create("http://localhost:9000/api/test/testFile2")
req.Method = "POST"
req.ContentType = "multipart/form-data"
req.ContentLength = file.ContentLength
Dim stream = req.GetRequestStream
Dim fileData As Byte()
Using BinaryReader As New BinaryReader(file.InputStream, Encoding.UTF8)
fileData = BinaryReader.ReadBytes(file.ContentLength)
End Using
stream.Write(fileData, 0, fileData.Length)
Dim response As WebResponse = req.GetResponse
Catch ex As Exception
Return InternalServerError()
End Try
End Function
<HttpPost>
<Route("testFile2")>
Function postTestFile2() As IHttpActionResult
Try
Dim files = HttpContext.Current.Request.Files
Dim requestStream = HttpContext.Current.Request.InputStream
If files.Count = 0 Then Throw New Exception("No file")
Dim file = files(0)
'Do the necessary with the file
Return Ok()
Catch ex As Exception
Return InternalServerError()
End Try
End Function

how to get source code from link with user name and password in vb or c#

i try to get code source from my facebook account bet i get only the login page code source...
i assumes its happens because problem with cookie
my code...
'download data from url and return string of the source code
Public Shared Function getSourceCode(address As String) As String
Dim reader As StreamReader = Nothing
'Address of URL
Dim URL As String = address
' Get HTML data
Dim client As WebClient = New WebClient()
Try
client.Proxy = Nothing
Dim data As Stream = client.OpenRead(URL)
reader = New StreamReader(data)
Catch
'error
End Try
If reader IsNot Nothing Then Return reader.ReadToEnd
Return ""
End Function

vb.net OpenWeatherMap using HttpWebRequest

I am unable to get the HttpWebRequest to work properly with OpenWeatherMap.
When I try out the URL from the browser I get the data. However, when I am sending it from the program I'm getting a message with code id. Like this:
"message":"","cod":"404"
What Am I doing wrong?
VB.NET Code:
Private Shared AppID As String = "add_app_id_Here"
Public Shared Function GetWeather(ByVal location As String) As List(Of WeatherDetails)
Dim url = String.Format _
("http://api.openweathermap.org/data/2.5/forecast/daily?q={0}&type=accurate&mode=xml&units=metric&cnt=3&appid={1}",
location, AppID)
Try
Dim request As HttpWebRequest = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
request.AuthenticationLevel = Net.Security.AuthenticationLevel.None
Dim response As WebResponse = request.GetResponse()
'The body of the request is sent here
Dim responseReader As New StreamReader(response.GetResponseStream())
Dim responseInfo As String = responseReader.ReadToEnd()
responseReader.Close()
response.Close()
If Not (responseInfo.Contains("message") And responseInfo.Contains("cod")) Then
Dim xEl = XElement.Load(New System.IO.StringReader(responseInfo))
Return GetWeatherInfo(xEl)
Else
Return New List(Of WeatherDetails)
End If
Catch ex As Exception
Return New List(Of WeatherDetails)
End Try
End Function
After breaking my head I found that his method HttpWebRequest is not tolerant to special characters or non printable characters.
Thus in the URL I had to hardcode the "%27" character and it solved the problem.

Is there any way to optimize performance of reading stream?

I'm requesting remote SOAP web-service but all operation (from click search button to render interface with answer) took almost two minutes, it's too long. So I wonder if there any possible way to improve performance of the current code.
Operation that parse xml and read data to database working quite well, problem only about reading answer from stream.
Public Shared Function CallWebService(ByVal an As String, ByVal xmlcommand As String) As String
Dim _url = "http://testapi.interface-xml.com/appservices/ws/FrontendService"
Dim soapEnvelopeXml As XmlDocument = CreateSoapEnvelope(xmlcommand)
Dim webRequest As HttpWebRequest = CreateWebRequest(_url, an)
webRequest.Proxy = System.Net.WebRequest.DefaultWebProxy
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest)
Dim asyncResult As IAsyncResult = webRequest.BeginGetResponse(Nothing, Nothing)
asyncResult.AsyncWaitHandle.WaitOne()
Dim soapResult As String
Using webResponse As WebResponse = webRequest.EndGetResponse(asyncResult)
Using bs As New BufferedStream(webResponse.GetResponseStream())
Using rd As New StreamReader(bs)
soapResult = rd.ReadLine()
Return soapResult
End Using
End Using
End Using
End Function
Here is solution!
Public Shared Function CallWebService(ByVal an As String, ByVal xmlcommand As String) As String
Dim _url = "http://testapi.interface-xml.com/appservices/ws/FrontendService"
Dim soapEnvelopeXml As XmlDocument = CreateSoapEnvelope(xmlcommand)
Dim webRequest As HttpWebRequest = CreateWebRequest(_url, an)
webRequest.Proxy = System.Net.WebRequest.DefaultWebProxy
webRequest.Headers.Add("Accept-Encoding", "gzip, deflate")
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest)
Dim asyncResult As IAsyncResult = webRequest.BeginGetResponse(Nothing, Nothing)
asyncResult.AsyncWaitHandle.WaitOne()
Dim soapResult As String
Using webResponse As WebResponse = webRequest.EndGetResponse(asyncResult)
Using bs As New BufferedStream(webResponse.GetResponseStream())
Using gz As New GZipStream(bs, CompressionMode.Decompress)
Using rd As New StreamReader(gz)
soapResult = rd.ReadLine()
Return soapResult
End Using
End Using
End Using
End Using
End Function

Creating a file on my website using VB.net

I have searched but couldn't get any real solution to creating a file on my website by uploading the file from the local system using VB.net
This is my code so far
Dim rdr As New FileStream(ReSaveFile, FileMode.Open)
Dim req As HttpWebRequest = DirectCast(WebRequest.Create("http://www.timemedian.com/display.txt"), HttpWebRequest)
req.Method = "POST"
' you might use "POST"
req.ContentLength = rdr.Length
req.AllowWriteStreamBuffering = True
Dim reqStream As Stream = req.GetRequestStream()
Dim inData As Byte() = New Byte(rdr.Length - 1) {}
' Get data from upload file to inData
Dim bytesRead As Integer = rdr.Read(inData, 0, rdr.Length)
' put data into request stream
reqStream.Write(inData, 0, rdr.Length)
rdr.Close()
req.GetResponse()
' after uploading close stream
reqStream.Close()
but I cant possible see the error. Please help
I uploaded the file using ftp protocol like this
Try
Dim mReq1 As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://ftp.websitename.com//" & SetID & ".pvx"), System.Net.FtpWebRequest)
mReq1.Credentials = New System.Net.NetworkCredential("username", "password")
mReq1.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim MFile1() As Byte = System.IO.File.ReadAllBytes(ReSaveFile)
Dim mStream1 As System.IO.Stream = mReq1.GetRequestStream()
mStream1.Write(MFile1, 0, MFile1.Length)
mStream1.Close()
mStream1.Dispose()
Catch ex As Exception
MsgBox("Your file was not fully posted to the remote server. PVX Mail may not function properly")
Exit Sub
End Try