C# – Set CommandTimeout used in Strongly Typed DataSet TableAdapter

ado.netcstrongly-typed-datasettimeout

Preamble:

So, over the past 5 years or so various applications and tools have been written here at my company. Unfortunately many of the people who developed these applications used strongly typed datasets, I'm considering outlawing them in our shop now…

One of the larger processes that used strongly typed datasets is now timing out… I intend to rewrite the the whole process using nHibernate in the next few months but for the moment I need to change the timeout to allow our users to use the process, albeit slowly… Unfortunately Microsoft made the commandtimeout methods private so I can't access them directly.

The only solution I've come across so far is to create a partial class for each TableAdapter and include the timeout methods there…

This is quite clunky as it would mean adding partial classes for quite a few TableAdapters…

Anyone know of a more efficient way to handle this?

Best Answer

I "solved" this using reflection. (While the VS2010 model allows exposing the Adapter property, the SelectCommand, etc, will be null prior to GetData, for instance.)

The "ugly code but functional code" I am currently using:

void SetAllCommandTimeouts(object adapter, int timeout)
{
    var commands = adapter.GetType().InvokeMember(
            "CommandCollection",
            BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic,
            null, adapter, new object[0]);
    var sqlCommand = (SqlCommand[])commands;
    foreach (var cmd in sqlCommand)
    {
        cmd.CommandTimeout = timeout;
    }
}

// unfortunately this still requires work after a TableAdapter is obtained...
var ta = new MyTableAdapter();
SetAllCommandTimeouts(ta, 120);
var t = ta.GetData();

It is not really possible to type adapter better (although perhaps to a Component), due to lack of common base/interfaces.

Happy coding.