Blue Theme Orange Theme Green Theme Red Theme
 
DevExpress Free UI Controls
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Mindcracker MVP Summit 2012
Search :       Advanced Search »
Home » ASP.NET and Web » Create and Use Session and Application Level Events in ASP.NET

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

This article, will explore the Session and Application level events exposed in the Global.asax file and how we can utilize in our applications.

Author Rank :
Page Views : 2037
Downloads : 20
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Create and Use Session and Application Level Events in ASP.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


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!
 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Abhimanyu Kumar Vatsa
http://www.itorian.com/about/
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
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.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
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.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
user right by gopal On July 8, 2010
how restrict user to access particular form or module
is done buy session or global.aspx
Reply | Email | Modify 
Re: user right by Abhimanyu Kumar On July 8, 2010
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


Reply | Email | Modify 
DevExpress Free UI Controls
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.