Question

I just learned a painful lesson about the use of static properties in classes. Mainly that they are not browser session specific when they are not part of the aspx page loaded. (Please correct me anywhere I am wrong as I don't have formal education in programming)

I have since been using Session objects.

The main thing that I hate about Session objects is that they are subject to typos because they are unknown to intellisense.

You can't just type the namespace.class.class.setgetproperty and know that you are referencing the correct session object like you can with class properties.

Is there a way to mix class and session objects together so when I call on a session object I can utilize intellisense?

Was it helpful?

Solution

Create a wrapper class, that wraps the Session object. Ultimately, you still have to use a key/value system still, though.

public class MySessionWrapper
{
   public string MySessionProperty 
   {
      get
      { 
          return Session["myProperty"] == null ? null : (string) Session["myProperty"]; 
      }
      set
      { 
          Session.Add("myProperty", value);
      }
   }
}

OTHER TIPS

You could wrap it inside of methods. As an example, say we were storing a User object. Something like this:

public void SetUser(User user)
{
    Session.Add("User", user);
}

public User GetUser()
{
     User user = (User)Session["User"];

     return user;
}

I think that I have optimized the code. Let me know if anyone sees anything that could be a issue. So far I have seen no problems.

public Users.CurrentUser GetSetCurrentUser
{
    get
    {
        if (Session["cUser"] == null) GetSetCurrentUser = new Users.CurrentUser();
        return (Users.cUser)Session["CurrentUser"];
    }
    set { Session.Add("cUser", value); }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top