Download.aspx.vb

Imports Microsoft.Win32

Public Class Download
  Inherits System.Web.UI.Page

  Protected WithEvents lblError As System.Web.UI.WebControls.Label

#Region " Web Form Designer Generated Code "

  'This call is required by the Web Form Designer.
  <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

  End Sub

  Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
    'CODEGEN: This method call is required by the Web Form Designer
    'Do not modify it using the code editor.
    InitializeComponent()
  End Sub

#End Region


  Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Try
      ClearError()
      If IsPostBack Then      ' we shouldn't have come here in normal circumstances
        SetError("Neočakávaná požiadavka (POST).")
        Exit Sub
      End If

      ' Parse the query string - "Ref" and "Type" variables are mandatory.
      Dim TypeName, Ref As String
      Me.ParseQueryString(TypeName, Ref)

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

      Response.End()
      Debug.WriteLine("Response ended.")

    Catch ex As Exception
      SetError(ex.ToString())
      Trace.Warn(ex.ToString())
      Diagnostics.Trace.WriteLine(ex.ToString())
      Debug.WriteLine("Catch ended.")
    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( _
   ByRef typeName As String, _
   ByRef ref As String)

    typeName = Request.QueryString("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 = Request.QueryString("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 msg As String)

    lblError.Text = msg
  End Sub

	Private Sub ClearError()
    lblError.Text = vbNullString
  End Sub


End Class