Download.vb - IHttpHandler implementation

imports Microsoft.Win32

Public Class Download
  Implements IHttpHandler

  Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable
    Get
      Return True
    End Get
  End Property


  Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest
    Try
      ' Parse the query string - "Ref" and "Type" variables are mandatory.
      Dim TypeName, Ref As String
      Me.ParseQueryString(context.Request.QueryString, TypeName, Ref)

      ' Create a IDownloadService dynamicaly and delegate to it.
      Dim Service As IDownloadService = CreateDownloadService(TypeName)
      Service.SendItemToBrowser(Ref, context.Response)

    Catch ex As Exception
      SetError(context, ex.ToString())
      context.Trace.Warn(ex.ToString())
      Diagnostics.Trace.WriteLine(ex.ToString())
    End Try
  End Sub


  Public Shared Function CreateHyperlink( _
   ByVal typeName As String, _
   ByVal ref As String) As String

    Return String.Format("Download.aspx?Type={0}&Ref={1}", typeName, ref)
  End Function


  Private Sub ParseQueryString( _
   ByVal qs As System.Collections.Specialized.NameValueCollection, _
   ByRef typeName As String, _
   ByRef ref As String)

    typeName = qs("Type")
    If typeName Is Nothing Then
      typeName = String.Empty
    End If
    ' If typeName contains a space, it is just HTML encoded "+" sign which the CLR uses
    ' when naming nested classes.
    typeName = typeName.Replace(" "c, "+"c)

    ref = qs("Ref")
    If ref Is Nothing Then
      ref = String.Empty
    End If
  End Sub


  Private Shared Function CreateDownloadService(ByVal typeName As String) As IDownloadService
    Try
      Return DirectCast(System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(typeName, True), IDownloadService)
    Catch ex As Exception
      Throw New ApplicationException(String.Format("Neplatný formát požiadavky na stránku ({0}).", typeName), ex)
    End Try
  End Function


  Private Sub SetError( _
   ByVal context As HttpContext, _
   ByVal msg As String)

    context.Response.Clear()
    context.Response.Write(msg)
  End Sub

End Class