Thursday, February 6, 2014

C# Session Wrapper

The following C# class is a simple implementation of a wrapper class for sessions. It allows getting, setting and removing of objects (of  a defined type) from the session.
public class SessionWrapper
{
    private static HttpSessionState Session
    {
        get
        {
            if (HttpContext.Current == null)
            {
            throw new ApplicationException("No Http Context, No Session to Get!");
            }
 
            return HttpContext.Current.Session;
        }
    }
 
    public static T Get<T>(string key)
    {
        if (Session[key] == null)
        {
            return default(T);
        }
        else
        {
            return (T)Session[key];
        }
    }
 
    public static void Set<T>(string key, T value)
    {
        Session[key] = value;
    }
 
    public static void Remove<T>(string key)
    {
        if (Session[key] != null)
        {
            Session.Remove(key);
        }
    }
}

C# Is Email Function

The following snippet is handy when validating if a given string is an email address.
public static bool IsEmail(string emailAddress)
        {
            Regex isEmail = new Regex(@"\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$");
            Match m = isEmail.Match(emailAddress);
            return m.Success;
        }