Imports Microsoft.VisualBasic
Imports System.Data.Common

Public Class LoggingModule
    Implements IHttpModule
    Public Sub Init(ByVal Application As HttpApplication) Implements IHttpModule.Init
        AddHandler Application.BeginRequest, AddressOf Me.Application_BeginRequest
    End Sub

    Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
        Dim ctx As HttpContext = DirectCast(sender, HttpApplication).Context
        Dim setting As ConnectionStringSettings = _
          ConfigurationManager.ConnectionStrings("MyDB")
        Dim factory As DbProviderFactory = _
          DbProviderFactories.GetFactory(setting.ProviderName)
        Using db As DbConnection = factory.CreateConnection()
            db.ConnectionString = setting.ConnectionString
            Dim comm As DbCommand = factory.CreateCommand()
            comm.CommandText = "INSERT INTO LogInfo(url,userAgent,accessTime) VALUES(@url,@userAgent,@accessTime)"
            comm.Connection = db
            Dim pUrl As DbParameter = factory.CreateParameter()
            pUrl.ParameterName = "@url"
            pUrl.Value = ctx.Request.Url.ToString()
            comm.Parameters.Add(pUrl)
            Dim pAgent As DbParameter = factory.CreateParameter()
            pAgent.ParameterName = "@userAgent"
            pAgent.Value = ctx.Request.UserAgent
            comm.Parameters.Add(pAgent)
            Dim pAccess As DbParameter = factory.CreateParameter()
            pAccess.ParameterName = "@accessTime"
            pAccess.Value = DateTime.Now.ToString()
            comm.Parameters.Add(pAccess)
            db.Open()
            comm.ExecuteNonQuery()
        End Using
    End Sub

    Public Sub Dispose() Implements IHttpModule.Dispose
    End Sub

End Class
