Powered By Blogger

Search Here!

Monday, February 25, 2013

Handle 'HTML text editor' in selenium RC and WebDriver

We could not directly insert text in the HTML editor. To automate the HTML editor we need to first click on the Show view source image button in the Editor tool box and then we can able to insert text in HTML editor text area.


WebDriver.FindElement(By.Id("viewsource")).Click();

WebDriver.FindElement(By.Id("txtHTMLEditor_textarea")).SendKeys("This is my Text!");



Friday, February 22, 2013

How to run same script on FF/IE/Chrome in Webdriver

Setting the Browser key in the app.config, we can execute the same script in the different browser(s).
        
         ///
        /// Returns an instance of the web driver based on test browser.
        ///

        /// The browser driver.

        public static IWebDriver GetInstance()
        {
            string browserName = ConfigurationManager.AppSettings["Browser"];
            IWebDriver webDriver = null;
            switch (browserName)
            {
                case Internet_Explorer: webDriver = IEWebDriver(); break;
                case FireFox: webDriver = FireFoxWebDriver(); break;
                case Safari: webDriver = SafariWebDriver(); break;
                case Chrome: webDriver = ChromeWebDriver(); break;
                default: throw new ArgumentException("The suggested browser was not found");
            }
            return webDriver;
        }

         ///
        /// Returns an instance of IE based driver.
        ///

        /// IE based driver.

        private static IWebDriver IEWebDriver()
        {
            IWebDriver webDriver = new InternetExplorerDriver(ieDriverPath, options, TimeSpan.FromMinutes(20));            webDriver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(timeOut));
            //Set The Cursor Position Center of the Screen
            Cursor.Position = new Point(Screen.PrimaryScreen.Bounds.Width / 2, Screen.PrimaryScreen.Bounds.Height / 2);
            return webDriver;
        }

        ///
        /// Returns an instance of Firefox based driver.
        ///

        /// FireFox based driver.

        private static IWebDriver FireFoxWebDriver()
        {
            IWebDriver webDriver = new FirefoxDriver();            webDriver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(timeOut));
            //Set The Cursor Position Center of the Screen
            Cursor.Position = new Point(Screen.PrimaryScreen.Bounds.Width / 2, Screen.PrimaryScreen.Bounds.Height / 2);
            return webDriver;
        }

        ///
        /// Returns an instance of Safari based driver.
        ///

        /// Safari based driver

        private static IWebDriver SafariWebDriver()
        {
            IWebDriver webDriver = new SafariDriver();            webDriver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(timeOut));
            return webDriver;
        }

        ///
        /// Returns an instance of Chrome based driver.
        ///

        /// Chrome based driver.

        private static IWebDriver ChromeWebDriver()
        {
            IWebDriver webDriver = new ChromeDriver(
                (Path.GetDirectoryName(
                System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
                + "\\..\\..\\..\\..\\ExternalAssemblies").Replace("file:\\", ""));
            return webDriver;
        }
    }

Add browser key in the app.config -
<add key="Browser" value="Internet Explorer" />

WebDriver: Refresh IFrame on the Page

Refresh the IFrame not the whole page. Pass the IFrame name in the method.

        ///
        /// Refresh the current selected iframe.
        ///

        /// This is the 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));
        } 

Saturday, February 16, 2013

Webdriver wait for window get loads and then select window

Wait for window get loads and then select the window.

///
/// Wait for window till it gets load on the page.
///

/// The name of the window.
/// This is time to wait.
/// if the window not loads in the specified interval of time.

/// If the window not exists on the page.

        protected void WaitUntilWindowLoads(string windowName, int timeOut = -1)
        {
            // Intialization of bool 'isWindowPresent' for checking window present
            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();
            if (timeOut == -1)
            {
                timeOut = this.waitTimeOut;
            }
            while (stopWatch.Elapsed.TotalSeconds < timeOut)
            {
                try
                {
                    //Wait for window
                    if (WaitUntilWindow(windowName) == true) break;
                }
                catch (Exception)
                {
                    // For Any exceptions catch value is assinged false
                }
            }
        }
  
///

/// Is Window Opened In the Specified Interval of Time or not.
///

/// This is the name of the window.
/// This is the time to wait for window get open.
/// True if the window is opened otherwise false.

/// If the window not able to find in the specified time.

/// If the window not exists on the page.

        protected bool WaitUntilWindow(string windowName, int timeOut = -1)
        {
            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();
            if (timeOut == -1)
            {
                timeOut = this.waitTimeOut;
            }
            while (stopWatch.Elapsed.TotalSeconds < timeOut)
            {
                if (WebDriver.WindowHandles.Any(item => WebDriver.SwitchTo().Window(item).Title == windowName))
                {
                    return true;
                }
            }
            stopWatch.Stop();
            return false;
        }

Webdriver Handling IEdriver.exe path of 32/64 bit machine !

Webdriver handling IEdriver.exe for 32 Bit and 64 bit machine. Now, we don’t need to bother to change every time the path for IEdriver.exe for 32/64 bit machine. Just add the below code and keep both IEdriver.exe file in a folder and it would automatically choose according to machine configuration.

String processorArchitecture = Microsoft.Win32.Registry.GetValue(
                "HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\Environment"
                , "PROCESSOR_ARCHITECTURE", null).ToString();

            string ieDriverPath =
                (Path.GetDirectoryName(
                System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
                + "\\..\\..\\..\\..\\ExternalAssemblies\\" + ((processorArchitecture == "x86") ? "x86" : "x64")).Replace("file:\\", "");

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));
}