Thursday, 1 December 2016

How to Click or find control by scrolling page in CodedUI


How to click on control if it is visible on page and we need to scroll the page to click on it.

In CodedUI we have UITestingUtilities dll that helps us a lot in finding control or verifying control existance by providing many extended methods.

In below code sample, we have one button control on page. To click on this control manually, we need to scroll the page and then we can click on control. This can be handled through code by using EnsureClickable() method. 
Here we are first making sure that the control exists by using TryFind() method and then trying to click control.

While loop added to check if more page scroll action required. Once the control is clicked the "isClickable" variable set to true, so that to break the While() loop. The exception  is thrown if the control is still hidden on blocked by some other control , To handle this condition we have to catch the exception and instead of throwing it we are scrolling the page down.


Code below

            BrowserWindow bw = new BrowserWindow();
            HtmlButton but = new HtmlButton(bw);
            //define properities for the button here

            bool isClickable = false;
            if(but.TryFind())
            {
                while (!isClickable)
                {
                    try
                    {
                        // It ensures control is visible and clickable
                        but.EnsureClickable();
                        Mouse.Click(but);
                        isClickable = true;
                    }
                    catch(FailedToPerformActionOnHiddenControlException)
                    {
                        //We dont through an exception instead we scroll the page down and try again
                        Mouse.MoveScrollWheel(-1);
                    }
                    catch (FailedToPerformActionOnBlockedControlException)
                    {
                        {
                            //We dont through an exception instead we scroll the page down and try again
                            Mouse.MoveScrollWheel(-1);
                        }
                    }
                }
            }

***Here we can add while loop break logic to avoid the situation like - the method will be continuously searching for control and scrolling page down. To do this we can count the Page scroll action and if it is more than certain count then we can break while loop and throw exception (like Control not found)