Sunday, February 22, 2009

ASP.NET Cookies Extensions Methods

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(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(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();
}
public static T ConvertTo(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("OrderId");
Response.Write(orderId.ToString());
}
}

protected void Button1_Click(object sender, EventArgs e)
{
Request.Cookies["MyCookie"].AddToCokie("OrderId", Int32.Parse(this.TextBox1.Text));
}
}
Source : http://blog.sb2.fr/post/2008/11/29/ASPNET-Cookies-Extensions-Methods.aspx

No comments:

Post a Comment