using System; using System.Web; namespace EnVisage.Code.Session { /// /// Utility class for interacting with and managing Session objects. /// public static class SessionManager { #region Methods /// /// Retrieves an object stored in the current user session associated with the specified session key. /// /// The expected type of the stored object /// The key which indexes the object within the current session /// An object of type T if found; otherwise the default of T /// thrown if the value could not be cast to the specified type or an unknown error occured public static T GetValue(string key) { object sessionObject = null; string errorMessage; try { sessionObject = HttpContext.Current.Session[key]; if (sessionObject != null) return ((T)sessionObject); return default(T); } catch (InvalidCastException invalidCastException) { string sessionObjectType = sessionObject == null ? "null" : sessionObject.GetType().ToString(); errorMessage = string.Format("SessionManager.GetValueWithDefault failed to cast Session['{0}'] to {1}. Object found is of type {2}.", key, typeof(T), sessionObjectType); var wrappedException = new Exception(errorMessage, invalidCastException); throw wrappedException; } catch (Exception exception) { errorMessage = string.Format("SessionManager.GetValueWithDefault failed to return Session['{0}'].", key); var wrappedException = new Exception(errorMessage, exception); throw wrappedException; } } /// /// Stores the specified object into the user's current session indexed with the specified key. /// /// The type of object to be stored in session /// The key which indexes the the object within session /// The object to be stored in session public static void SetValue(string key, T value) { HttpContext.Current.Session[key] = value; } /// /// Determines if an object indexed by the specified key exists with the current session. /// /// The index key of the object whose existence is to be checked /// True if an object exists; otherwise false public static bool Exists(string key) { return HttpContext.Current.Session[key] != null; } /// /// Removes the object associated with the specified key from the user's current session. /// /// The key which indexes the object to be removed. public static void Remove(string key) { if (HttpContext.Current.Session[key] != null) HttpContext.Current.Session.Remove(key); } #endregion } }