views:

681

answers:

3

We have various related session variables for a complex page that has various things going on. Currently these session values are individual page properties (Guid, String, Integer etc). If I had a serializable object with these properties and saved this in the session, would it be more efficient?

+3  A: 

No problem as long as the class is small and compact and is not much functional. You can create immutable structure to this if you need not alter the values once created more frequently. You can always overwrite with new structure upon any modification.

Here's some code.

    public struct MyStruct
    {
        public string MyProp;
        public MyStruct(string myProp)
        {
            this.MyProp = myProp;
        }
    }

    public MyStruct MyStructInSession
    {
        get
        {
            if (Session["_MyStructInSession"] == null)
            {
                Session["_MyStructInSession"] = new MyStruct("unnamed");
                //or you can throw an exception but that's not adviseble.
                //throw new Exception("Nothing stored in session");
            }
            return (MyStruct)Session["_MyStructInSession"];
        }
        set
        {
            Session["_MyStructInSession"] = value;
        }
    }
this. __curious_geek
The values will need to be updated individually. yes it will be a simple object with public getters and setters.
Mark Redman
I recommend creating an immutable struct type and store this in session. That's better way to go. I have done this in past and it's worked out well reliably for me. My struct type had about 8 props.
this. __curious_geek
@Curious, Could you show some sample code of what you did?
Muhammad Akhtar
@Curious, Thanks..........
Muhammad Akhtar
+2  A: 

If performance is a major concern, then you may want to look at optimizing the serialization of the session content. Serialization/deserialization becomes a bigger bottleneck when you scale out to a Session Server or use SQL Server to manage session state.

From MSDN Magazine:

Session state uses a custom serialization mechanism to convert the session dictionary and its contents to a binary blob before storing the data in an out-of-process store. The serialization mechanism has direct support for .NET Framework primitive types, including String, Boolean, DateTime, TimeSpan, Int16, Int32, Int64, Byte, Char, Single, Double, Decimal, SByte, UInt16, UInt32, UInt64, Guid, and IntPtr. These types are written directly to the blob, while object types are serialized with BinaryFormatter, which is slower. Deserialization follows the same rules. By optimizing the session contents, you can significantly reduce the overhead of serialization and deserialization of the state data.

When designing your session object model, avoid storing object types in the session. Instead, only store primitive types in the session dictionary and rebuild your business layer session objects on every request based on the session data. This avoids the overhead of using BinaryFormatter.

As always, measure your performance first before making any optimizations.

Even Mien
Hi, its just the usual preventative concern in keeping things as streamlined as possible and readable/updatable.
Mark Redman
I'd go with the struct then. But if your session serialization starts to become a bottleneck, you can always break the struct apart.
Even Mien
+4  A: 

It's unlikely to be a problem but you might consider storing page specific values in ViewState instead.

I create a static class called SessionInfo that wraps access to session variables, for example:

public static class SessionInfo
{
    private const string AUDITOR_ID_KEY = "AUDITOR_ID_KEY";

    private static T GetSessionObject<T>(string key)
    {
        object obj = HttpContext.Current.Session[key];
        if (obj == null)
        {
            return default(T);
        }
        return (T)obj;
    }

    private static void SetSessionObject<T>(string key, T value)
    {
        if (Equals(value, default(T)))
        {
            HttpContext.Current.Session.Remove(key);
        }
        else
        {
            HttpContext.Current.Session[key] = value;
        }
    }

   public static int AuditorId
   {
       get { return GetSessionObject<int>(AUDITOR_ID_KEY); }
       set { SetSessionObject<int>(AUDITOR_ID_KEY, value); }
   }
}
Jamie Ide
Re: Viewstate, The values are stored in session since the user needs to navigate away from and back to the page, eg when adding various new items or just navigating around the site. The session variables store various category and filter selections which persist for the session. In this case session is more secure and stable than cookies.
Mark Redman
@Mark - It sounds like Session is the better choice for you. I just wanted to point out that ViewState is encrypted and stored in a hidden form field, it's not stored in cookies.
Jamie Ide
@Jamie - Thanks for sharing this solution, I have gone further down this route hence the change in accepted answer.
Mark Redman