Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Web
Imports System.IO
Imports System.IO.Compression

Namespace Wrox.Demo.Compression

Public Class CompressionModule
    Implements IHttpModule

    Public Sub Dispose() Implements System.Web.IHttpModule.Dispose
        Throw New Exception("The method or operation is not implemented.")
    End Sub

    Public Sub Init(ByVal context As System.Web.HttpApplication) _
       Implements System.Web.IHttpModule.Init
        AddHandler context.BeginRequest, AddressOf context_BeginRequest
    End Sub

    Public Sub context_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
        Dim app As HttpApplication = CType(sender, HttpApplication)

        'Get the Accept-Encoding HTTP header from the request.
        'The requesting browser sends this header which we will use
        ' to determine if it supports compression, and if so, what type
        ' of compression algorithm it supports
        Dim encodings As String = app.Request.Headers.Get("Accept-Encoding")

        If (encodings = Nothing) Then
            Return
        End If

        Dim s As Stream = app.Response.Filter

        encodings = encodings.ToLower()

        If (encodings.Contains("gzip")) Then
            app.Response.Filter = New GZipStream(s, CompressionMode.Compress)
            app.Response.AppendHeader("Content-Encoding", "gzip")
            app.Context.Trace.Warn("GZIP Compression on")
        Else
            app.Response.Filter = _
                          New DeflateStream(s, CompressionMode.Compress)
            app.Response.AppendHeader("Content-Encoding", "deflate")
            app.Context.Trace.Warn("Deflate Compression on")
        End If
    End Sub
End Class

End Namespace
