Click here to Skip to main content
11,428,004 members (57,218 online)
Click here to Skip to main content

Programming Practice for Server Side State Maintenance Variable

, 11 Jan 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
Programming practice for server side state maintenance variable

Introduction

Http protocol is stateless, so we need to maintain state on Client side or Server side. For this time, I am going to discuss about the maintaining state on Server Side with one programming practice.

Problem

To maintain state on Server side, most of the developers use Session, Caching, Application variables. But most of the beginner developers make one mistake, which is:

session["myData"] = data;

Code pushes data in session variable(s).

Data = (Conversion_To_Data_Type_Of_Data) session["mydata"];

Code gets data back from session variable.So most of the developers follow the above procedure to push and get data from server side variable.

Disadvantages

  1. Developer requires remembering name of string value, i.e., name of the variable. If you refer to the above code, it's mydata.
  2. If there are a number of developers working on a project, it’s hard to maintain server side variable if we follow the above procedure, i.e., your maintenance increases.
  3. If there are large number of developers working in your project, you require to inform each and every one about the variable you are declaring.

Solution

The easiest solution that I found after doing so much programming is as follows:

Step 1

Create one static class:

public class SessionPropeties
{
 // code
}

Step 2

Create property for each session variable of your application as shown below:

public int UserId
{
        get
        {
           if(HttpContext.Current.Session["UserID"]!=null)
            return Convert.ToInt32(HttpContext.Current.Session["UserID"].ToString());
           else
          return 0;
        }
        set
        {
            HttpContext.Current.Session["UserID"] = value;
        }
}

After following the above steps, the class will be like below:

public class SessionPropeties
{
 public DataType prop1
 {
        get
        {
           if(HttpContext.Current.Session["prop1"]!=null)
            return Convert.ToDataType (HttpContext.Current.Session["prop1"].ToString());
           else
            return defaultvalue;
        }
        set
        {
            HttpContext.Current.Session["prop1"] = value;
        }
      
 }
 public DataType prop2
 {
        get
        {
           if(HttpContext.Current.Session["prop2"]!=null)
            return Convert.ToDataType (HttpContext.Current.Session["prop2"].ToString());
           else
            return defaultvalue;
        }
        set
        {
            HttpContext.Current.Session["prop2"] = value;
        }
      
 }
 
 ...........
 
}

Step 3

In coding to get and set data, you just require to call these properties.

To set data
SessionProperties.UserId = 1;
To get data
int userid = SessionProperties.UserId;

Advantages

  1. Once you declare your properties, you do not need to remember it. You just need to call your Session property class.
  2. Maintenance becomes easy when project size is large or there are a number of developers working in a team, because you just need to refer to the Sessionproperties class having all severside properties. And you can also add property you need and you don’t require to inform all the people working in your team.

Summary

You can maintain your Cache and Application server side variable in a similar way. So it's better you encapsulate your server side variable in one class which makes your task easy when you do code in web application.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Pranay Rana
Software Developer (Senior) GMind Solusion
India India

Microsoft C# MVP (12-13)


Hey, I am Pranay Rana, working as a ITA in MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.

For me def. of programming is : Programming is something that you do once and that get used by multiple for many years

You can visit my blog

StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr

Awards:


Follow on   Twitter   LinkedIn

Comments and Discussions

 
You must Sign In to use this message board.
    Spacing  Noise  Layout  Per page   
GeneralAll objects into a single Class
Yves17-Jan-11 15:59
memberYves17-Jan-11 15:59 
What just a simple Class with all the session members that we would need.
public class SessionPropeties
{
#region Public Data Member(s)

public int iUserID;
public string strLang;
public string strUserName;

//etc..etc
#endregion

#region Constructor

public SessionPropeties()
{
iUserID =-1;
strLang = "EN";
strUserName = "";
}

#endregion

#region Public Method(s)

static SessionPropeties GetSession()
{
SessionPropeties mySession = null;
try
{
mySession = (SessionPropeties)HttpContext.Current.Session["MySessionProperties"];
}
catch { }
return mySession;
}

static void SaveSession(SessionPropeties _mySession)
{
HttpContext.Current.Session["MySessionProperties"] = _mySession;
}

#endregion
}


You Build the object in Global.Asax

Sub Session_Start(ByVal Sender As Object, ByVal E As EventArgs)
Dim sessionInfo As New SessionPropeties()
'Do this only once
SessionPropeties.SaveSession(sessionInfo)
End Sub

You can access at all members like this ... StrongType properties
Dim sessionInfo As SessionPropeties= SessionPropeties.GetSession()
GeneralMy vote of 1
aprishchepov13-Jan-11 11:33
memberaprishchepov13-Jan-11 11:33 
Ideas described are quite immature. It's commonly known that you'd rather use generic helper to work with strong type session objects
GeneralRe: My vote of 1
Pranay Rana14-Jan-11 8:22
memberPranay Rana14-Jan-11 8:22 
thanks for reading my article
My blog:http://pranayamr.blogspot.com/
Programming practice

Do vote my articles December 2010
Best C# article of
Best ASP.NET article of

Best overall artic

GeneralMy vote of 4
Pravin Patil, Mumbai12-Jan-11 4:15
memberPravin Patil, Mumbai12-Jan-11 4:15 
The idea is very good...Good work bro
GeneralRe: My vote of 4
Pranay Rana12-Jan-11 6:58
memberPranay Rana12-Jan-11 6:58 
thank man
My blog:http://pranayamr.blogspot.com/
Programming practice

Do vote my articles December 2010
Best C# article of
Best ASP.NET article of

Best overall artic

GeneralMy vote of 4
Ruchit S.11-Jan-11 21:12
memberRuchit S.11-Jan-11 21:12 
type-safe programmers are safer.
GeneralRe: My vote of 4
Pranay Rana11-Jan-11 21:14
memberPranay Rana11-Jan-11 21:14 
thanks for explaining article more in detail... and for getting my point of article
My blog:http://pranayamr.blogspot.com/
Programming practice

Do vote my articles December 2010
Best C# article of
Best ASP.NET article of

Best overall artic

GeneralGood job!
Venkatesh Mookkan11-Jan-11 20:52
memberVenkatesh Mookkan11-Jan-11 20:52 
Good job. Keep up the good work. Thumbs Up | :thumbsup:

Venkatesh Mookkan (My: Tips/Tricks | Website | Blog Spot | Follow me @ Twitter)

GeneralRe: Good job!
Pranay Rana11-Jan-11 20:58
memberPranay Rana11-Jan-11 20:58 
thanks buddy
My blog:http://pranayamr.blogspot.com/
Programming practice

Do vote my articles December 2010
Best C# article of
Best ASP.NET article of

Best overall artic

GeneralMy vote of 4
Krunal Mevada11-Jan-11 19:48
memberKrunal Mevada11-Jan-11 19:48 
good job
GeneralRe: My vote of 4
Pranay Rana11-Jan-11 21:06
memberPranay Rana11-Jan-11 21:06 
thanks man
My blog:http://pranayamr.blogspot.com/
Programming practice

Do vote my articles December 2010
Best C# article of
Best ASP.NET article of

Best overall artic

GeneralBetter design..
Ruchit S.11-Jan-11 19:43
memberRuchit S.11-Jan-11 19:43 
I completely agree with PIEBALDconsult. casting and/or conversion needs to be done very much carefully especially in case of boxing/unboxing. Anyways, I'd not put more focus on casting and conversion in this comment since that is not the primary purpose of this article. I appreciate your thought of giving type-safe access to boxed session properties/objects. +1 for that. However, here's a more accessible design extension to your design with a little bit of twist.

public static class SessionExtensions
{
    public static SessionPropeties Properties(this HttpSessionState sessionBag)
    {
        return SessionPropeties.Instance;
    }
}
 
public class SessionPropeties
{
    private static SessionPropeties sessionProp = new SessionPropeties();
    private SessionPropeties() { }
 
    public static SessionPropeties Instance
    {
        get
        {
            return sessionProp;
        }
    }
 
    public int UserId
    {
        get
        {
            if (HttpContext.Current.Session["UserID"] != null)
                return Convert.ToInt32(HttpContext.Current.Session["UserID"].ToString());
            else
                return 0;
        }
        set
        {
            HttpContext.Current.Session["UserID"] = value;
        }
    }
}
 
//client-code:
//
//Good thing here is, client-programmers need not worry about what is SessionProperties class and what does it do since it is intentionally 
//hidden when you use extnesion-methods. Secondly, This also reduces the load on client-programmer by not having him to remember/refer-to an 
//additional class in the project.

protected void Page_Load(object sender, EventArgs e)
{
    int userId = Session.Properties().UserId;
}

Good 'type-safe' thought and good job Pranay.. All the best.
GeneralRe: Better design..
Venkatesh Mookkan11-Jan-11 20:57
memberVenkatesh Mookkan11-Jan-11 20:57 
Ruchit S. wrote:
public static SessionPropeties Properties(this HttpSessionState sessionBag)
{
return SessionPropeties.Instance;
}


I believe, this is support from C# 3.0. What about the people who uses C# 2.0 (.NET 2.0 or lesser)?

Venkatesh Mookkan (My: Tips/Tricks | Website | Blog Spot | Follow me @ Twitter)

GeneralRe: Better design..
Ruchit S.11-Jan-11 21:11
memberRuchit S.11-Jan-11 21:11 
Hi Venkatesh,

You are right. Extension methods are C# 3.0 feature and .Net 2.0 devs cannot enjoy this liberty.

Over the period of past 2-3 years, I have realized the languages like C# are becoming more and more epxressive. If you keep the language features in mind while designing your objects and mix them with OOAD practices you'll really be able to achieve great code and greater designs in fact. M not sure if anyone else here has experienced something similar but in my case, I tend to depend a lot on language features while designing. Would like hear from others if they also have similar feeling like this, though thid discussion may be off topic for the article writen here.
GeneralThoughts
PIEBALDconsult11-Jan-11 19:13
memberPIEBALDconsult11-Jan-11 19:13 
"Convert.ToInt32(HttpContext.Current.Session["UserID"].ToString());"

That's dreadful! OMG | :OMG:


You already showed that you can cast it, so cast it!

I also see no need for it to be static (and you don't include static in the code anyway).


This is actually quite a bit like something I'm doing with XML elements. The article on which is almost done.
GeneralRe: Thoughts
Pranay Rana11-Jan-11 19:33
memberPranay Rana11-Jan-11 19:33 
if you read article carefully

you can see that implementation is somewhat similar to singleton pattern .. properties are static because you not want to create instace of class like
SessionPropeties sa = new SessionProperties();

2. When you put your property in class you can apply conversion you want it just example by me

I hope you got my points

Thanks for reading my article..
Regards

GeneralRe: Thoughts
PIEBALDconsult12-Jan-11 3:28
memberPIEBALDconsult12-Jan-11 3:28 
Pranay Rana wrote:
singleton pattern


Dead | X|


Pranay Rana wrote:
you not want to create instace


Yes, I so.


Pranay Rana wrote:
just example by me


When you post an article you appear as an expert and others will follow your lead so you must post the best code you can; never post code you know to be bad without stating that it is so and including the proper code.
GeneralRe: Thoughts
Pranay Rana13-Jan-11 9:55
memberPranay Rana13-Jan-11 9:55 
okies......thanks buddy.. i will take care of this...
My blog:http://pranayamr.blogspot.com/
Programming practice

Do vote my articles December 2010
Best C# article of
Best ASP.NET article of

Best overall artic

GeneralRe: Thoughts
Dstructr17-Jan-11 22:17
memberDstructr17-Jan-11 22:17 
PIEBALDconsult wrote:
Yes, I so.


Thats just stupid, it should be a singelton or static methods.
It doesn't make any sense to recreate this class everytime.

Since session is already a singelton why should the wrapper be otherwise ?

Dst

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150428.2 | Last Updated 11 Jan 2011
Article Copyright 2011 by Pranay Rana
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid