<%@ WebHandler Language="VB" Class="C1ReportHttpHandler" %>

Imports System.Web
Imports System.Collections
Imports System.IO
Imports C1.Web.Wijmo.Controls.C1ReportViewer
Imports C1.Web.Wijmo.Controls.C1ReportViewer.ReportService

Public Class C1ReportHttpHandler
    Implements IHttpHandler

    Public Sub ProcessRequest(context As HttpContext) Implements IHttpHandler.ProcessRequest
        Dim reportService As IC1WebReportService = C1WebReportServiceHelper.MakeHelper(DirectCast(context.Request.Params("documentKey"), String))
        ' Export report to a file:
        Dim url As String = reportService.ExportToFile(DirectCast(context.Request.Params("documentKey"), String), context.Request.Params("exportFormat"), Nothing)

        ' Convert url to a file path:
        Dim pathSource As String = url.Substring(url.IndexOf("tempReports/"))
        pathSource = context.Server.MapPath(pathSource)

        Using fsSource As New FileStream(pathSource, FileMode.Open, FileAccess.Read)
            ' Read the source file into a byte array.
            Dim bytes As Byte() = New Byte(fsSource.Length - 1) {}
            Dim numBytesToRead As Integer = CInt(fsSource.Length)
            Dim numBytesRead As Integer = 0
            While numBytesToRead > 0
                ' Read may return anything from 0 to numBytesToRead.
                Dim n As Integer = fsSource.Read(bytes, numBytesRead, numBytesToRead)
                ' Break when the end of the file is reached.
                If n = 0 Then
                    Exit While
                End If
                numBytesRead += n
                numBytesToRead -= n
            End While
            ' Clear all content output from the buffer stream 
            context.Response.Clear()
            ' Add a HTTP header to the output stream that specifies the default filename 
            ' for the browser's download dialog 
            context.Response.AddHeader("Content-Disposition", "attachment; filename=" & DirectCast(context.Request.Params("documentKey"), String) & "." & DirectCast(context.Request.Params("exportFormatExt"), String))
            ' Add a HTTP header to the output stream that contains the 
            ' content length(File Size). This lets the browser know how much data is being transfered 
            context.Response.AddHeader("Content-Length", bytes.Length.ToString())
            ' Set the HTTP MIME type of the output stream 
            context.Response.ContentType = "application/octet-stream"
            ' Write the data out to the client. 
            context.Response.BinaryWrite(bytes)
        End Using
    End Sub

    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property


End Class

