Imports System
Imports System.Configuration
Imports System.Web
Imports SelectPdf

Public Class Global_asax
    Inherits System.Web.HttpApplication

    Protected Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Apply the DenyLocalFileAccess flag from Web.config globally.
        ' When true, SelectPdf rejects any attempt to convert local files / file:// URLs.
        Dim deny As Boolean = False
        Boolean.TryParse(ConfigurationManager.AppSettings("DenyLocalFileAccess"), deny)
        GlobalProperties.ForceDenyLocalFileAccess = deny
    End Sub

    ' "Working …" button support. The sample pages convert on a postback whose
    ' response is a PDF/image DOWNLOAD — which does NOT navigate the page, so the
    ' page's sample-form.js can't tell when the work is done. It sends a one-time
    ' "spdfDownloadToken" form field; here we echo it back as a cookie ON the
    ' download response, so the JS poll knows the file was delivered and restores
    ' the button. Acts only on actual downloads carrying the token.
    Protected Sub Application_PreSendRequestHeaders(ByVal sender As Object, ByVal e As EventArgs)
        Dim ctx As HttpContext = HttpContext.Current
        If ctx Is Nothing Then Return

        Dim resp As HttpResponse = ctx.Response
        Dim ct As String = If(resp.ContentType, String.Empty)
        Dim isDownload As Boolean =
            ct.StartsWith("application/pdf", StringComparison.OrdinalIgnoreCase) OrElse
            ct.StartsWith("image/", StringComparison.OrdinalIgnoreCase) OrElse
            ct.StartsWith("application/octet-stream", StringComparison.OrdinalIgnoreCase)
        If Not isDownload Then Return

        Dim token As String = ctx.Request.Form("spdfDownloadToken")
        If String.IsNullOrEmpty(token) Then Return

        Dim cookie As New HttpCookie("spdfDownloadToken", token)
        cookie.Path = "/"
        cookie.HttpOnly = False
        cookie.Expires = DateTime.UtcNow.AddSeconds(30)
        resp.Cookies.Add(cookie)
    End Sub
End Class
