asp.net VB.net file download handler not work properly - asp.net

I have big file (about 2GB) to distribute to our customer, My website is written by asp.net vb, this is my file download handler:
Public Class FileHandler
Implements IHttpHandler
Public Sub ProcessRequest(ByVal httpcontext As HttpContext) Implements IHttpHandler.ProcessRequest
If HttpContext.User.Identity.IsAuthenticated Then
Dim FileName As String = HttpContext.Request.QueryString("File")
HttpContext.Response.Buffer = False
HttpContext.Response.Clear()
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" & FileName)
HttpContext.Response.ContentType = "application/exe"
HttpContext.Response.TransmitFile("~/download/ExE/" & FileName)
HttpContext.Response.Flush()
HttpContext.Response.Close()
End If
End Sub
Public ReadOnly Property IsReusable As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
My problem is this handler sometimes could not work properly.
Most customer could download it by this handler, but some customer click the download link, it will endless waiting for server's response, after long time waiting, it shows the error page says the IE cannot display the webpage. some customer try to download the file from IE8, it will show the error page directly.
I am really appreciate any one can help with this issue. Thank you!

I use a button or just a plain link to the file itself, I've never had to use a handler to download files.
For example, on the aspx I have a button and in the code behind I send the user to the file using the response object:
Protected Sub Button_DownloadFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button_DownloadFile.Click
Response.AddHeader("Content-Disposition", "attachment; filename=TheFileName.ext")
Response.WriteFile("~/App_Data/TheFileName.ext")
END SUB

Related

Excel download not happening from server

I am trying to download an Excel file from the server on a button click, but it is not happening. It simply executes the code but the download is not happening.
Protected Sub btn_dwnldexcel_Click(sender As Object, e As EventArgs) Handles btn_dwnldexcel.Click
Dim fileToDownload = Server.MapPath("./Data/nd_format.xls")
''Response.ContentType = "application/octet-stream"
Response.ContentType = "application/vnd.ms-excel"
Dim cd = New ContentDisposition()
cd.Inline = False
cd.FileName = Path.GetFileName(fileToDownload)
Response.AppendHeader("Content-Disposition", cd.ToString())
Dim fileData As Byte() = System.IO.File.ReadAllBytes(fileToDownload)
Response.OutputStream.Write(fileData, 0, fileData.Length)
End Sub
Any idea would be appreciated.
Instead of trying to send the data from the same page, it is better to use a generic handler which does not have the overheads of processing an aspx page.
So, if you add a new item to the project and find "Generic handler (.ashx)" (or similar), and use code like this:
Imports System.Web
Imports System.Web.Services
Imports System.IO
Public Class DownloadExcelFile
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim actualFile = Server.MapPath("~/Data/nd_format.xls")
If File.Exists(actualFile) Then
context.Response.ContentType = "application/octet-stream"
context.Response.AddHeader("content-disposition", "attachment; filename=""" & Path.GetFileName(actualFile) & """")
context.Response.TransmitFile(actualFile)
Else
context.Response.Clear()
context.Response.TrySkipIisCustomErrors = True
context.Response.StatusCode = 404
context.Response.Write("<html><head><title>File not found</title><style>body {font-family: Arial,sans-serif;}</style></head><body><h1>File not found</h1><p>Error.</p></body></html>")
context.Response.End()
End If
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Then you can use a hyperlink instead of a Button:
Download Excel File
(You can style the hyperlink as a button with CSS if required.)

Simple HttpResponse in ASPX VB

We have an old Asp.net 2.0 web service where I need to put in a simple HTTP response. In the below code, the function "APIValidation()" returns an int, 200 or 404. All I need to do is have it send an HttpResponse so my node web app can read the statuscode (and then do what it needs to do).
I have no idea how to do this (I'm a noob with ASP), the tutorials I find are too elaborate, it seems this could be solved in a few lines of code, I just don't know which.
You can see it in action here:
200 : http://registration.imprintplus.com/imprinttest/GlobalSrvSN.aspx?sn=29820C0792024CDC8D590BF14AF42490
404: http://registration.imprintplus.com/imprinttest/GlobalSrvSN.aspx?sn=invalid
The other option is for Node to be able to extract the 200 or 404 out of what the ASP service gives me. Either or works for me.
Option Explicit Off
Option Strict Off
Imports ActivationServer
Partial Class GlobalSrvSN
Inherits System.Web.UI.Page
Public Function APIValidation(ByVal sn As String, ByVal databaseSource As String) As String
Dim act As New LogicProtect_ActivationServer(databaseSource)
Return act.APIValidation("user", "user#company.com", sn)
End Function
End Class
thanks a million!
Unsure how you're calling that function so will assume a few things if that's the only code you have.
If you're calling it from the .aspx file then this would be an example:
<%# Page Language="vb" ....." %>
<%
Dim foo = APIValidation(Request("sn"), "other string")
Response.StatusCode = CInt(foo)
%>
If from "code behind" ([page].aspx.vb):
Option Explicit Off
Option Strict Off
Imports ActivationServer
Partial Class GlobalSrvSN
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim foo = APIValidation(Request("sn"), "other string")
Response.StatusCode = CInt(foo)
End Sub
Public Function APIValidation(ByVal sn As String, ByVal databaseSource As String) As String
Dim act As New LogicProtect_ActivationServer(databaseSource)
Return act.APIValidation("user", "user#company.com", sn)
End Function
End Class
Notes: Above is a very trivial answer to keep things simple. But:
above is really a "Web Forms Page" (not technically a "web service") which would be asmx (2.0)
Skipped any input validation (queryString), error checking/handling.
Response object is how you'd control HTTP Responses (headers, etc.)
Hth

Lost HttpContext in a custom event

I'm getting the 'Response is not available in this context error' calling the following function:
Private Sub ReloadPage(ByVal inNumber As Integer) Handles tempaux.Advertise
'Response.Redirect("tope.aspx?dep=" & CStr(inNumber))
Response.Write("<script>window.open('tope.aspx?dep= & CStr(inNumber)','topFrame');</script>")
End Sub
I've changed the line adding the System.Web.HttpContext.Current before Response.Write and I get 'Object reference not set to an instance of an object'.
To give some background: tope.aspx is, as you can see, opened in topframe. As soon as it loads it starts a CustomTimer object I've defined:
Public Class tope
Inherits System.Web.UI.Page
Public funciones As funciones = New funciones
Dim WithEvents tempaux As CustomTimer = Global.objCustomTimer
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim inUserProfile As Int64
Try
tempaux.StartTimer()
Catch ex As Exception
'bla bla
End Try
As you can see I've declared the CustomTimer in the Global.asax. The CustomTimer object raises an Advertise event every 5 seconds and passes 'inNumber' as a parameter for the tope.aspx page to refresh some label, a simple thing. CustomTimer is a class I made to manage the timer, it doesn't inherits any other class( For what I've learned in my search it has to inherit some httpthing but I'm not sure). I'm guessing that at some point the httpcontext is being lost (I've searched in google and I couldn't figure its lifecycle or whatever information that tells me why it 'dies). Can anyone help me to find out what is the problem?
thanks
Your timer exists outside of the tope page class, so it is possible that the timer event is firing after the response from the page is complete and there is no longer a HttpContext.Current instance.
It sounds like what you are trying to do is to change an advertising banner on a page every 5 seconds, once the page is loaded. You need to do that using a javascript timer, which would fire every 5 seconds and make a request back to your web server for a new advertisement.

Why am I getting an weird error on my asp.net webpage?

I am currently developing a asp.net webpage and a WCF publish subscribe service. The WCF service has been done up the subscriber is a winform app which is also done up. I am now trying to get the asp.net webpage to connect to my publish service for my WCF. However there is an weird error that I am getting. I have added the app.config and the generatedProxy.cs.vb to my asp.net project.
This is the code for my class
Public Class json
Implements IPostingContractCallback
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Response.ContentType = "application/json"
If Request.QueryString("action") = "postAlert" Then
Dim site As InstanceContext = New InstanceContext(New json())
Dim client As PostingContractClient = New PostingContractClient(site)
client.PublishPost("testing")
client.Close()
End If
End Sub
Public Sub PostReceived(ByVal postSampleData As String)
Console.WriteLine("PostChange(item {0})", postSampleData)
End Sub
the sub PostReceived is the callback method for my WCF service. It practically is meant to be do nothing as this is the Publisher, but I still have to implement it due to the WCF standards. The error that I am getting is
Class 'json' must implement 'Sub PostReceived(postSampleData As String)' for interface 'IPostingContractCallback'
How come i am getting the error when i have already implemented the sub as stated above?
Method signature must be: (Take a look at VB.NET Interfaces)
Public Sub PostReceived(ByVal postSampleData As String) Implements IPostingContractCallback.PostReceived
Console.WriteLine("PostChange(item {0})", postSampleData)
End Sub

How to print in VB?

I have a web application build using classic ASP and VB. How do I print a document from within the back end VB code?
Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click
End Sub
What i am trying to do is get user to click on button a letter is generated and sent to printer?
You could use the window.print javascript function which will open the print dialogon the client browser allowing him to choose the printer and print the page:
Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click
ClientScript.RegisterStartupScript([GetType](), "print", "window.print();", true)
End Sub
As a side note, what you have is not a classic ASP application with VB, you have a classic ASP.NET WebForms application using VB.NET as a code behind.
UPDATE:
As requested in the comments section here's how you could write a generic handler which will dynamically generate the HTML you would like to print:
Imports System.Web
Imports System.Web.Services
Public Class Print
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/html"
context.Response.Write("<html><body onload=""window.print();""><table><tr><td>value1</td><td>value1</td></tr></table></body></html>")
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Now simply navigate to /Print.ashx.
you could look into some reports frameworks like CrystalReports (used to come with VS but you have to download it from SAP nowadays.
Here is a nice tutorial for the report-engine that comes packed into Visual Studio (I have to admit I don't have much experience with this but it looks fine to me): Creating an ASP.NET Report

Resources