ARTICLE

Create and Use Session and Application Level Events in ASP.NET

Posted by Abhimanyu Kumar Vatsa Articles | ASP.NET using VB.NET June 16, 2010
This article, will explore the Session and Application level events exposed in the Global.asax file and how we can utilize in our applications.
Reader Level:

Introduction

Global.asax file is also known as ASP.NET application file. It provides a way to respond to application or module level events in one central location. We can use this file to implement application security, total hits counting, number of users online as well as other tasks. The Global.asax file exists in the root of the application directory. Global.assx file is an optional file so if we don't need then simply delete it from application and no any other change required. The Global.asax file is configured so that any direct HTTP request (via URL) is rejected automatically, so users cannot download or view its contents. The ASP.NET page framework recognizes automatically any changes that are made to the Global.asax file. The framework reboots the application, which includes closing all browser sessions, flushes all state information, and restarts the application domain.

About Global.asax page

Adding a Global.asax to your web project is quiet simple. Open Visual Studio 2005 or 2008 > Create a new website > Go to the Solution Explorer > Add New Item > Global Application Class > Add.

Now we will have three Application Event Handlers and two Session Event Handlers.

Here is the list of Application Event Handlers:

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application startup
End Sub
   
Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application shutdown
End Sub
       
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
End Sub

Here is the list of Session Event Handlers:

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when a new session is started
End Sub

Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when a session ends.
' Note: The Session_End event is raised only when the sessionstate mode
' is set to InProc in the Web.config file. If session mode is set to StateServer
' or SQLServer, the event is not raised.
End Sub

Event Handlers will be used

Application_Start():
It gets fired when the first resource is requested from the web server and the web application starts.
Application_BeginRequest():
It gets fired when an application request is received. It's the first event fired for a request, which is often a page request (URL) that a user enters.

Working with Global.asax file

<%@ Application Language="VB" %>
<script runat="server">

    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs on application startup
        Application("TitleOfPage") = "USER DETAILS STATEMENT"
        Application("NumberOfOnlineUsers") = 0
        Application("NumberOfUsers") = 0
    End Sub

    Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
        Application.Lock()
        Application("NumberOfUsers") = CType(Application("NumberOfUsers"), Integer) + 1
        Application.UnLock()
    End Sub

    Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs on application shutdown
    End Sub

    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs when an unhandled error occurs
    End Sub

    Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs when a new session is started
        Application.Lock()
        Application("NumberOfOnlineUsers") = CType(Application("NumberOfOnlineUsers"), Integer) + 1
        Application.UnLock()
    End Sub

    Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs when a session ends.
        ' Note: The Session_End event is raised only when the sessionstate mode
        ' is set to InProc in the Web.config file. If session mode is set to StateServer
        ' or SQLServer, the event is not raised.
    End Sub
      
</script>

Working with Default.aspx file

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Create and Use Session and Application Level Events in ASP.NET</title>
</head>
<
body>
    <form id="form1" runat="server">
    <div>
        <table width="100%">
            <tr>
                <td colspan="3">
                    <asp:Label ID="Label1" runat="server" Text="Label" Width="561px" Font-Bold="True" Font-Size="Large" ForeColor="Red"></asp:Label><br />
                    <br />
                </td>
            </tr>
            <tr>
                <td style="width: 68px">
                    <asp:Label ID="Label4" runat="server" Font-Bold="True" ForeColor="Blue" Text="Number of Online Users"
                        Width="252px"></asp:Label></td>
                <td colspan="2">
                    <asp:Label ID="Label2" runat="server" Text="Label" Width="410px"></asp:Label></td>
            </tr>
            <tr>
                <td style="width: 68px">
                    <asp:Label ID="Label5" runat="server" Font-Bold="True" ForeColor="Blue" Text="Number of Users Served (Hits)"
                        Width="395px"></asp:Label></td>
                <td colspan="2">
                    <asp:Label ID="Label3" runat="server" Text="Label" Width="411px"></asp:Label></td>
            </tr>
        </table>

      </div>
    </form>
</body>
</
html>

Working with Default.aspx.vb file

Partial Class _Default
    Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Label1.Text = Application("TitleOfPage")
        Label2.Text = Application("NumberOfOnlineUsers")
        Label3.Text = Application("NumberOfUsers")
End Sub
End Class

HAVE A HAPPY CODING!
 

Login to add your contents and source code to this article
share this article :
post comment
 

This is couples of line from my one of the article about your query. Here it is:


*******************************************************************

Almost we have done everything but still we are missing a major thing. If you run your project at this time will open the SecurePage.aspx without login also. But if you want to redirect the user for login and then with authentication can access the SecurePage.aspx we have to deny the access in SecurePage.aspx page or directly in particular directory. And also when user enters credentials then session variables remember it until user close his browser or click on logout button or link (generally we prefer to click on logout).

So let's take a look to deny the access:

:::::::::::
  :::::::::::
  <
location path="securepage">
    <system.web>
      <
authorization>
        <
deny users="?"/>
      </authorization>
    </
system.web>
  </
location>

</configuration>

And we also have to change the authentication mode to "Forms" like:

::::::::::::::
<
system.web>
    <
authentication mode="Forms">
      <forms loginUrl="Login.aspx" />
    </authentication>
            <
compilation debug="true"/>
</system.web>
::::::::::::::


********************************************************

You can view this article here

http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/1686/?ArticleID=11c2c322-e4ed-4aaa-acf4-8d376acc3c4a


Posted by Abhimanyu Kumar Vatsa Jul 08, 2010

how restrict user to access particular form or module
is done buy session or global.aspx

Posted by gopal zala Jul 08, 2010
Nevron Diagram
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor