So, I am working on a demo web dashboard. Previously, I had been using Session to store settings about the dashboard, but I would like to move it to a more persistent means of saving settings.
It seems to me that using cookies would be my best bet. I’m not entirely positive I have the time to work everything out for writing to/from a database properly.
That being said, I might be in over my head on some assumptions I had made about the similarities between Session and Cookies.
Currently, I have some code like this:
public Dictionary<string, RadPageViewSetting> PageViewStates
{
get
{
Dictionary<string, RadPageViewSetting> _pageViewStates = (Dictionary<string, RadPageViewSetting>)Session["PageViewStates"];
if (object.Equals(_pageViewStates, null))
{
_pageViewStates = new Dictionary<string, RadPageViewSetting>();
Session["PageViewStates"] = _pageViewStates;
}
return _pageViewStates;
}
set
{
Session["PageViewStates"] = value;
}
}
where RadPageViewSetting is a class with some properties in it which I am recording.
Is this functionality possible with cookies? If not, where should I be looking to persist my data through browser-closes?
EDIT: I am going to use http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx to help me serialize the dictionary and then go about serializing my own custom data hypers (RadPageViewSetting).
EDIT: Here’s my untested solution. Could someone take a look at this real quick and let me know if it looks incorrect?
public SerializableDictionary<string, RadPageViewSetting> PageViewStates
{
get
{
SerializableDictionary<string, RadPageViewSetting> _pageViewStates = new SerializableDictionary<string,RadPageViewSetting>();
HttpCookie cookie = HttpContext.Current.Response.Cookies["PageViewStates"]; //If the named cookie does not exist, this method creates a new cookie with that name.
if (object.Equals(cookie, null))
{
cookie = new HttpCookie("PageViewStates");
cookie.Expires = DateTime.Now.AddYears(100);
cookie.Value = null;
HttpContext.Current.Response.Cookies.Add(cookie);
}
else if( cookie.Value != null )
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(cookie.Value);
XmlSerializer serializer = new XmlSerializer(_pageViewStates.GetType());
_pageViewStates = serializer.Deserialize(stream) as SerializableDictionary<string, RadPageViewSetting>;
HttpContext.Current.Response.Cookies.Set(cookie);
}
return _pageViewStates;
}
set
{
XmlSerializer serializer = new XmlSerializer(value.GetType());
MemoryStream stream = new MemoryStream();
serializer.Serialize(stream, value);
StreamReader reader = new StreamReader(stream);
HttpContext.Current.Response.Cookies["PageViewStates"].Value = reader.ReadToEnd();
}
}
Simple use Response.Cookies instead of Session.
Basically in a nutshell from MSDN
You should be able to store what ever you like in the cookie as long as you can serialize it into a string. As cookies are plain text.