Storing User Information in Session for C#

A topic that I deal with a lot, when building custom sites, is the session object. It seems to me that many folks are constantly using that old standby Session[“MyVariableHere”] method of grabbing a session variable. While this method works, we soon realize that *Surprise* the session variable can be null, or, in fact, a typo has been made. The code then becomes something like:

	bool UserLoggedIn = false;
	if (session["UserLoggedIn" != null)
		UserLoggedIn = (bool)["UserLoggedIn"];

Now imagine we want to store the user name, maybe the user’s email address etc. Pretty soon we have about ten differently named session level variables floating around that one might have trouble remembering the name of.

The method I have most often used to deal with this issue is a simple LoggedInUser object that is stored in session upon the users login event and then accessed through a global static class.

The LoggedInUser Class

    
    //Lets mark the class as serializable so that when we go to throw it in
    //session we don't get a nasty error
    [Serializable()]
    public class LoggedInUser
    {
		//Some private variables to store our data
        private long _ID;
        private string _name;
        private string _UserName;
        private string _email;
        
        //and some public ones to expose them (note, one could make these read only)
        public long ID
        {
            get { return _ID; }
            set { _ID = value; }
        }

        public string UserName
        {
            get { return _UserName; }
            set { _UserName = value; }
        }

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public string Email
        {
            get { return _email; }
            set { _email = value; }
        }

		//hey what the heck, now that I have my login ID, etc, why
		//not make it easy to load the full record if needed.
        public Login LoadMyLogin()
        {
           //Load from your DB here and Return the full Login Object
        }

		//Ok let's add a couple more properties for giggles
		public long OrgID { get; set; }
		public bool IsSiteAdmin { get; set; }
		public bool IsOrgActive { get; set; }
		public bool AgreedEULA { get; set; }
    }

So, as you can see we have a simple, serializable class setup for consumption later.

Hydration

Well, now that we have this nice little login class, we need to actually fill it with data. In the code I am yanking this out of I have a larger (more monolithic login object) that contains links to other objects, etc.. I don’t really want to serialize it and, further, it is a Linq object — in this case, so it isn’t easily serializable. To accomplish this task of hydration, I throw a quickie ToLoggedInUser method to my login class.

public LoggedInUser ToLoggedInUser()
{
    LoggedInUser aduser = new LoggedInUser();
    aduser.ID = this.LoginID;
    aduser.Name = this.Person.DisplayName;
    aduser.UserName = this.UserName;
    aduser.Email = this.Person.Email;
    aduser.IsAdmin = this.isAdmin;
    aduser.IsSiteAdmin = this.isSiteAdmin;
	aduser.OrgID = this.Person.OrgID;
	
    return aduser;
}

Once we have the object creation method available we can throw it into session upon user login.

Voila, I now have a hydrated LoggedInUser object. The only remaining piece then is to setup a property in session for easy access later. To accomplish this, I am going to create a GlobalVars static class inside my app_code folder (or in my dll — assuming I have imported system web so I can use httpcontext.current). With the GlobalVars class I can, from inside my pages, use the code:

lblUserName.Text = GlobalVars.LoggedInUser.Name;

or

btnDeleteEntireSite.Visible = GlobalVars.LoggedInUser.isSiteAdmin;

The “GlobalVars” Class — or heck call it “Settings” or “StuffINeed”

The final piece here is to create our static class. Code Below:

public static class GlobalVars
{
	public static LoggedInUser LoggedInUser
	{
		get
		{
			object o = HttpContext.Current.Session["_LoggedInUser"];
			if (o != null)
			{
				return (LoggedInUser)o;
			}
			return null;
		}
	}

Not too much to this piece really, we check to see if the session object is null and cast it to our object, if it exists, otherwise we send out null.

And one more thing…

I use my little GlobalVars class for all sorts of stuff like web.config settings and other random goodness, here is a more built out GlobalVars class to demonstrate some of these uses.

public static class GlobalVars
{
	public static LoggedInUser LoggedInUser
	{
		get
		{
			object o = HttpContext.Current.Session["_LoggedInUser"];
			if (o != null)
			{
				return (LoggedInUser)o;
			}
			return null;
		}
	}
	
	public static string SMTPServer
	{
		get
		{
			object o = ConfigurationManager.AppSettings["SMTP:Server"];
			if (o != null) {
				return o.ToString();	
			}
			return string.Empty;
		}
	}

	public static int SMTPServerPort
	{
		get
		{
			object o = ConfigurationManager.AppSettings["SMTP:ServerPort"];
			if (o != null)
			{
				if (!string.IsNullOrEmpty(o.ToString())) {
					return Convert.ToInt32(o);
				}
			}
			return 25;
		}
	}
	
	public static string SMTPFromAddress
	{
		get
		{
			object o = ConfigurationManager.AppSettings["SMTP:FromAddress"];
			if (o != null)
			{
				return o.ToString();
			}
			return "info@MySite.com";
		}
	}

	public static string SMTPBCC
	{
		get
		{
			object o = ConfigurationManager.AppSettings["SMTP:BCC"];
			if (o != null)
			{
				return o.ToString();
			}
			return "info@MySite.com";
		}
	}
}
Advertisements

2 responses to this post.

  1. Posted by Daniel on July 7, 2011 at 1:44 am

    I have this exact approach and glad someone else does the same thing. I’m not crazy after all! Thanks!

    Reply

  2. Posted by vijaya on June 21, 2012 at 11:05 am

    i want simple example how we define the session in our code c#

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: