Click here to Skip to main content
Click here to Skip to main content

Session Management for Beginners

By , 20 Jun 2012
 

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.

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)

About the Author

DominicZA
Software Developer Self Employed
South Africa South Africa
Member
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.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberPrasad_Kulkarni21 Jun '12 - 2:56 
Good work!
GeneralMy vote of 5membermember6020 Jun '12 - 18:25 
my 5!

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 20 Jun 2012
Article Copyright 2012 by DominicZA
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid