Imports System.Web.Optimization
Imports System.Configuration
Public Class MvcApplication
    Inherits System.Web.HttpApplication

    Protected Sub Application_Start()

            ' 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)
            Global.SelectPdf.GlobalProperties.ForceDenyLocalFileAccess = deny
        AreaRegistration.RegisterAllAreas()
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters)
        RouteConfig.RegisterRoutes(RouteTable.Routes)
        BundleConfig.RegisterBundles(BundleTable.Bundles)
    End Sub

    ' "Working …" button support. The convert action's response is a PDF/image
    ' DOWNLOAD, which doesn't 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 restores the button. Only acts on downloads carrying the token.
    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                   ' the page's JS must read it
        cookie.Expires = DateTime.UtcNow.AddSeconds(30)
        resp.Cookies.Add(cookie)
    End Sub
End Class
