As a developer, one of the issues I’ve had during coding was remembering all the sessions I have created. I may have created a temporary session that gets used between a few pages or I may have a session that exists throughout the website for a long period of time. The difficult part is remembering which sessions have been created and in use. There are ways to check if a session already exists or not under a particular name. However, they require extra coding in every area where it’s used.
So what if there’s a work-around for this problem? What if you know exactly what session names are used and the data type of the sessions? This would reduce the coding in different areas and only checking that needs to be done is to see if any data already exists in the session (in other words if the session is empty/null or if it contains data).
In this article, I will explain a technique I follow in my C# coding to keep my session variables organized. It is very handy and very useful. I don’t have to go through or do Find search to look up variables I might have used to know whether I’ll be messing something up.
In my example to explain the technique, I will use a session variable called Username that will contain the username of the user who has logged into the site. This is a very common session variable in many websites. Instead of having to query the database for every page to retrieve the username, normally developers store it in a session variable for quick access.
First thing to do in my technique is to create a static class that will be used to hold all the variables. The class will basically be a reference through which the sessions will be accessed.
public static class SessionHandler
{
}
There’s no construct method for this class as it’s a static class. All methods used to access the variable defined inside the classes will be static as well since they will not change. Next step is to declare the name for the session variable.
private static string username = "Username";
Above code shows an example of how the variable name is declared. This is just the identifier of the session variable’s name. If you would have declared a variable called Session[”ABC”] back in the past, this variable will have xxxx (any name you want since it’s private known only within the class although it’s better to use a variation of the value so that it can be easily identifiable) with value of “ABC”. The value is the name known by the system session handler while the variable name is known within the class. The data type will always remain as string because all session variable names are text (string).
The purpose of declaring a variable like this is to avoid spelling mistakes. Since the variables are static, they can be directly accessed (which we will get into later) and avoid typing it wrong (which is something we developers do sometimes unintentionally).
Now we have a class and a variable declared within the class that holds the value that will be used as the identifier for the session. But we do not have a method to access this private variable. To access, we need to create a get/set method.
public static string Username
{
get
{
// Check for null first
if (HttpContext.Current.Session[SessionHandler.username] == null)
{
// Return null if session variable is null
return null;
}
else
{
return HttpContext.Current.Session[SessionHandler.username].ToString();
}
}
set
{
HttpContext.Current.Session[SessionHandler.username] = value;
}
}
Above code shows the Get/Set method for the local variable username. Two important information that should be noticed in the method. First is that it’s a static method. Second is the name of the method. I have used the same name as the value of the local variable username. It is not mandatory to be that way but the method name is how you will access the session variable in your coding so make sure you use an identifiable name instead of random abc123. There is a third important information to notice which I will get into later.
First we’ll look at the Get method for the variable. In this method, we first check if the method exists or not in the current session. HttpContext is a system class (available through System.Web) with a property called Current.. This provides access to the system session handler and the variable that we are trying to check will be identified by the value of SessionHandler.username (classname.variablename). This will look for a session variable that you would have accessed as Session[”Username”] previously. If the variable doesn’t exist, it will return a null value. If it does exist, it will return the value stored inside Session[”Username”] (notice that it’s been converted to string datatype before returning).
Set method is pretty straight forward. Whatever is sent to be stored into that session variable will be in value and it will be set to that variable.
This demonstrates how a simple session variable can be managed efficiently. Summarizing the example above, the SessionHandler class code will be like this.
public static class SessionHandler
{
private static string username = "Username";
public static string Username
{
get
{
// Check for null first
if (HttpContext.Current.Session[SessionHandler.username] == null)
{
// Return null if session variable is null
return null;
}
else
{
return HttpContext.Current.Session[SessionHandler.username].ToString();
}
}
set
{
HttpContext.Current.Session[SessionHandler.username] = value;
}
}
}
To access the variable, all you have to do in coding is call SessionHandler.Username which will access the variable that you are after. You can get the data or set data into the variable without any hassle.
Now we get to the Third important information that I mentioned. In the example, I used a simple string session variable. What if the variable is not string and an object? How would it be stored? The answer to this question is pretty simple. Most of the code is the same.
So modifying the example used earlier, instead of storing the username, we store the user object that contains all user details including the username. The local variable declared will change from username to user (data type will remain as string). The value will change from “Username” to “User”.
In the methods is where the changes will be more prominent. The return data type in the method will have to change from string to User which is the object data type. The returning value from session variable has to be casted into the object data type before it can be returned.
If you want to access the object User, you can do it directly by calling SessionHandler.User. If you want to access the username variable within the User object, you can do so by calling SessionHandler.User.Username (assuming Username is a variable within User class with it’s own Get/Set methods).
The code below contains both examples in one class so that you can see how both types of variables are handled in a single class.
public static class SessionHandler
{
private static string user = "User";
private static string username = "Username";
public static User User
{
get
{
// Check for null first
if (HttpContext.Current.Session[SessionHandler.user] == null)
{
// Return null if session variable is null
return null;
}
else
{
return (User)HttpContext.Current.Session[SessionHandler.user];
}
}
set
{
HttpContext.Current.Session[SessionHandler.user] = value;
}
}
public static string Username
{
get
{
// Check for null first
if (HttpContext.Current.Session[SessionHandler.username] == null)
{
// Return null if session variable is null
return null;
}
else
{
return HttpContext.Current.Session[SessionHandler.username].ToString();
}
}
set
{
HttpContext.Current.Session[SessionHandler.username] = value;
}
}
}
You can add more session variables following similar pattern. Copy and paste the basic pattern (which would be the Username variable) and modify it to your needs.
You must be logged in to post a comment.