EnVisageOnline/Main-RMO/Source/EnVisage/Code/Session/SessionManager.cs

82 lines
3.4 KiB
C#

using System;
using System.Web;
namespace EnVisage.Code.Session
{
/// <summary>
/// Utility class for interacting with and managing Session objects.
/// </summary>
public static class SessionManager
{
#region Methods
/// <summary>
/// Retrieves an object stored in the current user session associated with the specified session key.
/// </summary>
/// <typeparam name="T">The expected type of the stored object</typeparam>
/// <param name="key">The key which indexes the object within the current session</param>
/// <returns>An object of type T if found; otherwise the default of T</returns>
/// <exception cref="Exception">thrown if the value could not be cast to the specified type or an unknown error occured</exception>
public static T GetValue<T>(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;
}
}
/// <summary>
/// Stores the specified object into the user's current session indexed with the specified key.
/// </summary>
/// <typeparam name="T">The type of object to be stored in session</typeparam>
/// <param name="key">The key which indexes the the object within session</param>
/// <param name="value">The object to be stored in session</param>
public static void SetValue<T>(string key, T value)
{
HttpContext.Current.Session[key] = value;
}
/// <summary>
/// Determines if an object indexed by the specified key exists with the current session.
/// </summary>
/// <param name="key">The index key of the object whose existence is to be checked</param>
/// <returns>True if an object exists; otherwise false</returns>
public static bool Exists(string key)
{
return HttpContext.Current.Session[key] != null;
}
/// <summary>
/// Removes the object associated with the specified key from the user's current session.
/// </summary>
/// <param name="key">The key which indexes the object to be removed.</param>
public static void Remove(string key)
{
if (HttpContext.Current.Session[key] != null)
HttpContext.Current.Session.Remove(key);
}
#endregion
}
}