gh0st
gh0st

Reputation: 33

CookieContainer mishap

I edited this for better readability. This is also a different question

The purpose of this code is to convert a CookieContainer object to a HashTable for later conversion to a CookieCollection. I get the error "Cannot find variable 'm_domainTable'" for this code

var cookieJar = new CookieContainer();
cookieJar.Add(new Uri("http://someuri.com"), new Cookie("name", "value", "/path/", ".domain"));
var table = (Hashtable) cookieJar.GetType().InvokeMember("m_domainTable",
            BindingFlags.NonPublic |
            BindingFlags.GetField |
            BindingFlags.Instance,
            null,
            cookieJar,
            new object[] {});

The purpose of even using this hack is to be able to cycle through a locally stored cookie file. I tried creating a new project using this code suggested below but I get the error "Object not set to an instance of an Object".

var cookieJar = new CookieContainer();
var table = (Hashtable)cookieJar.GetType()
        .GetField("m_domainTable", BindingFlags.NonPublic | BindingFlags.Instance)
        .GetValue(cookieJar);

So I am stuck. Previously I had shown my SendPost() method but since this error only involves these bits of code I took out that method. If you need any more code or need me to test anything let me know as I would love to get this working.

My enviornment setup is MonoDevelop using Mono / .Net 4.5 using these assemblies:

using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Collections;
using System.Web;

Upvotes: 0

Views: 384

Answers (1)

Andrey Korneyev
Andrey Korneyev

Reputation: 26876

Well, you can access this private field like

var table = (Hashtable)cookieJar.GetType()
                .GetField("m_domainTable", BindingFlags.NonPublic | BindingFlags.Instance)
                .GetValue(cookieJar);

Update

I missed mono tag in your original question. But since your working environment is Mono, not Microsoft CLR - then you might looking in the wrong way.

As far as I can see - m_domainTable hashtable exists only in Microsoft implementation, but not in Mono.

It can be proved by simple test code:

var cookieJar = new CookieContainer();
var type = cookieJar.GetType();
var fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

foreach (var field in fields)
    Console.WriteLine(field.ToString());

Then being run in Microsoft CLR, it outputs:

System.Collections.Hashtable m_domainTable
Int32 m_maxCookieSize
Int32 m_maxCookies
Int32 m_maxCookiesPerDomain
Int32 m_count
System.String m_fqdnMyDomain

but if you'll run it in Ideone (I suppose it is running Mono there), you'll get:

System.Int32 capacity
System.Int32 perDomainCapacity
System.Int32 maxCookieSize
System.Net.CookieCollection cookies

And have a look here: System.Net.CookieCollection cookies - it seems here is the field you need....

Upvotes: 1

Related Questions