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

Session Management for Beginners

, 20 Jun 2012
Rate this:
Please Sign up or sign in to vote.
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.

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)

Share

About the Author

DominicZA
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.
Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 5 PinmemberPrasad_Kulkarni21-Jun-12 2:56 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140814.1 | Last Updated 20 Jun 2012
Article Copyright 2012 by DominicZA
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid