Thursday 24 May, 2007

ASP.NET Application Level Settings with [Global.asax]

The global.asax file is used to handle application wide events. Below you will see a sample global.asax file along with comments about what each section is used for.

    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the application is started
' This Sub is called when an application begins. An application begins when
' any resource in the application is requested. You could use this sub to
' create an application wide variable such as a counter by typing the line
' below:
Application("CurrentUsers") = 0
End Sub

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the session is started
' Each time a new user requests a page, a new session is started
' You would use the sub to increment the CurrentUser count
Application("CurrentUsers")= cint(appication("CurrentUsers")) + 1
End Sub

Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
' Fires at the beginning of each request
' This sub is called any time a browser request a page in the application
End Sub

Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
' Fires upon attempting to authenticate the user
End Sub

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Fires when an error occurs
' You can use this sub to handle errors on an application wide basis
' instead of using the web.config. This sub does not always want to fire,
' so I have found that adding "Handles Mybase.Error" with fix this.
' Follow the example below to send an email and redirect to a generic page
' on errors (note: you must import the System.web.mail namespace)
Dim objErr As Exception = Server.GetLastError().GetBaseException()
Dim err As String = ""
err = err & "Error in:" & Request.Url.ToString() & vbCrLf
err = err & "Error Message:" & objErr.Message.ToString () & vbCrLf
err = err & "Stack Trace:" & objErr.StackTrace.ToString() & vbCrLf
Server.ClearError()
Dim mailMsg As New MailMessage()
mailMsg.From = ""
mailMsg.To = AddressEmailIsGoingTo
mailMsg.Subject = "Error in Application"
mailMsg.Body = err
SmtpMail.Send(mailMsg)
Server.Transfer(" error.aspx")
End Sub

Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the session ends
' When a user's session expires, this sub is called
Application("CurrentUsers")= cint(appication("CurrentUsers")) - 1
End Sub

Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
' Fires when the application ends
' When there are no more active sessions, the application will terminate
Application("CurrentUsers") = Nothing
End Sub


--
Prakash Samariya (IT Professional, HDSE)
Mob: 9879074678 Res: +91-79-32924610
http://ps-india.blogspot.com/
http://psamariya.googlepages.com/
Below Nelson's School, Opp SBI, Punit Ahram Road, Maninagar, Ahmedabad - 380008, Gujarat, India.

No comments:

Hits4Pay