Friday, 23 August 2019

Automation Selenium Take a Screen Shot

 public void TakeScreenshot(string fileName, string screenshotPath = null, IWebDriver driver = null)
        {
            Screenshot s = ((ITakesScreenshot)driver).GetScreenshot();//driver = new ChromeDriver();
            var path = @"C:\Ashutosh";

            if (!string.IsNullOrEmpty(screenshotPath))
            {
                path = screenshotPath;
            }

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            s.SaveAsFile(Path.Combine(screenshotPath, fileName + DateTime.Now.ToString("MM-dd-yyyy-HHmmss")), ScreenshotImageFormat.Png);
        }

Wednesday, 14 August 2019

Automation Selenium

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;

namespace AshuPractice
{
    [TestClass]
    public class FirstTestClass
    {
        IWebDriver driver;

        [TestMethod]
        public void ChromeMethod()
        {
            string actualResult;
            string expectedResult = "Google";
            driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://google.co.in/");
            driver.Manage().Window.Maximize();
            actualResult = driver.Title;
            if (actualResult.Contains(expectedResult))
            {
                Debug.WriteLine("Test Case Passed");
                Assert.IsTrue(true, "Test Case Passed");
            }
            else
            {
                Debug.WriteLine("Test Case Failed");
            }
            Thread.Sleep(2000);
            driver.Close();
            driver.Quit();
        }
        [TestMethod]
        public void WikiSearch()
        {
            driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.wikipedia.org/");
            driver.Manage().Window.Maximize();
            driver.FindElement(By.XPath("//*[@id='searchInput']")).SendKeys("selenuim");
            driver.FindElement(By.XPath("//*[@id='search-form']/fieldset/button/i")).Click();
            Thread.Sleep(2000);
            driver.Close();
            driver.Quit();
        }
        [TestMethod]
        public void ReadOnlyCollection()
        {
            driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.wikipedia.org/");
            driver.Manage().Window.Maximize();

            //ReadOnlyCollection<IWebElement> anchorLists = driver.FindElements(By.TagName("a"));
            IList<IWebElement> anchorLists = driver.FindElements(By.TagName("a"));
            foreach (var item in anchorLists)
            {
                if (item.Text != "")
                    if (item.Text.Contains("English"))
                    {
                        item.Click();
                        break;
                    }
            }

            Thread.Sleep(2000);
            driver.Close();
            driver.Quit();
        }
        [TestMethod]
        public void GetDropDownValue()
        {
            driver = new ChromeDriver();
            driver.Navigate().GoToUrl("https://www.wikipedia.org/");
            driver.Manage().Window.Maximize();

            IList<IWebElement> languages = new List<IWebElement>();
            languages = (driver.FindElement(By.XPath("//*[@id='searchLanguage']"))).FindElements(By.TagName("option"));
            foreach (var language in languages)
            {
                if (language.Text == "Dansk")
                {
                    SelectElement selectElement = new SelectElement(driver.FindElement(By.XPath("//*[@id='searchLanguage']")));
                    selectElement.SelectByText(language.Text);
                    break;
                }
            }
            Thread.Sleep(2000);
            driver.Close();
            driver.Quit();
        }
        [TestMethod]
        public void TwitterLogin()
        {

        }
    }   
}

Thursday, 8 August 2019

Automation selenium Scrolling and upload file

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.UI;


namespace AshuPractice
{

    [TestClass]
    public class UnitTest1
    {

        IWebDriver driver1;
        [TestMethod]
        public void TestMethod1()
        {

            // Open the browser for Automation
            IWebDriver driver = new ChromeDriver();

            driver.Manage().Window.Maximize();

            // WebPage which contains a WebTable
            driver.Navigate().GoToUrl("https://www.toolsqa.com/automation-practice-form/?firstname=&lastname=&sex=Male&exp=1&photo=&continents=Asia&submit=");
            //driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(30));
            //driver.Manage().Timeouts().
            Thread.Sleep(5000);

            // Below code is for scrolling
            var element = driver.FindElement(By.XPath("//*[@id='content']/div[1]/div/div/div/div[2]/div/form/fieldset/div[29]"));
            Actions actions = new Actions(driver);
            actions.MoveToElement(element);
            actions.Perform();         

            //Below code is for uploading
            (driver.FindElement(By.XPath("//*[@id='photo']"))).Click();
            Thread.Sleep(5000);
            SendKeys.SendWait("C:\\Users\\asamantr\\OneDrive - Itron\\Desktop\\New folder\\New Text Document.txt");
            SendKeys.SendWait(@"{Enter}"); //NameSpace using System.Windows.Forms         

            Thread.Sleep(5000);
            driver.Quit();
        }
    }
}

Monday, 5 August 2019

Automation Selenium Control Actions

using Itron.FDM.SQA.VSAutomation.Framework.Reporting;
using OpenQA.Selenium;
using OpenQA.Selenium.Appium.Windows;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Support.UI;
using System;
using System.Threading;

namespace Itron.FDM.SQA.VSAutomation.Framework.SeleniumUtilities
{
    public class ControlActions
    {
        private static ExtentReporter TestReport = SessionFactory.GetReport();

        public static bool IsElementExists(IWebElement element)
        {
            bool exists = false;

            try
            {
                exists = element.Displayed;
                return exists;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// <param name="element"></param>
        /// <param name="intervalToWaitInMilliSecs"></param>
        /// <param name="loopCount - The total wait time will be loopcount * intervalToWaitInMilliSecs"></param>
        /// <returns></returns>
        /// </summary>
        public static bool IsElementExistsWithWait(IWebElement element, int loopCount = 20, int intervalToWaitInMilliSecs = 500)
        {
            int attempt = 0;
            bool exists = false;

            if (element != null)
            {
                do
                {
                    try
                    {
                        exists = element.Displayed;

                        if (exists)
                        {
                            break;
                        }
                        else
                        {
                            attempt++;
                            Thread.Sleep(intervalToWaitInMilliSecs);
                        }
                    }
                    catch (Exception ex)
                    {
                        var s = ex.Message;
                        attempt++;
                        Thread.Sleep(intervalToWaitInMilliSecs);
                    }
                }
                while (attempt < loopCount);
            }

            return exists;
        }

        /// <summary>
        /// <param name="element"></param>
        /// <param name="intervalToWaitInMilliSecs"></param>
        /// <param name="loopCount - The total wait time will be loopcount * intervalToWaitInMilliSecs"></param>
        /// <returns></returns>
        /// </summary>
        public static bool WaitForElementNotExists(IWebElement element, int loopCount = 20, int intervalToWaitInMilliSecs = 500)
        {
            int attempt = 0;
            bool exists = true;

            if (element != null)
            {
                do
                {
                    try
                    {
                        exists = element.Displayed;

                        if (!exists)
                        {
                            break;
                        }
                        else
                        {
                            attempt++;
                            Thread.Sleep(intervalToWaitInMilliSecs);
                        }
                    }
                    catch (Exception ex)
                    {
                        var s = ex.Message;
                        attempt++;
                        Thread.Sleep(intervalToWaitInMilliSecs);
                    }
                }
                while (attempt < loopCount);
            }

            return exists;
        }

        /// <summary>
        /// Waits for the element to be enabled
        /// </summary>
        /// <param name="element"></param>
        /// <param name="maxTimeoutInSeconds"></param>
        public static void WaitForElementEnabled(WindowsDriver<IWebElement> session, IWebElement element, int loopCount = 1, int maxTimeIntervalInSeconds = 30)
        {
            int attempt = 0;
            bool t = false;

            if (element != null)
            {
                do
                {
                    try
                    {
                        var wait = new DefaultWait<WindowsDriver<IWebElement>>(session)
                        {
                            Timeout = TimeSpan.FromSeconds(maxTimeIntervalInSeconds),
                            PollingInterval = TimeSpan.FromSeconds(2)
                        };
                        wait.IgnoreExceptionTypes(typeof(InvalidOperationException));
                        wait.IgnoreExceptionTypes(typeof(WebDriverTimeoutException));
                        wait.IgnoreExceptionTypes(typeof(WebDriverException));

                        wait.Until(driver =>
                        {
                            t = element.Enabled;
                            return t != false;
                        });

                        if (t)
                        {
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        var s = ex.Message;
                        attempt++;
                    }
                }
                while (attempt < loopCount);
            }
        }

        public static void Click(IWebElement element, int loopCount = 20, int intervalToWaitMillSecs = 500)
        {
            try
            {
                IsElementExistsWithWait(element, loopCount, intervalToWaitMillSecs);
                TestReport.LogSuccess(string.Format("{0}{1}", "Click element ", element.GetAttribute("Name")));
                element.Click();
            }
            catch (Exception ex)
            {
                TestReport.LogFailure(string.Format("{0}{1}", "Failed Clicking element ", ex.Message));
            }
        }

        public static void Clear(IWebElement element, int loopCount = 20, int intervalToWaitMillSecs = 500)
        {
            try
            {
                IsElementExistsWithWait(element, loopCount, intervalToWaitMillSecs);
                TestReport.LogSuccess(string.Format("{0}{1}", "Clearing contents of element ", element.GetAttribute("Name")));
                element.Clear();
            }
            catch (Exception ex)
            {
                TestReport.LogFailure(string.Format("{0}{1}", "Failed Clearing contents of element ", ex.Message));
            }
        }

        public static void SendKeyBoardPressKey(WindowsDriver<IWebElement> session, string key)
        {
            try
            {
                TestReport.LogSuccess("Entering value '" + key + "' through keyboard ");
                GetActionsInstance(session).SendKeys(key);
            }
            catch (Exception ex)
            {
                TestReport.LogFailure(string.Format("{0}{1}", "Failed entering value through keyboard", ex.Message));
            }
        }

        public static void SelectAllKeyboard(WindowsDriver<IWebElement> session)
        {
            try
            {
                TestReport.LogSuccess("Performing Select All operation");
                GetActionsInstance(session).SendKeys(Keys.Control + "a" + Keys.Control);
            }
            catch (Exception ex)
            {
                TestReport.LogFailure(string.Format("{0}{1}", "Failed performing Select All operation", ex.Message));
            }
        }

        public static void SendKeysToElement(IWebElement element, string textToEnter, int loopCount = 20, int intervalToWaitMillSecs = 500)
        {
            try
            {
                IsElementExistsWithWait(element, loopCount, intervalToWaitMillSecs);
                TestReport.LogSuccess(string.Format("{0},{1}", "Entering value '" + textToEnter + "' to element ", element.GetAttribute("Name")));
                element.SendKeys(textToEnter);
            }
            catch (Exception ex)
            {
                TestReport.LogFailure(string.Format("{0},{1}", "Failed entering value to element ", ex.Message));
            }
        }

        public static void SendKeysToElementClearFirst(IWebElement element, string textToEnter, int loopCount = 20, int intervalToWaitMillSecs = 500)
        {
            try
            {
                IsElementExistsWithWait(element, loopCount, intervalToWaitMillSecs);
                TestReport.LogSuccess(string.Format("{0},{1}", "Clearing and Entering value '" + textToEnter + "' to element ", element.GetAttribute("Name")));
                element.Clear();
                element.SendKeys(textToEnter);
            }
            catch (Exception ex)
            {
                TestReport.LogFailure(string.Format("{0},{1}", "Failed clearing and entering value to element ", ex.Message));
            }
        }

        public static void ClickByMoveByOffset(WindowsDriver<IWebElement> driver, int x, int y)
        {
            try
            {
                TestReport.LogSuccess("Performing click moving by offset using coordinates " + x + " , " + y + "");
                GetActionsInstance(driver).MoveByOffset(x, y).Click().Build().Perform();
            }
            catch (Exception ex)
            {
                TestReport.LogFailure(string.Format("{0}{1}", "Performing click moving by offset using coordinates", ex.Message));
            }
        }

        public static void MovetoElement(WindowsDriver<IWebElement> driver, IWebElement element, int loopCount = 20, int intervalToWaitMillSecs = 500)
        {
            try
            {
                IsElementExistsWithWait(element, loopCount, intervalToWaitMillSecs);
                TestReport.LogSuccess(string.Format("{0}{1}", "Moving the cursor to the element ", element.GetAttribute("Name")));
                GetActionsInstance(driver).MoveToElement(element).Build().Perform();
            }
            catch (Exception ex)
            {
                TestReport.LogFailure(string.Format("{0}{1}", "Failed moving the cursor to the element", ex.Message));
            }
        }

        public static void MovetoElement(WindowsDriver<IWebElement> driver, IWebElement element, int x, int y, int loopCount = 20,
            int intervalToWaitMillSecs = 500)
        {
            try
            {
                IsElementExistsWithWait(element, loopCount, intervalToWaitMillSecs);
                TestReport.LogSuccess(string.Format("{0}{1}{2}", "Moving the cursor to the element '" + element.GetAttribute("Name") + "' using coordinates", x, y));
                GetActionsInstance(driver).MoveToElement(element, x, y).Build().Perform();
            }
            catch (Exception ex)
            {
                TestReport.LogFailure(string.Format("{0}{1}", "Failed moving the cursor to the element using coordinates", ex.Message));
            }
        }

        public static void ClickByMovetoElement(WindowsDriver<IWebElement> driver, IWebElement element, int x, int y, int loopCount = 20,
            int intervalToWaitMillSecs = 500)
        {
            try
            {
                IsElementExistsWithWait(element, loopCount, intervalToWaitMillSecs);
                TestReport.LogSuccess(string.Format("{0}{1}{2}", "performing click by moving the cursor to the element '" + element.GetAttribute("Name") + "' using coordinates", x, y));
                GetActionsInstance(driver).MoveToElement(element, x, y).Click().Build().Perform();
            }
            catch (Exception ex)
            {
                TestReport.LogFailure(string.Format("{0}{1}", "Failed performing click by moving the cursor to the element using coordinates", ex.Message));
            }
        }

        public static void ClickByMovetoElement(WindowsDriver<IWebElement> driver, IWebElement element, int loopCount = 20,
            int intervalToWaitMillSecs = 500)
        {
            try
            {
                IsElementExistsWithWait(element, loopCount, intervalToWaitMillSecs);
                TestReport.LogSuccess("performing click by moving the cursor to the element '" + element.GetAttribute("Name") + "'");
                GetActionsInstance(driver).MoveToElement(element).Click().Build().Perform();
            }
            catch (Exception ex)
            {
                TestReport.LogFailure(string.Format("{0}{1}", "Failed performing click by moving the cursor to the element '" + element.GetAttribute("Name") + "'", ex.Message));
            }
        }

        public static void SelectCheckBox(IWebElement element, int loopCount = 20, int intervalToWaitMillSecs = 500)
        {
            try
            {
                IsElementExistsWithWait(element, loopCount, intervalToWaitMillSecs);
                TestReport.LogSuccess("Selecting checkbox '" + element.GetAttribute("Name") + "'");
                if (!(element.Selected))
                    element.Click();
            }
            catch (Exception ex)
            {
                TestReport.LogFailure(string.Format("{0}{1}", "Failed selecting checkbox '" + element.GetAttribute("Name") + "'", ex.Message));
            }
        }

        public static void UnSelectCheckBox(IWebElement element, int loopCount = 20, int intervalToWaitMillSecs = 500)
        {
            try
            {
                IsElementExistsWithWait(element, loopCount, intervalToWaitMillSecs);
                TestReport.LogSuccess("UnSelecting checkbox '" + element.GetAttribute("Name") + "'");
                if (element.Selected)
                    element.Click();
            }
            catch (Exception ex)
            {
                TestReport.LogFailure(string.Format("{0}{1}", "Failed Unselecting checkbox '" + element.GetAttribute("Name") + "'", ex.Message));
            }
        }

        public static bool IsEnabled(IWebElement element, int loopCount = 20, int intervalToWaitMillSecs = 500)
        {
            bool status = false;
            try
            {
                IsElementExistsWithWait(element, loopCount, intervalToWaitMillSecs);
                TestReport.LogSuccess("Enabled status for '" + element.GetAttribute("Name") + "'");
                status = element.Enabled;
            }

            catch (Exception ex)
            {
                TestReport.LogFailure(string.Format("{0}{1}", "Failed to find element '" + element.GetAttribute("Name") + "'", ex.Message));
            }

            return status;
        }

        public static bool IsSelected(IWebElement element, int loopCount = 20, int intervalToWaitMillSecs = 500)
        {
            bool status = false;
            try
            {
                IsElementExistsWithWait(element, loopCount, intervalToWaitMillSecs);
                TestReport.LogSuccess("Selected status for '" + element.GetAttribute("Name") + "'");
                status = element.Selected;
            }

            catch (Exception ex)
            {
                TestReport.LogFailure(string.Format("{0}{1}", "Failed to find element '" + element.GetAttribute("Name") + "'", ex.Message));
            }

            return status;
        }

        public static void SelectValueInCombobox(IWebElement element, IWebElement elementToSelect, int loopCount = 20, int intervalToWaitMillSecs = 500)
        {
            try
            {
                IsElementExistsWithWait(element, loopCount, intervalToWaitMillSecs);
                TestReport.LogSuccess(string.Format("{0}{1}", "Selecting value ", elementToSelect.GetAttribute("Name"), element.GetAttribute("Name")));
                element.Click();
                elementToSelect.Click();
            }

            catch (Exception ex)
            {
                TestReport.LogSuccess(string.Format("{0}{1}{2}", "Failed selecting value ", elementToSelect.GetAttribute("Name"), element.GetAttribute("Name"), ex.Message));
            }
        }

        public static void ClickByActions(WindowsDriver<IWebElement> driver, IWebElement element, int loopCount = 20, int intervalToWaitMillSecs = 500)
        {
            try
            {
                IsElementExistsWithWait(element, loopCount, intervalToWaitMillSecs);
                TestReport.LogSuccess("Click element " + element.GetAttribute("Name") + " using action builder");
                GetActionsInstance(driver).Click(element).Build().Perform();
            }
            catch (Exception ex)
            {
                TestReport.LogFailure(string.Format("{0}{1}", "Failed to click element using action builder", ex.Message));
            }
        }

        public static void ClickByActions(WindowsDriver<IWebElement> driver)
        {
            try
            {
                TestReport.LogSuccess("perform click using action builder");
                GetActionsInstance(driver).Click().Build().Perform();
            }
            catch (Exception ex)
            {
                TestReport.LogFailure(string.Format("{0}{1}", "Failed to perform click using action builder", ex.Message));
            }
        }

        public static void DoubleClick(WindowsDriver<IWebElement> driver, IWebElement element, int loopCount = 20, int intervalToWaitMillSecs = 500)
        {
            try
            {
                IsElementExistsWithWait(element, loopCount, intervalToWaitMillSecs);
                TestReport.LogSuccess("Double Click element " + element.GetAttribute("Name") + "");
                GetActionsInstance(driver).DoubleClick(element).Build().Perform();
            }
            catch (Exception ex)
            {
                TestReport.LogFailure(string.Format("{0}{1}", "Failed to double click element", ex.Message));
            }
        }

        public static void RightClick(WindowsDriver<IWebElement> driver, IWebElement element, int loopCount = 20, int intervalToWaitMillSecs = 500)
        {
            try
            {
                IsElementExistsWithWait(element, loopCount, intervalToWaitMillSecs);
                TestReport.LogSuccess("Right Click element " + element.GetAttribute("Name") + "");
                GetActionsInstance(driver).ContextClick(element).Build().Perform();
            }
            catch (Exception ex)
            {
                TestReport.LogFailure(string.Format("{0}{1}", "Failed to right click element", ex.Message));
            }
        }

        private static Actions GetActionsInstance(WindowsDriver<IWebElement> driver) { return new Actions(driver); }
    }
}