Saturday, 10 December 2011

Base Page For Detecting Session Timeout in ASP.Net/C#



In this tutorial we will be going over how to create a base page class to handle your sessions. The number one question I get asked time and time again is how to manage sessions, and how to detect if a session has expired. Back in the days before .Net things were a little more complicated when it came to solving this riddle, but with the advent of the .Net Framework 2.0 a new class was introduced, the HttpSessionState Class, which is a member of the System.Web.SessionState Namespace. The new HttpSessionState Class gives us access to session state items and other lifetime management methods.

One of the items in the
HttpSessionState class we will be looking at is the IsNewSession Property. This property lets us know whether the current session was created wtih the current request, or if it was an existing session. This is invaluable as we can use it to determine if the users session had expired or timed out. The IsNewSession Property is more robust and advanced then simply checking if the session is null because it takes into account a session timeout as well.

In this tutorial we will create a base page class that we can inherit all our pages from, and in this class we will check the status of the users session in the
Page.OnInit Method. The OnOnit Method fires before the Page Load Event, giving us the ability to check the session before the page is actually rendered. So lets get to some code.

The first thing we will need to do, as with any class you create, is to make sure we have a reference to the appropriate Namespaces. For our class we need but 2 Namespaces, the
System.Web.UI Namespace and the System Namespace, so lets add them to our class.

NOTE:
All Namespace references need to come before the declaration of your class.

csharp
  1. using System;  
  2. using System.Web.UI;  


using System;

using System.Web.UI;



Now we are going to declare our class, the class in this example is named
SessionCheck, and it looks like

csharp
  1. public class SessionCheck: System.Web.UI.Page  
  2. {  
  3.   
  4. }  


public class SessionCheck: System.Web.UI.Page

{

  

}



You will notice that our base class, which we will be inheriting from, inherits from the System.Web.UI.Page class. Doing this gives us access to all the methods, properties and events of the
Page class. In our base class we will have a single property, this will be the property that will hold the URL we want the user to redirect to if there is a problem with their session. We make this property static so we can access it without having to create an instance of the class. We dont want to have to do this because we are inheriting from it. This is our property

csharp
  1. /// <summary>  
  2. /// property vcariable for the URL Property  
  3. /// </summary>  
  4. private static string _url;  
  5.   
  6. /// <summary>  
  7. /// property to hold the redirect url we will  
  8. /// use if the users session is expired or has  
  9. /// timed out.  
  10. /// </summary>  
  11. public static string URL  
  12. {  
  13.     get { return _url; }  
  14.     set { _url = value; }  
  15. }  


/// <summary>

/// property vcariable for the URL Property

/// </summary>

private static string _url;

  

/// <summary>

/// property to hold the redirect url we will

/// use if the users session is expired or has

/// timed out.

/// </summary>

public static string URL

{

    get { return _url; }

    set { _url = value; }

}



Now that we have our property out of the way, we will look at the only method of our base class, the
OnInit Method, which we will override in order to add our ow functionality. In this method we will also initialize our base class, you do that with this line
csharp
  1. base.OnInit(e);  


base.OnInit(e);



In our
OnInit Method we will first check to see if the current session is null. If the session is null we then will check the IsNewSession Property to see if this session was created in this request. If we determine the session is a new session, we will then cal upon the Headers Property of the HttpRequest Class, which is located in the System.Web Namespace.

The
Header we are retrieving is the Cookie Header. Once we have this, we will first check to see if it's null, if it's not null we will look for the value ASP.Net_SessionId. Now if we make it this far, and that cookie exists, we know the session has timed out, so we will then redirect the user to our redirect page, which is set with the URL Property. So lets take a look at our new OnInit Method:

csharp
  1. override protected void OnInit(EventArgs e)  
  2. {  
  3.     //initialize our base class (System.Web,UI.Page)  
  4.     base.OnInit(e);  
  5.     //check to see if the Session is null (doesnt exist)  
  6.     if (Context.Session != null)  
  7.     {  
  8.         //check the IsNewSession value, this will tell us if the session has been reset.  
  9.         //IsNewSession will also let us know if the users session has timed out  
  10.         if (Session.IsNewSession)  
  11.         {  
  12.            //now we know it's a new session, so we check to see if a cookie is present  
  13.             string cookie = Request.Headers["Cookie"];  
  14.             //now we determine if there is a cookie does it contains what we're looking for  
  15.             if ((null != cookie) && (cookie.IndexOf("ASP.NET_SessionId") >= 0))  
  16.             {  
  17.                 //since it's a new session but a ASP.Net cookie exist we know  
  18.                 //the session has expired so we need to redirect them  
  19.                 Response.Redirect("Default.aspx?timeout=yes&success=no");  
  20.             }  
  21.         }  
  22.     }  
  23. }  


override protected void OnInit(EventArgs e)

{

    //initialize our base class (System.Web,UI.Page)

    base.OnInit(e);

    //check to see if the Session is null (doesnt exist)

    if (Context.Session != null)

    {

        //check the IsNewSession value, this will tell us if the session has been reset.

        //IsNewSession will also let us know if the users session has timed out

        if (Session.IsNewSession)

        {

           //now we know it's a new session, so we check to see if a cookie is present

            string cookie = Request.Headers["Cookie"];

            //now we determine if there is a cookie does it contains what we're looking for

            if ((null != cookie) && (cookie.IndexOf("ASP.NET_SessionId") >= 0))

            {

                //since it's a new session but a ASP.Net cookie exist we know

                //the session has expired so we need to redirect them

                Response.Redirect("Default.aspx?timeout=yes&success=no");

            }

        }

    }

}



That's it, we have completed our base class which all our web forms will inherit from, allowing us to keep an eye on the users session. Now that we have the class completed we need to use it. Before it can be affected we need to do 1 of 2 things
  1. Add EnableSessionState = true to the @Page directive on all pages that will inherit from our base class or
  2. Add the following line to the <system.web> section of our web.config file:

CODE

<pages autoEventWireup="true" enableSessionState="true" enableViewState="true" enableViewStateMac="true" smartNavigation="true" validateRequest="false" />
Number 2 on that list will enable session state on all pages in the web. If you dont access session items in each of your pages, this might be overkill. Next we will need to inherit from our base class. Doing this will give our web form the following declaration

csharp
  1. public partial class _Default : SessionCheck  
  2. {  
  3.   
  4. }  


public partial class _Default : SessionCheck

{

  

}



Then in the
Page_Load Event we will set the redirect URL for our base class

csharp
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     SessionCheck.URL = "Default.aspx";  
  4. }  


protected void Page_Load(object sender, EventArgs e)

{

    SessionCheck.URL = "Default.aspx";

}


Now here is the entire base page in its entirety


csharp
  1. // ********************************************************************************  
  2. *********  
  3. //                           LICENSE INFORMATION  
  4. // ********************************************************************************  
  5. *********  
  6. //   SessionCheck Version 1.0.0.0  
  7. //   A Base Page class for detecting session time outs  
  8. //  
  9. //   Copyright © 2008    
  10. //   Richard L. McCutchen   
  11. //   Created: 05MAR08  
  12. //  
  13. //   This program is free software: you can redistribute it and/or modify  
  14. //   it under the terms of the GNU General Public License as published by  
  15. //   the Free Software Foundation, either version 3 of the License, or  
  16. //   (at your option) any later version.  
  17. //  
  18. //   This program is distributed in the hope that it will be useful,  
  19. //   but WITHOUT ANY WARRANTY; without even the implied warranty of  
  20. //   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  
  21. //   GNU General Public License for more details.  
  22. //  
  23. //   You should have received a copy of the GNU General Public License  
  24. //   along with this program.  If not, see <http://www.gnu.org/licenses/>.  
  25. // ********************************************************************************  
  26. *********  
  27.   
  28. using System;  
  29. using System.Web.UI;  
  30.   
  31. /// <summary>  
  32. /// This is a custom "base page" to inherit from which will be used  
  33. /// to check the session status. If the session has expired or is a timeout  
  34. /// we will redirect the user to the page we specify. In the page you use  
  35. /// to inherit this from you need to set EnableSessionState = True  
  36. /// </summary>  
  37. public class SessionCheck : System.Web.UI.Page  
  38. {  
  39.     /// <summary>  
  40.     /// property vcariable for the URL Property  
  41.     /// </summary>  
  42.     private static string _redirectUrl;  
  43.   
  44.     /// <summary>  
  45.     /// property to hold the redirect url we will  
  46.     /// use if the users session is expired or has  
  47.     /// timed out.  
  48.     /// </summary>  
  49.     public static string RedirectUrl  
  50.     {  
  51.         get { return _redirectUrl; }  
  52.         set { _redirectUrl = value; }  
  53.     }  
  54.   
  55.     public SessionCheck()  
  56.     {  
  57.         _redirectUrl = string.Empty;  
  58.     }  
  59.   
  60.     override protected void OnInit(EventArgs e)  
  61.     {  
  62.         //initialize our base class (System.Web,UI.Page)  
  63.         base.OnInit(e);  
  64.         //check to see if the Session is null (doesnt exist)  
  65.         if (Context.Session != null)  
  66.         {  
  67.             //check the IsNewSession value, this will tell us if the session has been reset.  
  68.             //IsNewSession will also let us know if the users session has timed out  
  69.             if (Session.IsNewSession)  
  70.             {  
  71.                //now we know it's a new session, so we check to see if a cookie is present  
  72.                 string cookie = Request.Headers["Cookie"];  
  73.                 //now we determine if there is a cookie does it contains what we're looking for  
  74.                 if ((null != cookie) && (cookie.IndexOf("ASP.NET_SessionId") >= 0))  
  75.                 {  
  76.                     //since it's a new session but a ASP.Net cookie exist we know  
  77.                     //the session has expired so we need to redirect them  
  78.                     Response.Redirect("Default.aspx?timeout=yes&success=no");  
  79.                 }  
  80.             }  
  81.         }  
  82.     }  
  83. }  


// ********************************************************************************

*********

//                           LICENSE INFORMATION

// ********************************************************************************

*********

//   SessionCheck Version 1.0.0.0

//   A Base Page class for detecting session time outs

//

//   Copyright © 2008  

//   Richard L. McCutchen 

//   Created: 05MAR08

//

//   This program is free software: you can redistribute it and/or modify

//   it under the terms of the GNU General Public License as published by

//   the Free Software Foundation, either version 3 of the License, or

//   (at your option) any later version.

//

//   This program is distributed in the hope that it will be useful,

//   but WITHOUT ANY WARRANTY; without even the implied warranty of

//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the

//   GNU General Public License for more details.

//

//   You should have received a copy of the GNU General Public License

//   along with this program.  If not, see <http://www.gnu.org/licenses/>.

// ********************************************************************************

*********

  

using System;

using System.Web.UI;

  

/// <summary>

/// This is a custom "base page" to inherit from which will be used

/// to check the session status. If the session has expired or is a timeout

/// we will redirect the user to the page we specify. In the page you use

/// to inherit this from you need to set EnableSessionState = True

/// </summary>

public class SessionCheck : System.Web.UI.Page

{

    /// <summary>

    /// property vcariable for the URL Property

    /// </summary>

    private static string _redirectUrl;

  

    /// <summary>

    /// property to hold the redirect url we will

    /// use if the users session is expired or has

    /// timed out.

    /// </summary>

    public static string RedirectUrl

    {

        get { return _redirectUrl; }

        set { _redirectUrl = value; }

    }

  

    public SessionCheck()

    {

        _redirectUrl = string.Empty;

    }

  

    override protected void OnInit(EventArgs e)

    {

        //initialize our base class (System.Web,UI.Page)

        base.OnInit(e);

        //check to see if the Session is null (doesnt exist)

        if (Context.Session != null)

        {

            //check the IsNewSession value, this will tell us if the session has been reset.

            //IsNewSession will also let us know if the users session has timed out

            if (Session.IsNewSession)

            {

               //now we know it's a new session, so we check to see if a cookie is present

                string cookie = Request.Headers["Cookie"];

                //now we determine if there is a cookie does it contains what we're looking for

                if ((null != cookie) && (cookie.IndexOf("ASP.NET_SessionId") >= 0))

                {

                    //since it's a new session but a ASP.Net cookie exist we know

                    //the session has expired so we need to redirect them

                    Response.Redirect("Default.aspx?timeout=yes&success=no");

                }

            }

        }

    }

}

And there you have it, a custom base class that you can use to detect session timeouts. I hope you found this tutorial helpful and useful, and thank you for reading smile.gif

Happy Coding!

Imp qus in asp .net4


What is the difference between Debug.Write and Trace.Write? 

The Debug.Write call won’t be compiled when the DEBUGsymbol is not defined (when doing a release build). Trace.Write calls will be compiled. Debug.Write is for information you want only in debug builds, Trace.Write is for when you want it in release build as well.

What are different transaction options available for services components? 

There are 5 transactions types that can be used with COM+. Whenever an object is registered with COM+ it has to abide either to these 5 transaction types.
Disabled: - There is no transaction. COM+ does not provide transaction support for this component.
Not Supported: - Component does not support transactions. Hence even if the calling component in the hierarchy is transaction enabled this component will not participate in the transaction.
Supported: - Components with transaction type supported will be a part of the transaction if the calling component has an active transaction.
If the calling component is not transaction enabled this component will not start a new transaction.
Required: - Components with this attribute require a transaction i.e. either the calling should have a transaction in place else this component will start a new transaction.
Required New: - Components enabled with this transaction type always require a new transaction. Components with required new transaction type instantiate a new transaction for themselves every time.

What does it meant to say “the canonical” form of XML? 

The purpose of Canonical XML is to define a standard format for an XML document. Canonical XML is a very strict XML syntax, which lets documents in canonical XML be compared directly.
Using this strict syntax makes it easier to see whether two XML documents are the same. For example, a section of text in one document might read Black & White, whereas the same section of text might read Black & White in another document, and even in another. If you compare those three documents byte by byte, they’ll be different. But if you write them all in canonical XML, which specifies every aspect of the syntax you can use, these three documents would all have the same version of this text (which would be Black & White) and could be compared without problem. This Comparison is especially critical when xml documents are digitally signed. The digital signal may be interpreted in different way and the document may be rejected.

What are the mobile devices supported by .net platform? 

The Microsoft .NET Compact Framework is designed to run on mobile devices such as mobile phones, Personal Digital Assistants (PDAs), and embedded devices. The easiest way to develop and test a Smart Device Application is to use an emulator.
These devices are divided into two main divisions:
1) Those that are directly supported by .NET (Pocket PCs, i-Mode phones, and WAP devices)
2) Those that are not (Palm OS and J2ME-powered devices).

What is a Windows Service and how does its lifecycle differ from a “standard” EXE? 

Windows service is a application that runs in the background. It is equivalent to a NT service.
The executable created is not a Windows application, and hence you can’t just click and run it . it needs to be installed as a service, VB.Net has a facility where we can add an installer to our program and then use a utility to install the service. Where as this is not the case with standard exe

What is the difference between repeater over datalist and datagrid? 

The Repeater class is not derived from the WebControl class, like the DataGrid and DataList. Therefore, the Repeater lacks the stylistic properties common to both the DataGrid and DataList. What this boils down to is that if you want to format the data displayed in the Repeater, you must do so in the HTML markup. The Repeater control provides the maximum amount of flexibility over the HTML produced. Whereas the DataGrid wraps the DataSource contents in an HTML < table >, and the DataList wraps the contents in either an HTML < table > or < span > tags (depending on the DataList’s RepeatLayout property), the Repeater adds absolutely no HTML content other than what you explicitly specify in the templates. While using Repeater control, If we wanted to display the employee names in a bold font we’d have to alter the “ItemTemplate” to include an HTML bold tag, Whereas with the DataGrid or DataList, we could have made the text appear in a bold font by setting the control’s ItemStyle-Font-Bold property to True. The Repeater’s lack of stylistic properties can drastically add to the development time metric. For example, imagine that you decide to use the Repeater to display data that needs to be bold, centered, and displayed in a particular font-face with a particular background color. While all this can be specified using a few HTML tags, these tags will quickly clutter the Repeater’s templates. Such clutter makes it much harder to change the look at a later date. Along with its increased development time, the Repeater also lacks any built-in functionality to assist in supporting paging, editing, or editing of data. Due to this lack of feature-support, the Repeater scores poorly on the usability scale.
However, The Repeater’s performance is slightly better than that of the DataList’s, and is more noticeably better than that of the DataGrid’s. Following figure shows the number of requests per second the Repeater could handle versus the DataGrid and DataList

What is a PostBack? 

The process in which a Web page sends data back to the same page on the server.

Is it possible to prevent a browser from caching an ASPX page? 

Just call SetNoStore on the HttpCachePolicy object exposed through the Response object’s Cache property, as demonstrated here:
<%@ Page Language="C#" %>


<%

Response.Cache.SetNoStore ();
Response.Write (DateTime.Now.ToLongTimeString ());
%>
SetNoStore works by returning a Cache-Control: private, no-store header in the HTTP response. In this example, it prevents caching of a Web page that shows the current time

What are VSDISCO files? 

VSDISCO files are DISCO files that support dynamic discovery of Web services. If you place the following VSDISCO file in a directory on your Web server, for example, it returns� � references to all ASMX and DISCO files in the host directory and any subdirectories not noted in elements:

xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17">

Name two properties common in every validation control? 

ControlToValidate property and Text property.

What namespace does the Web page belong in the .NET Framework class hierarchy? 

System.Web.UI.Page

Are the actual permissions for the application defined at run-time or compile-time? 

The CLR computes actual permissions at runtime based on code group membership and the calling chain of the code.

What is the difference between authentication and authorization? 

Authentication happens first. You verify user’s identity based on credentials. Authorization is making sure the user only gets access to the resources he has credentials for.

What is a code group? 

A code group is a set of assemblies that share a security context.

How can C# app request minimum permissions? 

Using System.Security.Permissions;
[assembly:FileDialogPermissionAttribute(SecurityAction.RequestMinimum, Unrestricted=true)].

How can you work with permissions from your .NET application? 

You can request permission to do something and you can demand certain permissions from other apps. You can also refuse permissions so that your app is not inadvertently used to destroy some data.

What’s the difference between code-based security and role-based security? Which one is better? 

Code security is the approach of using permissions and permission sets for a given code to run. The admin, for example, can disable running executables off the Internet or restrict access to corporate database to only few applications. Role-based security most of the time involves the code running with the privileges of the current user. This way the code cannot supposedly do more harm than mess up a single user account. There’s no better, or 100% thumbs-up approach, depending on the nature of deployment, both code-based and role-based security could be implemented to an extent.

How do you display an editable drop-down list? 

Displaying a drop-down list requires a template column in the grid. Typically, the ItemTemplate contains a control such as a data-bound Label control to show the current value of a field in the record. You then add a drop-down list to the EditItemTemplate. In Visual Studio, you can add a template column in the Property builder for the grid, and then use standard template editing to remove the default TextBox control from the EditItemTemplate and drag a DropDownList control into it instead. Alternatively, you can add the template column in HTML view. After you have created the template column with the drop-down list in it, there are two tasks. The first is to populate the list. The second is to preselect the appropriate item in the list — for example, if a book’s genre is set to “fiction,” when the drop-down list displays, you often want “fiction” to be preselected.
8