Monday, June 16, 2014

Bug fix for Cookies container in C# .net 3.5

There is bug for .net 3.5 about cookies container, read here (CookieContainer domain handling issue (.NET 2.0-3.5)
) https://connect.microsoft.com/VisualStudio/feedback/details/541197/cookiecontainer-domain-handling-issue-net-2-0-3-5

I got three whole week with pain in my head about this issue. AND there is no solving problem for 3.5 ( its feeling like abandoned technology by microsoft ).

Anyways, here the solving code from http://dot-net-expertise.blogspot.com/2009/10/cookiecontainer-domain-handling-bug-fix.html

Here the solution:
  1. Don’t use .Add(Cookie), Use only .Add(Uri, Cookie) method.
  2. Call BugFix_CookieDomain each time you add a cookie to the container or before you use .GetCookie or before system use the container.
private void BugFix_CookieDomain(CookieContainer cookieContainer)
{
    System.Type _ContainerType = typeof(CookieContainer);
    Hashtable table = (Hashtable)_ContainerType.InvokeMember("m_domainTable",
                               System.Reflection.BindingFlags.NonPublic |
                               System.Reflection.BindingFlags.GetField |
                               System.Reflection.BindingFlags.Instance,
                               null,
                               cookieContainer,
                               new object[] { });
    ArrayList keys = new ArrayList(table.Keys);
    foreach (string keyObj in keys)
    {
        string key = (keyObj as string);
        if (key[0] == '.')
        {
            string newKey = key.Remove(0, 1);
            table[newKey] = table[keyObj];
        }
    }
}


Here example of piece my code, to help you better understanding.
Uri target = new Uri("http://yourwebsite.com/login");

HttpWebRequest Crequest = (HttpWebRequest)WebRequest.Create(target);

//reset MAINCookieContainer;
MAINCookieContainer = new CookieContainer();
Crequest.CookieContainer = MAINCookieContainer;
Crequest.Credentials = CredentialCache.DefaultCredentials;
((HttpWebRequest)Crequest).UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36";
Crequest.Method = "GET";
Crequest.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse Cresponse = (HttpWebResponse)Crequest.GetResponse();
foreach (Cookie cookie in Cresponse.Cookies)
{
 //add Cookie's to the MAINCookieContainer (the next HttpWebRequest will use them)

 MAINCookieContainer.Add(target, cookie);
 BugFix_CookieDomain(MAINCookieContainer);
}