Help with Cookies

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am trying to write some values to cookies to later get those values on
postback events.
I want to know how to store a multi-value cookie, and request those values.
I am using C#. Can anyone help with some code?

Hector
 
one possible way:

i am using an object wrapper for my values and i will serialize my
object and write it in a cookie, and then upon the retrival i will
deserialize it.
But you should be careful about the size.

Hope this helps.
 
Ok,
first please note I have not tested the following code, and i typed it
directly here.

Assume you have two attrubures that you wish to put them in a cookie:

string FName;
string LName


option one:

HttpCookie cookie = new HttpCookie("NameCookie");
cookie.Values["FName"] = "ffff";
cookie.Values["LName"] = "llll";
HttpResponse.Cookies.Add(cookie);

for retrieving use HasKeys.

option two:
this option is designed for masochist people like me! But seriously it
has some advantages (and i am not going to tell you what they are).

you need to create a class to wrap your types, in our case two
properties, something like:
[Serilialize]
public class Name
{
string fname, lname;

public Name(string fname, string lname)
{
this.fname = fname;
this.lname = lname;
}

public string FName
{
get { return fname; }
set { fname = value; }
}

public string LName
{
get { return lname; }
set { lname = value; }
}
}

now you have to write a serializer method that returns a string:

string SerilizeName(Name name)
{
IFormatter formatter = new BinaryFormatter();
StringWriter write= new StringWriter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, name);

//please note you should use different encoding
return Convert.ToBase64String(stream.ToArray());
}

now the main method:

void WriteToCookie()
{
Name name = new Name("fff", "lll");
HttpCookie coockie = new HttpCookie("NameCookie", SerilizeName(name))
HttpResponse.Cookies.add(coockie);
}

upon the cookie retreival you should deserilize the string and convert
it to the Name class, and i will leave the deserilizer to you ;)
 
Back
Top