web 2.0

ASP.NET Cookies Extensions Methods

Hi,

Tonight a simple way to manage Cookies on an ASP.NET Application with Strongly Typed Objects.

These Extensions might be improved but it's a beginning.

Here is the code

public static class CookieExtensions
{
    public static void AddToCokie<T>(this HttpCookie cok, String name, T val)
        where T : struct
    {
        if (cok == null)
            return;
        if (!String.IsNullOrEmpty(cok.Values[name]))
            cok.Values.Remove(name);
        cok.Values.Add(name, val.ToString());
        HttpContext.Current.Response.Cookies.Add(cok);
    }
    public static T GetCookieValue<T>(this HttpCookie cok, String name)
        where T : struct
    {
        if (cok == null)
            return default(T);
        if (String.IsNullOrEmpty(cok[name]))
            return default(T);

        return cok[name].ConvertTo<T>();
    }
    public static T ConvertTo<T>(this String input) where T : struct
    {
        T ret = default(T);

        if (!string.IsNullOrEmpty(input))
        {
            ret = (T)Convert.ChangeType(input, typeof(T));
        }

        return ret;
    }
}

And here is a sample of usage

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Int32 orderId = Request.Cookies["MyCookie"].GetCookieValue<Int32>("OrderId");
            Response.Write(orderId.ToString());
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Request.Cookies["MyCookie"].AddToCokie<Int32>("OrderId", Int32.Parse(this.TextBox1.Text));
    }
}

Hope this help's!



Views(852)

kick it on DotNetKicks.com

Share/Save/Bookmark Subscribe

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

ASP.NET | C#

Comments

Technorati Profile