Return ZipFile in ASHX - asp.net

I have an ASHX file that receives some parameters (user and password). Using this parameters i need to send a zipfile as ASHX's result. I've written this code but when i open the downloaded zip, it appears to be corrupted.
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.Clear()
context.Response.ContentType = "application/x-zip-compressed"
Dim sLoginName As String = context.Request.QueryString("LOGIN_NAME")
Dim sLoginPassword As String = context.Request.QueryString("LOGIN_PASSWORD")
If (Not String.IsNullOrEmpty(sLoginName) And
Not String.IsNullOrEmpty(sLoginPassword)) Then
If (CheckLogin(sLoginName, sLoginPassword)) Then
Dim sZipUpdatePath As String = String.Empty
Dim sVersionToInstall As String = GetVersionToInstall(sLoginName, sLoginPassword)
Dim sZipName As String = "UPDATE.zip"
If (Not String.IsNullOrEmpty(sVersionToInstall) And
Not String.IsNullOrEmpty(sZipName)) Then
sZipUpdatePath = "~\Updates\" + sVersionToInstall + "\" + sZipName
context.Response.TransmitFile(context.Server.MapPath(sZipName))
End If
End If
End If
End Sub
How can solve it?

Related

QueryStringModule with FriendlyUrls does not working

Good morning, I need to encrypt my querystring and i found an interesting method in this link and I convert it in vb.net:
Imports System
Imports System.IO
Imports System.Web
Imports System.Text
Imports System.Security.Cryptography
Public Class QueryStringModule
Implements IHttpModule
Public Sub Dispose() Implements IHttpModule.Dispose
End Sub
Public Sub Init(ByVal context As HttpApplication) Implements IHttpModule.Init
AddHandler context.BeginRequest, New EventHandler(AddressOf context_BeginRequest)
End Sub
Private Const PARAMETER_NAME As String = "enc="
Private Const ENCRYPTION_KEY As String = "key"
Private Sub context_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim context As HttpContext = HttpContext.Current
If context.Request.Url.OriginalString.Contains("aspx") AndAlso context.Request.RawUrl.Contains("?") Then
Dim query As String = ExtractQuery(context.Request.RawUrl)
Dim path As String = GetVirtualPath()
If query.StartsWith(PARAMETER_NAME, StringComparison.OrdinalIgnoreCase) Then
Dim rawQuery As String = query.Replace(PARAMETER_NAME, String.Empty)
Dim decryptedQuery As String = Decrypt(rawQuery)
context.RewritePath(path, String.Empty, decryptedQuery)
ElseIf context.Request.HttpMethod = "GET" Then
Dim encryptedQuery As String = Encrypt(query)
context.Response.Redirect(path & encryptedQuery)
End If
End If
End Sub
Private Shared Function GetVirtualPath() As String
Dim path As String = HttpContext.Current.Request.RawUrl
path = path.Substring(0, path.IndexOf("?"))
path = path.Substring(path.LastIndexOf("/") + 1)
Return path
End Function
Private Shared Function ExtractQuery(ByVal url As String) As String
Dim index As Integer = url.IndexOf("?") + 1
Return url.Substring(index)
End Function
Private ReadOnly Shared SALT As Byte() = Encoding.ASCII.GetBytes(ENCRYPTION_KEY.Length.ToString())
Public Shared Function Encrypt(ByVal inputText As String) As String
Dim rijndaelCipher As RijndaelManaged = New RijndaelManaged()
Dim plainText As Byte() = Encoding.Unicode.GetBytes(inputText)
Dim SecretKey As PasswordDeriveBytes = New PasswordDeriveBytes(ENCRYPTION_KEY, SALT)
Using encryptor As ICryptoTransform = rijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16))
Using memoryStream As MemoryStream = New MemoryStream()
Using cryptoStream As CryptoStream = New CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)
cryptoStream.Write(plainText, 0, plainText.Length)
cryptoStream.FlushFinalBlock()
Return "?" & PARAMETER_NAME & Convert.ToBase64String(memoryStream.ToArray())
End Using
End Using
End Using
End Function
Public Shared Function Decrypt(ByVal inputText As String) As String
Dim rijndaelCipher As RijndaelManaged = New RijndaelManaged()
Dim encryptedData As Byte() = Convert.FromBase64String(inputText)
Dim secretKey As PasswordDeriveBytes = New PasswordDeriveBytes(ENCRYPTION_KEY, SALT)
Using decryptor As ICryptoTransform = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16))
Using memoryStream As MemoryStream = New MemoryStream(encryptedData)
Using cryptoStream As CryptoStream = New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)
Dim plainText As Byte() = New Byte(encryptedData.Length - 1) {}
Dim decryptedCount As Integer = cryptoStream.Read(plainText, 0, plainText.Length)
Return Encoding.Unicode.GetString(plainText, 0, decryptedCount)
End Using
End Using
End Using
End Function
End Class
but also my project use FriendlyUrls and I figured out that with FriendlyUrls the things does not working and always return the url without the extension ".aspx" but with the querystring not encrypted
Imports System.Web.Routing
Imports Microsoft.AspNet.FriendlyUrls
Public Module RouteConfig
Sub RegisterRoutes(ByVal routes As RouteCollection)
Dim settings As FriendlyUrlSettings = New FriendlyUrlSettings() With {
.AutoRedirectMode = RedirectMode.Permanent
}
routes.EnableFriendlyUrls(settings)
End Sub
End Module
of course if I set .AutoRedirectMode to Off it works but without friendlyurls.
Am I doing something wrong?
EDIT 09/10/2019:
We figured out that remove the test of OriginalString.Contains("aspx") in the context_BeginRequest the encryption works, now the code is like:
Private Sub context_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim context As HttpContext = HttpContext.Current
If context.Request.RawUrl.Contains("?") Then
Dim query As String = ExtractQuery(context.Request.RawUrl)
Dim path As String = GetVirtualPath()
If query.StartsWith(PARAMETER_NAME, StringComparison.OrdinalIgnoreCase) Then
Dim rawQuery As String = query.Replace(PARAMETER_NAME, String.Empty)
Dim decryptedQuery As String = Decrypt(rawQuery)
context.RewritePath(path, String.Empty, decryptedQuery)
ElseIf context.Request.HttpMethod = "GET" Then
Dim encryptedQuery As String = Encrypt(query)
context.Response.Redirect(path & encryptedQuery)
End If
End If
End Sub
But now the question is: there is other method to target an aspx page without test the extension? I think there is a risk that targeting things that not should target like "ashx" or cache-busting code that use querystring.

Asp.net vb An error occurred during local report processing in Web Service

I have a web service gift redemption.After redeeem successfull, I want to generate a invoice(pdf content) and store into database. When in debug, it prompts me "An error occurred during local report processing" when it is at the renderedBytes process.
The rdlc is in the web service folder.
The below code works in web application but not in web service.
Public dtInvDtl As New DataTable
Protected Function GenerateInvoice(ByVal sID As String) As Boolean
Dim dtInvoice As DataTable = (get record from database)
Dim dtInvoiceDtl = (get record from database)
dtInvDtl = dtInvoiceDtl
oLocalReport = New LocalReport
oLocalReport.ReportPath = HttpContext.Current.Server.MapPath("Invoice.rdlc")
Dim reportDataSource As ReportDataSource = New ReportDataSource("DS_INVOICE", dtInvoice)
oLocalReport.DataSources.Add(reportDataSource)
' Add handler for subreporting binding function
AddHandler oLocalReport.SubreportProcessing, AddressOf Subreport
Dim reportType As String = "PDF"
Dim mimeType As String = String.Empty
Dim encoding As String = String.Empty
Dim fileNameExtension As String = String.Empty
Dim deviceInfo As String = "<DeviceInfo>" & _
" <OutputFormat>PDF</OutputFormat>" & _
" <PageWidth>8.5in</PageWidth>" & _
" <PageHeight>11in</PageHeight>" & _
"</DeviceInfo>"
Dim warnings() As Warning = Nothing
Dim streams() As String = Nothing
Dim renderedBytes() As Byte
' Render the report
renderedBytes = oLocalReport.Render(reportType, deviceInfo, mimeType, encoding, fileNameExtension, streams, warnings)
End Function
'SubReporting Binding Function
Protected Sub Subreport(ByVal sender As Object, ByVal e As SubreportProcessingEventArgs)
e.DataSources.Clear()
Dim rds = New ReportDataSource("INVOICE_DTL", dtInvDtl)
e.DataSources.Add(rds)
End Sub

Exceptional handling in ASP.NET file handler

I am processing PDF/JPG/GIF files using HTTP Handler.
A popup receives a btnId in query string and detects the file extension then calls the handler with btnId and processes the request.
Files are physical stored on server with file names in DB.
When there is an issue with the file like file not found or some error I want an alert to be displayed and opened window to be closed which is not working right now.
I know the reason and that is I am writing the alert into response which will eventually land in either object tag or Image tag.
Can some one please suggest how can this be achieved. Help will be appreciated. Thanks!!!
Public Class ViewHelpContent
Inherits System.Web.UI.Page
'Method that dynamically decides based on file extension which file viewer to render
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim embed As String = String.Empty
Dim count As Integer
Dim fileName As String = String.Empty
Dim extension As String = String.Empty
Try
If Not IsPostBack Then
If Not Request.QueryString("btnId") Is Nothing Then
Dim btnId As String = Request.QueryString("btnId").ToString()
count = GetFileAttachedToButton(btnId, fileName)
extension = Path.GetExtension(fileName)
If extension.ToLower() = ".pdf" Then
embed = "<object id=""objPDFViewer"" data=""{0}{1}"" type=""application/pdf"">"
embed &= "If you are unable to view file, you can download from here"
embed &= " or there is no file available to be viewed."
embed &= "</object>"
ElseIf extension.ToLower() = ".jpeg" OrElse extension.ToLower() = ".jpg" OrElse extension.ToLower() = ".gif" Then
embed = "<img id=""objImgViewer"" src=""{0}{1}"" alt=""No file is available to be viewed."" />"
Else
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('No help content uploaded for this button.');", True)
Return
End If
helpContent.Text = String.Format(embed, ResolveUrl("~/ProcessHelpContent.ashx?btnId="), btnId)
End If
End If
Catch ex As Exception
ExceptionHandler.LogError(ex)
JSHelper.ShowSystemError(Me)
End Try
End Sub
End Class
Public Class ProcessHelpContent
Implements System.Web.IHttpHandler
'Sub that processes the help request and generates the requested content based on button Id
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim btnId As String = String.Empty
Dim fileName As String = String.Empty
Dim contentType As String = String.Empty
Dim outputDir As String = String.Empty
Dim count As Integer
Dim strPath As FileInfo = Nothing
Dim extension As String = String.Empty
Try
If Not context.Request.QueryString("btnId") Is Nothing Then
btnId = context.Request.QueryString("btnId").ToString()
outputDir = ConfigurationManager.AppSettings("HelpContentFilesFolder")
count = GetFileAttachedToButton(btnId, fileName)
strPath = New FileInfo(outputDir & fileName)
If Not String.IsNullOrWhiteSpace(fileName) Then
If File.Exists(strPath.FullName) Then
extension = Path.GetExtension(strPath.FullName)
If context.Request.QueryString("download") = "1" Then
context.Response.AppendHeader("Content-Disposition", Convert.ToString("attachment; filename=") & fileName)
End If
context.Response.Cache.SetCacheability(HttpCacheability.NoCache)
If extension.ToLower() = ".pdf" Then
context.Response.ContentType = "application/pdf"
ElseIf extension.ToLower() = ".jpg" OrElse extension.ToLower() = ".jpeg" Then
context.Response.ContentType = "image/jpeg"
ElseIf extension.ToLower() = ".gif" Then
context.Response.ContentType = "image/gif"
End If
context.Response.TransmitFile(strPath.FullName)
context.Response.Flush()
Else
context.Response.Write("<script>alert('Uploaded help file is missing. Please re-upload or contact administrator.'); window.close();</script>")
End If
Else
context.Response.Write("<script>alert('Uploaded help file is missing. Please re-upload or contact administrator.'); window.close();</script>")
End If
End If
Catch ex As Exception
ExceptionHandler.LogError(ex)
context.Response.Write("<script>alert('Uploaded help file is missing. Please re-upload or contact administrator.'); window.close();</script>")
End Try
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class

Microsoft Translator for multiple textbox?

I get problem when use Microsoft Bing translator for show output on 3 labels for different languages.
Here is my code :
Imports System
Imports System.Collections.Generic
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Xml.Linq
Public Class AdmAccessToken
Public Property access_token() As String
Get
Return m_access_token
End Get
Set(ByVal value As String)
m_access_token = value
End Set
End Property
Private m_access_token As String
Public Property token_type() As String
Get
Return m_token_type
End Get
Set(ByVal value As String)
m_token_type = value
End Set
End Property
Private m_token_type As String
Public Property expires_in() As String
Get
Return m_expires_in
End Get
Set(ByVal value As String)
m_expires_in = value
End Set
End Property
Private m_expires_in As String
Public Property scope() As String
Get
Return m_scope
End Get
Set(ByVal value As String)
m_scope = value
End Set
End Property
Private m_scope As String
End Class
Partial Class translated
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
'Button1.Click += New EventHandler(Button1_Click1)
End Sub
Protected Sub Button1_Click1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim clientID As String = "*******"
Dim clientSecret As String = "************"
Dim strTranslatorAccessURI As String = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"
Dim strRequestDetails As String = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientID), HttpUtility.UrlEncode(clientSecret))
Dim webRequest As System.Net.WebRequest = System.Net.WebRequest.Create(strTranslatorAccessURI)
webRequest.ContentType = "application/x-www-form-urlencoded"
webRequest.Method = "POST"
Dim bytes As Byte() = System.Text.Encoding.ASCII.GetBytes(strRequestDetails)
webRequest.ContentLength = bytes.Length
Using outputStream As System.IO.Stream = webRequest.GetRequestStream()
outputStream.Write(bytes, 0, bytes.Length)
End Using
Dim webResponse As System.Net.WebResponse = webRequest.GetResponse()
Dim serializer As New System.Runtime.Serialization.Json.DataContractJsonSerializer(GetType(AdmAccessToken))
Dim token As AdmAccessToken = DirectCast(serializer.ReadObject(webResponse.GetResponseStream()), AdmAccessToken)
Dim headerValue As String = "Bearer " + token.access_token
Dim txtToTranslate As String = TextBox1.Text
Dim uri As String = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(txtToTranslate) + "&from=en&to=es"
Dim translationWebRequest As System.Net.WebRequest = System.Net.WebRequest.Create(uri)
translationWebRequest.Headers.Add("Authorization", headerValue)
Dim response As System.Net.WebResponse = Nothing
response = translationWebRequest.GetResponse()
Dim stream As System.IO.Stream = response.GetResponseStream()
Dim encode As System.Text.Encoding = System.Text.Encoding.GetEncoding("utf-8")
Dim translatedStream As New System.IO.StreamReader(stream, encode)
Dim xTranslation As New System.Xml.XmlDocument()
xTranslation.LoadXml(translatedStream.ReadToEnd())
Label1.Text = "Your Translation is: " + xTranslation.InnerText
End Sub
End Class
Can anyone give some advice?
I just need to know how I can get translated text to 3 different label language: label 1 for dutch language, label 2 for english language, and label 3 for indonesian language.
The final chunk of code in your example does the translation from English to Spanish. (The part that starts with Dim txtToTranslate...)
You will have to just use that 3 times (put it in a function) with once doing a translation from your target language to Dutch, once to English, once to Indonesian.
The part where the translation is specified is this:
Dim uri As String = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(txtToTranslate) + "&from=en&to=es"
From=en means 'from English'
To=es means 'to Spanish'
So just amend that for the languages you need...

Access sessions in asp.net handler

I am trying to upload images using generic handler as shown below and I have a normal aspx page where I am showing all the uploaded images after uploading.Everything is working fine.
<%# WebHandler Language="VB" Class="Upload"%>
Imports System
Imports System.Web
Imports System.Threading
Imports System.Web.Script.Serialization
Imports System.IO
Public Class Upload : Implements IHttpHandler, System.Web.SessionState.IRequiresSessionState
Public Class FilesStatus
Public Property thumbnail_url() As String
Public Property name() As String
Public Property url() As String
Public Property size() As Integer
Public Property type() As String
Public Property delete_url() As String
Public Property delete_type() As String
Public Property [error]() As String
Public Property progress() As String
End Class
Private ReadOnly js As New JavaScriptSerializer()
Private ingestPath As String
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim r = context.Response
ingestPath = context.Server.MapPath("~/UploadedImages/")
r.AddHeader("Pragma", "no-cache")
r.AddHeader("Cache-Control", "private, no-cache")
HandleMethod(context)
End Sub
Private Sub HandleMethod(ByVal context As HttpContext)
Select Case context.Request.HttpMethod
Case "HEAD", "GET"
ServeFile(context)
Case "POST"
UploadFile(context)
Case "DELETE"
DeleteFile(context)
Case Else
context.Response.ClearHeaders()
context.Response.StatusCode = 405
End Select
End Sub
Private Sub DeleteFile(ByVal context As HttpContext)
Dim filePath = ingestPath & context.Request("f")
If File.Exists(filePath) Then
File.Delete(filePath)
End If
End Sub
Private Sub ServeFile(ByVal context As HttpContext)
If String.IsNullOrEmpty(context.Request("f")) Then
ListCurrentFiles(context)
Else
DeliverFile(context)
End If
End Sub
Private Sub UploadFile(ByVal context As HttpContext)
Dim statuses = New List(Of FilesStatus)()
Dim headers = context.Request.Headers
If String.IsNullOrEmpty(headers("X-File-Name")) Then
UploadWholeFile(context, statuses)
Else
UploadPartialFile(headers("X-File-Name"), context, statuses)
End If
WriteJsonIframeSafe(context, statuses)
End Sub
Private Sub UploadPartialFile(ByVal fileName As String, ByVal context As HttpContext, ByVal statuses As List(Of FilesStatus))
If context.Request.Files.Count <> 1 Then
Throw New HttpRequestValidationException("Attempt to upload chunked file containing more than one fragment per request")
End If
Dim inputStream = context.Request.Files(0).InputStream
Dim fullName = ingestPath & Path.GetFileName(fileName)
Using fs = New FileStream(fullName, FileMode.Append, FileAccess.Write)
Dim buffer = New Byte(1023) {}
Dim l = inputStream.Read(buffer, 0, 1024)
Do While l > 0
fs.Write(buffer, 0, l)
l = inputStream.Read(buffer, 0, 1024)
Loop
fs.Flush()
fs.Close()
End Using
statuses.Add(New FilesStatus With {.thumbnail_url = "Thumbnail.ashx?f=" & fileName, .url = "Upload.ashx?f=" & fileName, .name = fileName, .size = CInt((New FileInfo(fullName)).Length), .type = "image/png", .delete_url = "Upload.ashx?f=" & fileName, .delete_type = "DELETE", .progress = "1.0"})
End Sub
Private Sub UploadWholeFile(ByVal context As HttpContext, ByVal statuses As List(Of FilesStatus))
For i As Integer = 0 To context.Request.Files.Count - 1
Dim file = context.Request.Files(i)
file.SaveAs(ingestPath & Path.GetFileName(file.FileName))
Thread.Sleep(1000)
Dim fname = Path.GetFileName(file.FileName)
statuses.Add(New FilesStatus With {.thumbnail_url = "Thumbnail.ashx?f=" & fname, .url = "Upload.ashx?f=" & fname, .name = fname, .size = file.ContentLength, .type = "image/png", .delete_url = "Upload.ashx?f=" & fname, .delete_type = "DELETE", .progress = "1.0"})
Next i
End Sub
Private Sub WriteJsonIframeSafe(ByVal context As HttpContext, ByVal statuses As List(Of FilesStatus))
context.Response.AddHeader("Vary", "Accept")
Try
If context.Request("HTTP_ACCEPT").Contains("application/json") Then
context.Response.ContentType = "application/json"
Else
context.Response.ContentType = "text/plain"
End If
Catch
context.Response.ContentType = "text/plain"
End Try
Dim jsonObj = js.Serialize(statuses.ToArray())
context.Response.Write(jsonObj)
End Sub
Private Sub DeliverFile(ByVal context As HttpContext)
Dim filePath = ingestPath & context.Request("f")
If File.Exists(filePath) Then
context.Response.ContentType = "application/octet-stream"
context.Response.WriteFile(filePath)
context.Response.AddHeader("Content-Disposition", "attachment, filename=""" & context.Request("f") & """")
Else
context.Response.StatusCode = 404
End If
End Sub
Private Sub ListCurrentFiles(ByVal context As HttpContext)
Dim files = New List(Of FilesStatus)()
Dim names = Directory.GetFiles(context.Server.MapPath("~/UploadedImages/"), "*", SearchOption.TopDirectoryOnly)
For Each name In names
Dim f = New FileInfo(name)
files.Add(New FilesStatus With {.thumbnail_url = "Thumbnail.ashx?f=" & f.Name, .url = "Upload.ashx?f=" & f.Name, .name = f.Name, .size = CInt(f.Length), .type = "image/png", .delete_url = "Upload.ashx?f=" & f.Name, .delete_type = "DELETE"})
Next name
context.Response.AddHeader("Content-Disposition", "inline, filename=""files.json""")
Dim jsonObj = js.Serialize(files.ToArray())
context.Response.Write(jsonObj)
context.Response.ContentType = "application/json"
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Now I want to add a session variable by generating a random string and add the uploaded images to the newly created random string.
1.I have seen this Question on SO to use System.Web.SessionState.IRequiresSessionState for sessions and how do I create a folder with that and add my images to that folder after doing that how do I access this session variable in my normal aspx page.
2.(Or) the better way is create session variable in aspx page and pass that to handler?If so how can I do that?
3 .I am trying to find the control from my handler.Is that possible?If anyone knows how to get this then also my problem will get resolved so that I am trying to create a session from m aspx page.
Can anyone explain the better way of handling this situation.
I completely agree with jbl's comment.
You can get and set session using HttpContext.Current.Session anywhere on your project.
No matter where you create the session. Just make sure that the session exists before you access it.
Not sure what exactly you are asking here(need some more explanation).
Here is an example, where I used session on HttpHandler. However, it is on c#(hope you can understand).
This is not really an answer but #Knvn wrote a C# example which I couldn't understand so I used a converter to convert it to VB. Posted it here in case it helps someone in the future.
Public Class HttpHandler
Implements IHttpHandler
Implements IRequiresSessionState
Public Sub New()
End Sub
Public Sub ProcessRequest(context As HttpContext)
Dim Request As HttpRequest = context.Request
Dim Response As HttpResponse = context.Response
If SessionHandler.Current.UserID = 0 Then
Response.Redirect("~/Default.aspx")
Else
Try
If Request.Path.EndsWith(".pdf") Then
Dim client As New WebClient()
Dim buffer As [Byte]() = client.DownloadData(HttpContext.Current.Server.MapPath(Request.Path))
Response.ContentType = "application/pdf"
Response.AddHeader("content-length", buffer.Length.ToString())
Response.BinaryWrite(buffer)
Else
Using reader As New StreamReader(HttpContext.Current.Server.MapPath(Request.Path))
Response.Write(reader.ReadToEnd())
End Using
End If
Catch
Response.Redirect("~/Default.aspx")
End Try
End If
End Sub
Public ReadOnly Property IsReusable() As Boolean
' To enable pooling, return true here.
' This keeps the handler in memory.
Get
Return False
End Get
End Property
End Class

Resources