Click here to Skip to main content
Licence CPOL
First Posted 16 Aug 2007
Views 10,839
Bookmarked 12 times

How to build a simple Session State Sink

By | 16 Aug 2007 | Article
Allows you to easily manage your Session without casting, and removes redundant code.

Introduction

This code is just to:

  1. Keep all of your Session management in one place.
  2. Allow you to remember what your Session variables are.
  3. Simplify code.

Using the code

The normal way to access the Session in a page is like this. Note that there is no intellisense, and that you will need to cast it every time you want to get it.

Week week = (Week) Session["Week"];

Here's what I'm changing it to. Note that intellisense is available to see what variables are kept in the Session.

Week week = SessionStateSink.Week; 
Plant plant = SessionStateSink.Plant;

Here is the (static) Session State Sink:

using System.Web.SessionState;

public static class SessionStateSink {
    // Getting Current Session --> This is needed, since otherwise

    // the static sink won't know what the session is.

    private static HttpSessionState Session{
        get {return HttpContext.Current.Session; }
    }
 
    // Session Variable - Auto-Create

    public static Week Week {
        get {
            if (Session["Week"] == null) {
                Session.Add("Week",new Week());
            }
            return (Week)Session["Week"];
        }
    }

    //Session Variable - Get/Set

    public static Plant Plant {
        get {
            return (Plant)Session["Plant"];
        }
        set{
            if (Session["Plant"] == null)
                Session.Add("Plant",value);
            else
                Session["Plant"] = value;
        }
    } 
}

Overall, this mostly just makes the code a little cleaner and easier to manage.

License

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

About the Author

ColinBashBash

Software Developer

United States United States

Member

likes boardgames, computer games, and enjoys his .net programming job.

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. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120517.1 | Last Updated 16 Aug 2007
Article Copyright 2007 by ColinBashBash
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid