Revisit the Context option of persistent state management in ASP.NET

Vishvvas
Posted by in ASP.NET category on for Advance level | Points: 250 | Views : 7858 red flag
Rating: 4 out of 5  
 1 vote(s)

The Context.Items option of persistent state menegement is one of the lesser known option but its a good technique in peculiar scenarios and worth mastering.

Objective

To revisit the Context option of persistent state management in ASP.NET

Introduction

State management in ASP.Net is widely discussed and published subject. There are few good articles which help us understand the state management options or techniques. Just to reiterate, they are

·         Application

·         Session

·         ViewState

·         QueryString

·         Cookies

·         Form Post / Hidden Form Field

·         Cache

·         Context

·         Web.config and Machine.config Files

With so many options available, sometimes it becomes difficult to decide when to use what. The options like Session and “ViewState” are well known but it’s not true with other options. In this article we would focus on use of Context and explore the usage scenarios where the “Context” can be used.



Description

Context is nothing but an “HTTPContext” which holds data for a single user for single request and it is persisted for that request only. This is unlike the “Session” option where in the contents can be kept till the particular user is making request (within the session expiry time). “ViewState” is specifically designed for maintaining the contents within post backs.

The “Items” collection of the Context is employed for maintaining the contents during a request. The other properties of this class include “Request”, “Response”, “Session”, “Error” etc. In theory, this collection can hold large amount of data but it is preferred for small amount of data to be maintained as it is often implemented through a handler in “Global.asax” for every request and such data is abandoned for next request. Let’s run through a practical example.

Example: We will see this happening in an ASP.NET web application. Steps for creating a web application in Visual Solution

FileàAddà New Project àChoose “ASP.NET Web Application” àProvide name and location for the project

Also add a Webform i.e. WebForm1.aspx.

The list would be passed through the Context’s item collection and this list would contain the instances of person class as following.

namespace POCO

{

 

public class Person

    {

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string MiddleName { get; set; }

     

        public int PersonId { get; set; }

        public Person()

        {

           

        }

        public Person(string firstName, string lastName)

        {

            this.FirstName = firstName;

            this.LastName = lastName;

        }

        public Person(string firstName, string lastName, string middleName)

        {

            this.FirstName = firstName;

            this.LastName = lastName;

            this.MiddleName = middleName;

        }

        public Person(string firstName, string lastName, int ID)

        {

            this.FirstName = firstName;

            this.LastName = lastName;

            this.PersonId = ID;

        }

        public string PersonName

        {

            get { return FirstName + " " + LastName; }

        }

    }

}

 

In the default page of this application, copy the following code

 

namespace TestWebApplication

{

    public partial class _Default : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            List<POCO.Person> personList = new List<POCO.Person>()

            {

                { new POCO.Person {FirstName="TestFirstName1", LastName="TestLastName1"}},    

                { new POCO.Person {FirstName="TestFirstName2", LastName="TestLastName2"}},  

                { new POCO.Person {FirstName="TestFirstName3", LastName="TestLastName3"}}

            };

            //following list would be available in the webform1.aspx

            Response.Write("The list is available in the webform1.aspx");

            Context.Items["DefaultPagePersonList"] = personList;

             //first check with server transfer

           // ServerTrasfer();

            Redirect();

 

 

        }

private void Redirect()

        {

 

            Response.Redirect("WebForm1.aspx");

        }

        private void ServerTrasfer()

        {

            Server.Transfer("WebForm1.aspx");

 

        }

 

    }

}

In the “WebForm1.aspx“, add a dropdownlist and copy following code.

namespace TestWebApplication

{

    public partial class WebForm1 : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            List<POCO.Person> personListToBeBound = Context.Items["DefaultPagePersonList"] as List<POCO.Person>;

            DropDownList1.DataSource = personListToBeBound;

            this.DropDownList1.DataTextField = "FirstName";

            this.DropDownList1.DataValueField = "LastName";

 

            DropDownList1.DataBind();

        }

    }

}


Output 1: When Server.Transfer is used.

Output 2: When Response.Redirect is used.



The ouput demonstrates that this technique doesn’t work with redirect as it cause the roundtrip to client and the data is not available. When Server.Transfer is implemented the data is available and is shown in the dropdownlist.

As Context’s item collection is available for HTTPHandler, HTTPModules and also in Application_BeginRequest of global.asax file.In this method session is still not associated with the request hence session can’t be used.

Recommended uses:

1.       For personalization i.e. getting the user preferences and loading them from Context.Items

2.       For functionality to be implemented in HTTPHandlers or HTTPModules

3.       Error propagation from particular page to error page executed through Server.Transfer eliminating the need of round trip.

Summary & Conclusion


We started with the nine options/ techniques available in ASP.NET. The focus being on using Context.Items, we run through an example of creating a list and persisting through Context.Items. The data persistence is accomplished when Server.Transfer is employed and not with Response.Redirect.. Hope this helped.

Benefits:

1.       The data in this collection is available in HTTPHandler, HTTPModules and Application_BeginRequest

2.       A roundtrip to browser client is avoided through Sever.Transfer               

 

Limitations / Liabilities / Contradictions / Considerations:

1.       Can’t be used in conjunction with Response.Redirect as data is not persisted.

2.       Needs to be used for small chunk of data even though in theory it’s possible to have large chunk of data.

 

HAPPY PROGRAMMING!!!

Page copy protected against web site content infringement by Copyscape

About the Author

Vishvvas
Full Name: Vishwas Sutar
Member Level: HonoraryPlatinum
Member Status: Member,MVP
Member Since: 5/30/2011 2:13:10 AM
Country: India

http://www.dotnetfunda.com
Extensive and rich experience across gamut of technologies and programming languages like PB,VB,C++,VB.NET, C#, Classic ASP,ASP.NET, ASP.NET MVC.

Login to vote for this post.

Comments or Responses

Posted by: Ashuthinks on: 8/18/2011 | Points: 25
hi
very important and widely used :)
good one !

Thanks,
Ashish Fugat

Login to post response

Comment using Facebook(Author doesn't get notification)