Click here to Skip to main content
15,868,016 members
Articles / Web Development / ASP.NET
Tip/Trick

Session Management for Beginners

Rate me:
Please Sign up or sign in to vote.
4.80/5 (8 votes)
20 Jun 2012CPOL1 min read 17K   9   2
A simple idea to keep session variables easily accessible

Introduction

Coming from an app development background, something I would do is create a class, say CurrentUser, and give a bunch of static variables that I need to access throughout the program. This then allows me to only fetch the data once, taking a tiny bit of pressure off of the server.

The problem with doing this in ASP is that the static variables will stored on the server, and anyone who logs in after the first person will just get their values instead of their own. Using Session there is a very easy, elegant work around. 

Using the code 

Start of lets create a CurrentUser class. Lets assume that throughout our application it is important to know their age, surname, and current city. We create these three variables as properties. Since we only need to retrieve the information, we only set a getter. 

The first thing we do is check whether our value exists in the session. If it is null, we call Initialize.

C#
public class CurrentUser
{ 
    public static string Surname 
    {
        get
        {
            if (String.IsNullOrEmpty(Session["surname"]))
                Initialize();
            return (string)Session["surname"];
        }
    }  
    public static string City
    {
        ...
    } 
    public static string City
    {
        ...
    }      
    private void Initialize()
    {
        MyDataObject obj = FetchMyData();
        Session.Add("surname", obj.Surname);
        ....
    }
}

That is pretty much it. It's not meant to be a super in depth article, just a little tip for you guys just starting on ASP. Hope you find it useful.

History

Version 1: Published.

License

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


Written By
Software Developer Self Employed
South Africa South Africa
I've been passionate about coding since I can remember. My early years of coding involved QBasic and VB. My love for video games lured me into learning Game Maker and spent 2 years playing around with that. I have been programming in C# for a year now, and love learning new things.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Prasad_Kulkarni21-Jun-12 2:56
Prasad_Kulkarni21-Jun-12 2:56 
Good work!

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.