A Handy Extension Method: Retrieving Session Variables

27 במאי 2009

4 תגובות

[More handy extension methods: raise events safely, get the current page load mode]

Retrieving session variables is a daily task for web developers. In order to fetch a session variable, we should check if it exists and only then convert it to the expected type and use it. For example:

int myVal;
if (Session["MyVar"] != null)
{
    int.TryParse(Session["MyVar"], out myVal);
}

// ... more code ...

This is an annoying practice which can be easily replaced by extension methods.

So I’ve built a few extension methods, some are generic and some aren’t, which allow grabbing session values with ease (and even define default return values!):

public static class Extensions
{
    /// <summary>
    /// Gets a session value.
    /// </summary>
    /// <typeparam name="T">The type of the value.</typeparam>
    /// <param name="name">The name of the session variable.</param>
    /// <param name="defaultValue">The default value to use if the value is undefined.</param>
    /// <returns>The session value. If undefined or the value is not from the expected type, the default value is returned.</returns>
    public static T GetValue<T>(this HttpSessionState session, string name, T defaultValue)
    {
        if (session[name] == null)
        {
            return defaultValue;
        }

        try
        {
            return (T)Convert.ChangeType(session[name], typeof(T));
        }
        catch { }

        return defaultValue;
    }

    /// <summary>
    /// Gets a session value.
    /// </summary>
    /// <typeparam name="T">The type of the value.</typeparam>
    /// <param name="name">The name of the session variable.</param>
/// <returns> /// The session value. /// If undefined or the value is not from the expected type, the type's default value is returned. /// </returns>
public static T GetValue<T>(this HttpSessionState session, string name) { return session.GetValue<T>(name, default(T)); } /// <summary> /// Gets a session value. /// </summary> /// <param name="name">The name of the session variable.</param> /// <param name="defaultValue">The default value to use if the value is undefined.</param> /// <returns>The session value. If undefined, the default value is returned.</returns> public static object GetValue(this HttpSessionState session, string name, object defaultValue) { if (session[name] == null) { return defaultValue; } return session[name]; } /// <summary> /// Gets a session value. /// </summary> /// <param name="name">The name of the session variable.</param> /// <param name="defaultValue">The default value to use if the value is undefined.</param> /// <returns>The session value. If undefined, null is returned.</returns> public static object GetValue(this HttpSessionState session, string name) { return session.GetValue(name, null); } }

That’s it. Now fetching a session variable is fun! 🙂

// On an aspx code:
Session["Moo"] = "Yes!";
Session.GetValue("VarName"); // Returns null
Session.GetValue("VarName", 666); // Returns 666
Session.GetValue<String>("VarName"); // Returns null
Session.GetValue<String>("Moo", "LaLaLA"); // Returns "Yes!" (we've defined this variable before)

Enjoy!

All the best,

Shay.

kick it on DotNetKicks.com Shout it

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. שדות החובה מסומנים *

4 תגובות

  1. Lee Dumond27 במאי 2009 ב 18:27

    Pretty nice, except for the empty catch block in the first method. Not good.

    להגיב
  2. shayf27 במאי 2009 ב 18:31

    You're totally right Lee… I noticed that but I didn't want to make this too complicated (thought about adding a raiseOnError parameter).

    I guess it'll be the implementor decision whether to add log there, a parameter or to raise the exception.

    Thanks!

    להגיב
  3. Syed Tayyab Ali27 במאי 2009 ב 19:41

    You article is really using extensions in true sense.

    להגיב