4

I have always stored data for a user (after they logged in) in a Session variable, so I can use that data on any page.
I found out that another way to store information globally is to store it in a class, using { get; set;}, and then calling that from any page.

Right now, I've used both these methods as a test, and they both work really well:

Session["LoginId"] = rdr["uniqueIdentifier"].ToString();

And

Member.LoginId = rdr["uniqueIdentifier"].ToString();

Where (In Member.cs)

public class Member
{
    public static int Challenges { get; set; }
    public static int NicknameId { get; set; }
    public static string LoginId { get; set; }
    public static string FriendsListId { get; set; }

    public static void ClearVariables()
    {
        Challenges = 0;
        NicknameId = 0;
        LoginId = null;
        FriendsListId = null;
    }
}

Global.asax

void Session_End(object sender, EventArgs e) 
    {
        Member.ClearVariables();
    }

My question is, is it safe enough to store user data in a class like this, or should I stick with Session objects?

Updated for Completeness Will this post do something like above, but for multiple users? How to access session variables from any class in ASP.NET?

Community
  • 1
  • 1
TheGeekZn
  • 3,696
  • 10
  • 55
  • 91
  • Yep, that's a single user system. Did you try using it with more than one user? – Damien_The_Unbeliever Oct 23 '12 at 06:22
  • Not as of yet. I've only used this so far in testing. – TheGeekZn Oct 23 '12 at 06:22
  • 2
    Even using Session can be a problem. If you needed to use multiple servers behind a load balancer you would need to make sure each user request always went to the same server so that they always had the same session. This can be done with sticky IP addresses but has draw backs; [What is the downside to sticky sessions with load balancers?](http://serverfault.com/questions/46307/what-is-the-downside-to-sticky-sessions-with-load-balancers) – Dave Anderson Oct 23 '12 at 06:28
  • Why not get the best of both worlds. Change your `Member` class to stop using static variables and then simply create a new `Member` instance in `Session_Start@Global.asax` and assign it to the current session. – Jason Larke Oct 23 '12 at 06:30
  • @DaveAnderson Wow, you just gave me a new insight onto this topic. Will read up on it now :D – TheGeekZn Oct 23 '12 at 06:30
  • @JasonLarke, (your statement excited me) could you post an example, or would I need to create a new question for that? – TheGeekZn Oct 23 '12 at 06:32
  • 1
    @DaveAnderson - or use state server or SQL server session state (or I believe there are other solutions that also implement shared session state across multiple web servers) – Damien_The_Unbeliever Oct 23 '12 at 06:43
  • Class storage should be used for constants which you need to access in all the pages/classes. But this should not be used to store user specific data. – Narendra Oct 23 '12 at 06:44
  • @Damien yes those are a better option, the second most popular answer to that question in my comment had a good link; [TechNet June 2009 - Providing Scalability for ASP.NET Applications](http://technet.microsoft.com/en-us/magazine/2009.06.asp.aspx) which covers more alternatives. Keeps control in the developers hands rather than needing the sysadmins. – Dave Anderson Oct 23 '12 at 06:54
  • @NewAmbition You can take a look at something like this: http://stackoverflow.com/questions/5644304/storing-custom-objects-in-sessions this way you wouldn't have to use `Global.asax` at all – Jason Larke Oct 23 '12 at 07:20
  • @JasonLarke I came accross an answer like that; I still want to use it in its own class.cs file, but I have found no way to call the variables. – TheGeekZn Oct 23 '12 at 07:31

6 Answers6

8

In your case it is not safe at all since static variables in asp.net are common to all users.

Amiram Korach
  • 13,056
  • 3
  • 28
  • 30
8

I found this approach is one of the most easy to use and with least error of chances. I think this is called Facade Design Pattern.

 public class SiteSession
{
    #region Attributes
    private static string _siteSession = "__SiteSession__";
    #endregion

    #region Constructor
    private SiteSession()
    {
    }
    #endregion

    #region CurrentSession
    public static SiteSession Current
    {
        get
        {
            SiteSession session = HttpContext.Current.Session[_siteSession ] as    SiteSession;
            if (session == null)
            {
                session = new SiteSession();
                HttpContext.Current.Session[_siteSession ] = session;
            }
            return session;
        }
    }
    #endregion

    #region SessionProperties
    public sherserve.CustomTypes.UserTypes UserType { get; set; }
    public int UserID { get; set; }
    public String StaffID { get; set; }
    public String Position { get; set; }
    public String StaffName { get; set; }
    public int TimeZone { get; set; }

    public String DealerId { get; set; }
    public String DealerPosition { get; set; }
    public String DealerName { get; set; }
    public int DealerFirmId { get; set; }

    public String ClientId { get; set; }
    public String ClientName { get; set; }
    public String ClientBusiness { get; set; }
    public String CountryCode { get; set; }
    public int ClientFirmId { get; set; }
    #endregion

}

Values can be store in Session like this:

 SiteSession.Current.UserType = user.UserType;

And Can be obtain like this :

int userId=    SiteSession.Current.UserID;

It is type safe as well.

Paddy
  • 33,309
  • 15
  • 79
  • 114
muhammad kashif
  • 2,566
  • 3
  • 26
  • 49
  • Before I go ahead an mess something up, could you possibly give the code to use it on the aspx.cs page? – TheGeekZn Oct 23 '12 at 07:48
  • Where does `as TraccrSession` come from? – TheGeekZn Oct 23 '12 at 07:57
  • Check now , actually Traccr is my project name , before giving to you I tried to replace it everywhere. If still your find it in the code just change it to SiteSession. – muhammad kashif Oct 23 '12 at 07:59
  • Almost about to trial this.. Is there anyway to clear all the variables? – TheGeekZn Oct 23 '12 at 08:05
  • Well I did not try this but you can figure it out easily. Try at your self and update us back so that everybody else can know how to do it. – muhammad kashif Oct 23 '12 at 09:29
  • 1
    I kept the `Session.Abandon` and `Session.Clear` on my logout button, and that seems to clear everything. My theory is that it destroys the session the user vairables are stored in. – TheGeekZn Oct 23 '12 at 10:26
  • 1
    Haha well I still tried; so anyone else reading this article will know xD – TheGeekZn Oct 23 '12 at 11:51
  • If you are using shared session state (e.g out of proc), do you need to write the session back after changing the referenced object? Because it gets serialized and sent to other machines, and changed the referenced object probably won't update the session reference? – David d C e Freitas Nov 04 '13 at 03:12
  • Hi there. Enjoyed the answer but when trying access the properties, I get a null reference exception. Does anyone know what might be the problem? Thanks. – Marius Popa Sep 01 '16 at 12:41
  • what is null? Current object or the property itself? if Current object is null then you have not instantiated it, in above example the object of the class SiteSession is a singleton object. If the property is null then in the getter you should handle this. would be easy to answer if you share your code. – muhammad kashif Sep 08 '16 at 10:41
3

Using static variables is not safe. The values set for one user would overwrite the values for another user.
Static variable would mean only one variable is created and used for all sessions. The life time of static variables is the application life time.
If your variables are meant to be user-specific (which appear to be) you will need to stick with Session variables.

coder_bro
  • 10,503
  • 13
  • 56
  • 88
  • So in layman terms - any user that logs on after the previous would destroy the previous users data and replace it with their own? – TheGeekZn Oct 23 '12 at 06:21
1

I am sure that it is not working for you. An instance of class exists only as long as the request is processed. Once the request is processed, you will not be able to get the instance of the class again. In case of static variables, it is application wide and not suitable to store the user specific information.

Session is designed to handle the state of application across the post back and it is the sole purpose of session, i.e. to maintain the state of application and it is ideal for your requirement.

Murtuza Kabul
  • 6,438
  • 6
  • 27
  • 34
0

disadvantage off second approach is when the application restarts the variable will lose their values.but with session your data will be stored in browser cookies.

EDIT:

only use static variables when you need a application level common - shared (between all users) variables.

Behnam Esmaili
  • 5,835
  • 6
  • 32
  • 63
0

Sessions are created per user, while classes, in production, are alive throughout the application's whole lifetime.

Though you may not experience issues in development with only one user, in production each request will override the previous data, and could therefore pose security risks.

Stick to sessions.

Yam Marcovic
  • 7,953
  • 1
  • 28
  • 38