Powered By Blogger

Search Here!

Saturday, February 16, 2013

Webdriver Ignoring UnexpectedAlertBehavior and Zoom Level

With 'UnexpectedAlertBehavior' option we can do any work in front like chatting while in background window scripts are executing and 'IgnoreZoomLevel ' we can also run scripts at any zoom level.

InternetExplorerOptions options = new InternetExplorerOptions

                                                  {
                                                      IntroduceInstabilityByIgnoringProtectedModeSettings = true,
                                                      UnexpectedAlertBehavior = InternetExplorerUnexpectedAlertBehavior.Ignore,
                                                      IgnoreZoomLevel = true                                                     
                                                  };
IWebDriver webDriver = new InternetExplorerDriver(ieDriverPath, options, TimeSpan.FromMinutes(10));            webDriver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(timeOut));
return webDriver;

Generate Random Number

Generate Random Number for specified string length and character set.

///
/// Generates the alphanumeric random code.
///

/// This is the set of the characters from which random code needs to generate.
/// The length of the string needed to generate random code.
/// The alphanumeric random code.

        protected string GetRandomNumber(string characterSet, int length)
        {
            Random random = new Random();
            //The below code will select the random characters from the set
            //and then the array of these characters are passed to string
            //constructor to makes an (alpha) numeric string depends on the user need.
            string getRandomCode = new string(Enumerable.Repeat(characterSet, length)
                    .Select(set => set[random.Next(set.Length)]).ToArray());
            return getRandomCode;
        }


Character Set = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+}{“:?><,./’;[]|\"

Webdriver Handling Thinking Indicator Loading !

When we switch to different page or Iframes, we need to wait for some time due to loader in progress. Webdriver throws exception like 'ElementNotVisibleException' or 'TimeoutException' in case if we not handled this situation properly. 

///
/// Wait until Thinking Indicator is loading on the page.
///

/// True if the thinking indicator element is currently present
/// after the specified time interval, false otherwise.

/// if the window not loads in the specified interval of time.

/// If the element not visible on the page.

        protected bool IsThinkingIndicatorLoading(int timeOut = -1)
        {
            //If element not present then webdriver throw the exception,
            //catch this exception so that outer code does not worry
            //about this exception and existing logic which relies on TRUE/FALSE can work as it is.
            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();
            if (timeOut == -1)
            {
                timeOut = this.waitTimeOut;
            }
            bool isThinkingIndicatorProcessing = false;
            try
            {
                while (stopWatch.Elapsed.TotalSeconds < timeOut)
                {
                    isThinkingIndicatorProcessing = WebDriver.FindElement(By.XPath
                        ("//img[contains(@src,'/IMG/ThinkingIndicator/process.gif')]")).Displayed;
                }
            }
            catch (Exception)
            {
                stopWatch.Stop();
                return false;
            }
            stopWatch.Stop();
            return isThinkingIndicatorProcessing;
        }

WebDriver Wait Till Page Successfully Switched To Another Page !

Sometimes, Due to Build slowness we are not able to switch to another page successfully. The WebDriver throws exception either we are doing the correct thing. So, we need to wait for particular time to page get switched successfully and we needverify it through page title.

///
/// Waits for page switched to another page successfully.
///

/// The expected title, which must be an exact match.
/// This is the time to wait for HTML element to appear on the page.
/// If the element not able to find in the specified time.

/// True when the title matches, false otherwise throws the exception.

/// An expectation for checking the title of a page.

protected bool WaitForPageGetSwitched(string expectedPageTitle, int timeOut = -1)
{
if (timeOut == -1)
{
timeOut = this.waitTimeOut;
}
var wait = new WebDriverWait(WebDriver, TimeSpan.FromSeconds(timeOut));
wait.Until(ExpectedConditions.TitleIs(expectedPageTitle));
return true;
}

Refresh Iframe Using WebDriver !

Webdriver has a method to refresh current page void refresh() but if page contains multiple IFrame's and we need to refresh IFrame only not whole page then use the under given method to refresh the IFrame through Java Script Executor-

///
/// Refresh the current selected iframe.
///
/// This is name of the Iframe.
/// Executes JavaScript in the context of the currently  selected frame or  window.
/// The script fragment provided will be executed as the body of an anonymous function.

/// Indicates that a driver can execute JavaScript, providing
/// access to the mechanism to do so.

protected void RefreshIFrameByJavaScriptExecutor(string iFrameName)
{
          ((IJavaScriptExecutor)WebDriver).ExecuteScript(string.Format("document.getElementById('{0}').src = " + "document.getElementById('{0}').src", iFrameName));
}