Tuesday, January 16, 2007

ButtonCollection iteration and PostBacks using WatiN

I've been playing with the .NET 2.0 WatiN framework and ran into a problem that might be of interest to someone.

My application under test is .NET 1.1. I was trying to click through a series of buttons in a DataGrid and also click 'OK' on the confirmation dialog that would appear after the DataGrid
button was clicked. I was generally only able to go through this process once, though, before receiving the following exception:

System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).

My code to loop through the DataGrid buttons at the time was as follows:

ButtonCollection collection = ie.Buttons.Filter(Find.ByValue("Delete"));
if (collection.Length > 0)
{
foreach (Button button in collection)
{
//ConfirmDialogHandler confirmDialogHandler = new ConfirmDialogHandler();

using (new UseDialogOnce(ie.DialogWatcher, new SimpleJavaDialogHandler(false)))
{
button.Click();
//button.ClickNoWait();
//confirmDialogHandler.WaitUntilExists();
//confirmDialogHandler.OKButton.Click();
//ie.WaitForComplete();
}
}
}

As you can see from the commented-out code I also tried the ConfirmDialogHandler as described in this email.


I finally got my concept to work by using this code:

while (ie.Buttons.Filter(Find.ByValue("Delete")).Length > 0)
{
Button button = ie.Buttons.Filter(Find.ByValue("Delete"))[0];
using (new UseDialogOnce(ie.DialogWatcher, new SimpleJavaDialogHandler(false)))
{
button.Click();
}
}


I assume that my problem was related to the just-clicked button no longer being part of the original ButtonCollection after PostBack and that this created some type of concurrency issue somewhere in the ASP.NET / WatiN innards.

Hope that this helps someone.