Friday, August 27, 2010

Cookie parser

Please find cookie parser code, please use it if you like it. You are most welcome to suggest improvements because I know it has lot of scope of improvement. The highlighted yellow code may be used differently, few suggestion:


1) You can have one cookie collection object and before making any http call, use this cookie collection to attach cookies with call based on domain.

2) You may use HashTable and each domain may act as Key and value can have cookie collection object for that particular domain.

3) You may use it as it is if you are not making call domain’s other than “msn” and “live”.





private static void FindDomainCookies(WebHeaderCollection headers )

{

for (int i = 0; i < headers.Count; i++)

{

if ("Set-Cookie" == headers.Keys[i])

{



string rawCookie = headers[i];

if (rawCookie.Contains(","))

{

//regexp for Date format per RFC http://www.w3.org/Protocols/rfc2109/rfc2109 Wdy, DD-Mon-YY HH:MM:SS GMT

string dateRegExp = @"(?<day>expires=[A-Z,a-z]{3}),(?<date>\s\d{2}-[A-Z,a-z]{3}-\d{4}\s\d{2}:\d{2}:\d{2}\sgmt)";

string replaceDateExp = @"${day}${date}";

rawCookie = Regex.Replace(rawCookie, dateRegExp, replaceDateExp, RegexOptions.IgnoreCase);

}

string[] multipleCookies = rawCookie.Split(new char[] { ',' });

for (int j = 0; j < multipleCookies.Length; j++)

{

Cookie cookie = new Cookie();

string[] cookieValues = multipleCookies[j].Split(new char[] { ';' });

string [] paramNameVale;

foreach (string param in cookieValues)

{

paramNameVale = param.Trim().Split(new char[] { '=' });

paramNameVale[0] = paramNameVale[0].ToLower();

if (paramNameVale[0] == "domain")

cookie.Domain = param.Split(new char[] { '=' })[1];

else if (paramNameVale[0] == "expires")

{

string date = paramNameVale[1];

//Date format per RFC http://www.w3.org/Protocols/rfc2109/rfc2109 Wdy, DD-Mon-YY HH:MM:SS GMT

date = Regex.Replace(date, @"(?<day>(sun
mon
tue
wed
thu
fri
sat))", @"${day},", RegexOptions.IgnoreCase);

cookie.Expires = Convert.ToDateTime(date);

}

else if (paramNameVale[0] == "path")

cookie.Path = paramNameVale[1];

}

cookieValues[0] = cookieValues[0].Trim();

cookie.Name = cookieValues[0].Split(new char[] { '=' })[0];

cookie.Value = cookieValues[0].Split(new char[] { '=' })[1];

if (cookie.Domain.ToLower().Contains("live"))


liveCookies.Add(cookie);


else if (cookie.Domain.ToLower().Contains("msn"))


msnCookies.Add(cookie);

}

}

}

}

No comments:

Post a Comment