# Sunday, August 22, 2004

For one of the innumerable personal apps I am writing, I decided to store some values in session variables. However, I loathe the syntax for both getting and setting such variables:

Session["UserID"] = userID;

GetSomeData(Convert.ToInt16(Session["UserID"]));

Yuck. Why? The literal strings. I want strongly-typed stuff. I don't want to have the opportunity to accidentally type Session["UsrID"] and deal with resulting issues (I know, it is not that big of a deal, but you know), I want design-time features like code completion/Intellisense. So, at first my idea was to create an enum containing all of the session variables I would use for the app, like so:

public enum SessionVariables
{
   UserID, ClientID, etc.
}

And then I would do this:

Session[SessionVariables.UserID.ToString()] = userID;

That gave me Intellisense and strong typing (more so than a string literal), reducing the chance that something would be typed incorrectly.

But I still don't like the whole "Session[...]" thing. In order to understand my solution, I first must say that I have created a base class for my site's pages. Every ASP.NET page must inherit from the System.Web.UI.Page class at some point, either directly or as a result of a deeper inheritance structure, and I have an intermediate class which inherits from that class, and then all of my pages inherit from that derived class. So, the solution I came up with (I doubt this is in any way original, nor do I feel it is necessarily the ideal) involves creating properties on that base class. For example:

      public short User_UserID
      {
         set
         {
            Session["UserID"] = value;
         }
         get
         {
            return short.Parse(Session["UserID"].ToString());
         }
      }

As long as the page inherits from this intermediate base class instead of inheriting directly from the Page class, I have an easy, strongly-typed means of obtaining session variables without using the nasty syntax (I only need to use it in the property). So, now I can do this in my code-behind files:

User_UserID = userID;

GetSomeData(User_UserID);

Much sexier, and as an added bonus it abstracts WHERE I store the variables. So, if I want to, I can change that property in the base class so that instead of storing this value in session, I can store and retrieve it from a cookie should I desire to do so. (By the way, the reason I preface the property with the "User_" is because it makes it gives the property name a context, in this case these are properties associated with the current User. Also, one of the variables I am storing is a ClientID and that is already the name of a property of the Page class, so I have a collision there.)

Now, the question I have is this: is this a good way to accomplish this? It works, and I personally like it, but I have only thought it through for about 25 minutes.

Kick It on DotNetKicks.com
Monday, August 23, 2004 1:05:10 AM (Mountain Daylight Time, UTC-06:00)
I also have found that doing it that way is one of the better ways of doing it. I frequently find myself doing it in whatever way I feel like doing it that day, and have found that it really doesn't matter a whole lot. Unlike you, I do not 'loathe' collection syntax, but to each his own.
Here are several other ways I have found useful:
1) Generally when I store something in session, I need to store more than just one value in session, so I create an object for it. The object gives me the type safety that I desire, and doesn't allow for me to mistype anything (because it will only be typed once, for every use). I generally mark the class as serializable, although it should be implicit (just trying to keep with good practices :-). I then will create a Parse, or ParseContext method in that class that will retrieve the values for me:

[Serializable]
public sealed class SessionData {
public int UserId;
public string UserName;
//..... constructor's etc
public static SessionData ParseContext(System.Web.HttpContext context) {
return (SessionData)context.Session["UserData"];
}
}

2) If I really do only need one value, then I generally just put a static method in Global.asax (which accepts an arguement of HttpContext) to obtain my value (similar to ParseContext() above, but returning a simple type like string).

Either way though, if you do it that way, then you only have to type the session value once, and you don't have to worry about inheriting from another class (both obviously have their pros and cons). I would definately use constants instead of an enum though, as it will save on both performance, and code aesthetics (Global.UserId).
Jason Walker
Monday, August 23, 2004 6:21:37 PM (Mountain Daylight Time, UTC-06:00)
Yeah, I had thought about creating a custom class or struct in order to aggregate the things I need to store in session, and at some point I may feel good about that (I really don't have much time at this very instant to think about it, but at some point soon I will). Using such is probably more semantically sound than the approach I wrote about, mainly because the UserID is not *really* a property of the Page object, it is more a property of the requester of the page. Yeah, I think that makes more sense. Okay, I think I may change thins . . . just writing this comment has convinced me that there is a better way to do this . .

My ASP.NET pages usually inherit from another base class anyway, because there are certain things I like to provide on a more global level (i.e. the ability to give focus to a particular control, track metrics, etc.), so that is not a big concern for me.

And I don't loathe the collection syntax per se, it is the use of literal strings in my code. Regardless of where it is, I don't like using those, although now that I think about it, the enum syntax I was using (SessionVariables.UserID.ToString()) was not really much better, aside from providing a small amount of code completion help . . .

Thanks for your response.
All comments require the approval of the site owner before being displayed.
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: a@href@title, b, blockquote@cite, i, strike, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Live Comment Preview