Sunday, January 8, 2012

Count Session variables in ASP

This is a very simple interface, which exposes an integer for you to use to report the count
of session variables at the moment session state is restored.
This code allows you to move custom information from a preprocessor into an instance of
a request handler. To pass this information to any handler, the implementation needs only to
inherit from this interface:
public class CreateSessionVars : System.Web.UI.Page, ISessionCounter
{
private int _SessionVarCount;
public int SessionVarCount
{
get { return _SessionVarCount; }
set { _SessionVarCount = value; }
}
//Snip…
This page uses implementation inheritance with System.Web.UI.Pageas its base class, as
is the usual case for ASPX code-behinds, but then takes the additional step of implementing
the ISessionCounter interface. The page will now be instructed by the request preprocessor
as to how many session variables existed when the session state was first restored. It can do
whatever it needs to with this information. In this case, you’ll use it to expose a button to cre-
ate a user-selected number of session variables, and then track the deltas as postbacks occur.
Leveraging this interface-based approach to polymorphic handler types is a common
method to check type information on the handler in a preprocessor, and pass information
from the preprocessor pipeline into a handler. You can use custom attributes this way as well,
for an aspect-based approach yielding similar polymorphic behavior.
Running Codes
%@ Page language="c#"
CodeFile="CreateSessionVars.aspx.cs"
Inherits="CreateSessionVars" %>
private void btnSubmit_Click(object sender, System.EventArgs
{
int Count = int.Parse(txtCount.Text) + Session.Keys.Count
for (int i = Session.Keys.Count; i < Count; i++) { Session[string.Format("sessionvar{0}",i)] = i; } } private void btnSubmit_Click(object sender, System.EventArgs { int Count = int.Parse(txtCount.Text) + Session.Keys.Count for (int i = Session.Keys.Count; i < Count; i++) { Session[string.Format("sessionvar{0}",i)] = i; } }



No comments:

Post a Comment