コード例 #1
0
ファイル: ScraperEx.cs プロジェクト: dt-bet/Scrape.Utility
        ////public static bool IsStale(this IWebDriver webDriver, IWebElement webElement)
        ////{
        ////    return ExpectedConditions.StalenessOf(webElement)(webDriver);
        ////}



        public static System.Collections.ObjectModel.ReadOnlyCollection <IWebElement> WaitForElements(this IWebDriver driver, string css, int time = 120)
        {
            OpenQA.Selenium.Support.UI.WebDriverWait wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(time));

            System.Collections.ObjectModel.ReadOnlyCollection <IWebElement> pagelinks = null;
            try
            {
                pagelinks = wait.Until((d) =>
                {
                    return(d.FindElements(By.CssSelector(css)));
                });
            }
            catch
            {
                int cnt = 0;
                while (pagelinks == null & cnt < 10)
                {
                    pagelinks = driver.FindElements(By.CssSelector(css));
                    Thread.Sleep(1000);
                    cnt++;
                }
            }

            return(pagelinks);
        }
コード例 #2
0
        private void PageScrolDown(int offset = 1300, bool applyRandomwait = true)
        {
            //wait for loading new emps
            if (applyRandomwait)
            {
                ri = r.Next(_settings.ScrollMinWait, _settings.ScrollMaxWait);
                Thread.Sleep(ri * 100);
            }

            //scroll down to load the employees
            IJavaScriptExecutor jse = (IJavaScriptExecutor)_driver;

            jse.ExecuteScript($"window.scrollBy(0,{offset})", "");

            //wait for loading new emps
            if (applyRandomwait)
            {
                ri = r.Next(_settings.ScrollMinWait, _settings.ScrollMaxWait);
                Logger.Debug($"Sleeping for {ri * 500} milliseconds for Ajax requests");
                Thread.Sleep(ri * 500);
            }

            IWait <IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(_driver, TimeSpan.FromSeconds(15.00));

            wait.Until(wd => ((IJavaScriptExecutor)_driver).ExecuteScript("return document.readyState").ToString() == "complete");
        }
コード例 #3
0
 public SolicitarMigracao(IWebDriver _navegador)
 {
     navegador          = _navegador;
     filiadosParaMigrar = new FiliadosParaMigrar();
     wait  = new SupportUI.WebDriverWait(_navegador, TimeSpan.FromSeconds(60));
     _base = new Base(_navegador);
 }
コード例 #4
0
ファイル: UIObjects.cs プロジェクト: karthik-kt/SWAT-Main
        internal bool WaitUntilLoading()
        {
            By     byLoading = By.ClassName("busy");
            string message   = null;

            try
            {
                if (driver.FindElement(byLoading).Displayed)
                {
                    do
                    {
                        message = driver.FindElement(byLoading).Text.ToUpper();
                        var wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));
                        wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
                        if (message == "AN ERROR HAS OCCURRED")
                        {
                            MyLogger.Log("<<AN ERROR HAS OCCURRED>> message displayed.");
                            return(false);
                        }
                        Thread.Sleep(10);
                    }while (message == "LOADING...");
                }
                return(true);
            }
            catch
            {
                return(true);
            }
        }
コード例 #5
0
ファイル: Browser.cs プロジェクト: TriveniGh/TestFolder
        public static void WaitforthePageLoad()
        {
            try
            {
                // driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(Constants.WaitforthePageLoad));

                IWait <IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(Constants.WaitforthePageLoad));



                wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
            }
            catch (Exception e)
            {
                Logger.error("Failed to load the Page", e);
                Test.Result("Page should be loaded", "Failed to Load the page", "Failed");
            }
            finally
            {
                Logger.info("  loading  the page" + "*--*--*--*");
                if (driver.Url.ToLower().Contains("error"))
                {
                    Test.Result("Logout should be successful", "Un expected error while performing logout", "Failed");
                    Test.TakeScreenShot();
                }
                // Logger.info("In" + PageName + "*-_-*-_-*-_-*" + ObjectName);
            }
        }
コード例 #6
0
ファイル: ClickExtensions.cs プロジェクト: shoter/WebUtils
        public static void TryClick(this IWebDriver driver, By by)
        {
            var element             = driver.FindElement(by);
            IWait <IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(5.00));

            wait.Until(driver1 => driver.tryClick(by));
        }
コード例 #7
0
        public void SearchStudent(string People)
        {
            var wait = new OpenQA.Selenium.Support.UI.WebDriverWait(PropertiesCollection.driver, TimeSpan.FromSeconds(60));

            System.Threading.Thread.Sleep(60000);
            PropertiesCollection.driver.SwitchTo().Frame("myFrame");
            System.Threading.Thread.Sleep(2000);

            wait.Until(ExpectedConditions.ElementToBeClickable(btnPeopleSelector));
            btnPeopleSelector.Click();
            System.Threading.Thread.Sleep(2000);
            wait.Until(ExpectedConditions.ElementToBeClickable(txtPeopleSelector));
            txtPeopleSelector.Click();

            txtPeopleSelector.SendKeys(People);
            wait.Until(ExpectedConditions.ElementToBeClickable(btnPeopleSearch));

            btnPeopleSearch.Click();
            System.Threading.Thread.Sleep(5000);

            firstgrdPeopleSelector.Click();

            wait.Until(ExpectedConditions.ElementToBeClickable(btnApply));
            btnApply.Click();
        }
コード例 #8
0
        public void WaitTillPageIsLoaded()
        {
            IWait <IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(webDriver, TimeSpan.FromSeconds(60.00));

            wait.Until(
                driver => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
        }
コード例 #9
0
ファイル: Methods.cs プロジェクト: Apocalipsian/TestAB
        public string click(IWebDriver driver, List <filtry.unactiveFilters> lists, int number)
        {
            string filterName;

            IWait <IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));

            if (number >= 0)
            {
                filterName = lists[number].textFilter.Text;
                lists[number].textFilter.Click();
                return(filterName);
            }
            else
            {
                number = rand.Next(0, lists.Count - 1);

                filterName = lists[number].textFilter.Text;

                ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", lists[number].textFilter);
                driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(2));
                try
                {
                    lists[number].textFilter.Click();
                    wait.Until(ExpectedConditions.StalenessOf(lists[number].textFilter));
                    driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(2));
                }
                catch
                {
                    MessageBox.Show("Nie udało się kliknąć filtru");
                }
                return(filterName);
            }
        }
コード例 #10
0
        private void SearchResultPageScrollDown()
        {
            ri = r.Next(_settings.ScrollMinWait, _settings.ScrollMaxWait);
            Logger.Debug($"Sleeping for {ri * 500} milliseconds for Ajax requests");
            Thread.Sleep(ri * 500);

            Logger.Debug("Scrolling down page...");

            IJavaScriptExecutor jse = (IJavaScriptExecutor)_driver;

            jse.ExecuteScript($"window.scrollBy(0,600)", "");


            jse.ExecuteScript($"window.scrollBy(0,600)", "");

            ri = r.Next(_settings.ScrollMinWait, _settings.ScrollMaxWait);
            Logger.Debug($"Sleeping for {ri * 500} milliseconds for Ajax requests");
            Thread.Sleep(ri * 500);

            jse.ExecuteScript($"window.scrollBy(0,600)", "");

            ri = r.Next(_settings.ScrollMinWait, _settings.ScrollMaxWait);
            Logger.Debug($"Sleeping for {ri * 500} milliseconds for Ajax requests");
            Thread.Sleep(ri * 500);

            jse.ExecuteScript($"window.scrollBy(0,-700)", "");

            ri = r.Next(_settings.ScrollMinWait, _settings.ScrollMaxWait);
            Logger.Debug($"Sleeping for {ri * 500} milliseconds for Ajax requests");
            Thread.Sleep(ri * 500);

            IWait <IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(_driver, TimeSpan.FromSeconds(15.00));

            wait.Until(wd => ((IJavaScriptExecutor)_driver).ExecuteScript("return document.readyState").ToString() == "complete");
        }
コード例 #11
0
        public static void WaitForPageLoadNew(this IWebDriver webDriver, TimeSpan timeSpan)
        {
            Thread.Sleep(5000);
            IWait <IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(webDriver, timeSpan);

            wait.Until(driver1 => ((IJavaScriptExecutor)webDriver).ExecuteScript("return document.readyState").Equals("complete"));
        }
コード例 #12
0
        public void What_Is_Implicit_Wait_And_Explicit_Wait()
        {
            //Implicit wait- Asking the browser to wait for amount of time driver should wait while searching for an element if it is not present immediately
            //If the element is found beofre the time seciified the next step will be executed without waiting for remaining time mentioned in implicit wait.
            chromedriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);

            //Explicit Wait- Specific wait
            OpenQA.Selenium.Support.UI.WebDriverWait wait = new OpenQA.Selenium.Support.UI.WebDriverWait(chromedriver, TimeSpan.FromSeconds(10));
            wait.Message = "";                                       //Gets for sets the message to be displayed when time expires
            wait.IgnoreExceptionTypes();                             //Configures this instance to ignore the specific exceptions while waiting on the condition
            wait.PollingInterval = TimeSpan.FromMilliseconds(100);   //Gets or sets how often the condition should be evaluated. The deafult timeout is 500milliseond
            wait.Until(x => x.FindElements(By.XPath("")).Count > 1); //Condtion till the wait should be applied. Throws exception when timeout expires.
            //wait.Until(ExpectedConditions.)
            wait.Until(ExpectedConditions.AlertIsPresent());
            //An expectation for checking that an element is present on the DOM of a page
            //This does not necessarily mean that the element is visible.
            //// Returns:
            //     The OpenQA.Selenium.IWebElement once it is located.
            wait.Until(ExpectedConditions.ElementExists(By.Id("elem")));

            // Summary:
            //     An expectation for checking that an element is present on the DOM of a page and
            //     visible. Visibility means that the element is not only displayed but also has
            //     a height and width that is greater than 0.
            // Returns:
            //     The OpenQA.Selenium.IWebElement once it is located and visible.
            wait.Until(ExpectedConditions.ElementIsVisible(By.Id("elem")));

            wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("elem")));

            wait.Until(ExpectedConditions.TextToBePresentInElement(chromedriver.FindElement(By.Id("elem")), ""));
            // An expectation for checking the title of a page.
            wait.Until(ExpectedConditions.TitleIs(""));
            wait.Until(ExpectedConditions.UrlContains(""));
        }
コード例 #13
0
        /*    public IList<CCLISong> search(String term)
         *  {
         *      IList<CCLISong> list = new List<CCLISong>();
         *
         *      this.driver.Navigate().GoToUrl("https://olr.ccli.com/search/results?SearchTerm=" + Uri.EscapeUriString(term) + "&PageSize=100&AllowRedirect=False");
         *      this.wait();
         *      ICollection<IWebElement> elements = this.driver.FindElementById("searchResults").FindElements(By.TagName("td"));
         *
         *      foreach (var item in elements.Take(10))
         *      {
         *          var ViewSong = item.FindElement(By.ClassName("searchResultsSongSummary")).FindElement(By.ClassName("row"));
         *          var uuid = item.FindElement(By.ClassName("searchResultsSongSummary")).GetAttribute("id").Replace("song-", String.Empty);
         *          ViewSong.FindElement(By.TagName("a")).Click();
         *          this.wait();
         *          var dataModalId = ViewSong.FindElement(By.TagName("a")).GetAttribute("data-reveal-id");
         *          var detailsDiv = this.driver.FindElementById(dataModalId);
         *
         *          var title = detailsDiv.FindElement(By.TagName("h3")).Text;
         *          var ccliId = detailsDiv.FindElement(By.TagName("h4")).Text;
         *
         *          bool publicDomain = false;
         *          string unparsedAuthors = "";
         *          try
         *          {
         *              unparsedAuthors = detailsDiv.FindElements(By.ClassName("secondarySongAttributes"))[0].Text;
         *              publicDomain = detailsDiv.FindElements(By.ClassName("secondarySongAttributes"))[1].Text.Contains("Public Domain");
         *          }
         *          catch (Exception e)
         *          {
         *              // ignore
         *          }
         *
         *          detailsDiv.FindElement(By.ClassName("close-reveal-modal")).Click();
         *          this.wait();
         *
         *          var ReportSong = item.FindElement(By.ClassName("searchResultsSongSummary")).FindElement(By.ClassName("row"));
         *
         *          var song = new CCLISong(title, unparsedAuthors, ccliId, publicDomain);
         *          list.Add(song);
         *      }
         *      return list;
         *  }*/

        private void Wait()
        {
            IWait <OpenQA.Selenium.IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));

            wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
            System.Threading.Thread.Sleep(TimeSpan.FromSeconds(3));
        }
コード例 #14
0
        public static void WaitForPageLoad(this IWebDriver driver)
        {
            var wait =
                new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));

            wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
        }
コード例 #15
0
        public List <PlayableElement> GetVideos()
        {
            IWait <IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));

            wait.Until(drive => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
            IReadOnlyCollection <IWebElement> elList;

            videos = new List <PlayableElement>();

            elList = driver.FindElements(By.ClassName(YouTubeValues.YTMainVideoLockup));
            if (elList.Count != 0)
            {
                foreach (IWebElement el in elList)
                {
                    if (el.Displayed)
                    {
                        VideoElementsSafeguardMainPage(() => { ListVideoMainPage(el); }, el);
                    }
                }
            }
            else
            {
                elList = driver.FindElements(By.XPath(string.Format(YouTubeValues.LiContainsVideo)));
                foreach (IWebElement el in elList)
                {
                    if (el.Displayed)
                    {
                        VideoElementsSafeguardSuggestionBar(() => { ListVideoSuggestionBar(el); }, el);
                    }
                }
            }
            return(videos);
        }
コード例 #16
0
ファイル: Form1.cs プロジェクト: HenleyKuang/ExecuteJS
 void WaitForLoad(IWebDriver driver, int timeoutSec)
 {
     while (true)
     {
         Thread.Sleep(1000);
         try
         {
             if (driver.Url != previousUrl)
             {
                 IWait <IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(timeoutSec));
                 wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
                 previousUrl = driver.Url;
                 //MessageBox.Show("Loaded");
                 int index = 0;
                 foreach (string item in listScripts)
                 {
                     string currentAddress = removeProtocol(readControlText(listViewScripts, index));
                     //MessageBox.Show(driver.Url + "\n" + currentAddress);
                     if (getControlChecked(listViewScripts, index) && removeProtocol(driver.Url).StartsWith(currentAddress))
                     {
                         string jsCode = listScripts[index].ToString();
                         //MessageBox.Show("Executing script");
                         IJavaScriptExecutor js = driver as IJavaScriptExecutor;
                         js.ExecuteScript(jsCode);
                     }
                     index++;
                 }
                 //MessageBox.Show("DOne");
             }
         }
         catch (Exception ee) { }
     }
 }
コード例 #17
0
        /// <summary>
        /// Retries the wait for document loaded.
        /// </summary>
        private void _RetryWaitForDocumentLoaded()
        {
            IWebDriver         driver = Factory.Instance;
            IWait <IWebDriver> wait   = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(Browsers.DefaultTimeoutInSeconds));

            wait.Until(d => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
        }
 public WebDriverWaitHelper(IWebDriver webDriver, TimeOutConfig timeOutConfig)
 {
     _webDriver          = webDriver;
     _timeOutConfig      = timeOutConfig;
     _implicitWait       = WebDriverWait(timeOutConfig.ImplicitWait);
     _pagenavigationWait = WebDriverWait(timeOutConfig.PageNavigation);
 }
コード例 #19
0
        public Driver waitUntilPageLoaded()
        {
            IWait <IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));

            wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));

            return(this);
        }
コード例 #20
0
        /// <summary>
        /// Waits for element.
        /// </summary>
        /// <param name="elemId">Element identifier.</param>
        public void WaitForElement(string elemId)
        {
            IWebDriver driver = Factory.Instance;

            Console.WriteLine("WaitForElement id '{0}'", elemId);
            IWait <IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(Browsers.DefaultTimeoutInSeconds));

            wait.Until(d => d.FindElement(By.Id(elemId)));
        }
コード例 #21
0
        protected IWebElement WaitForElementByTime(By locator, int seconds)
        {
            WaitUntilPageReady();
            OpenQA.Selenium.Support.UI.WebDriverWait waitTime = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(seconds));
            waitTime.Until(ExpectedConditions.ElementExists(locator));
            IWebElement element = driver.FindElement(locator);

            waitTime.Until(ExpectedConditions.ElementToBeClickable(element));
            return(element);
        }
コード例 #22
0
        protected IWebElement WaitForElementByTime(By locator, TimeSpan time)
        {
            WaitUntilPageReady();
            OpenQA.Selenium.Support.UI.WebDriverWait waitTime = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, time);
            waitTime.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(locator));
            IWebElement element = driver.FindElement(locator);

            waitTime.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(element));
            return(element);
        }
コード例 #23
0
        // A dialog is identifable by the class of the div it lives in. It is uniquely identifiable by this class and the elements
        // of the title span
        public Dialog(string title)
        {
            sTitle = title;
            By byDialog = By.XPath("//div[@role='dialog']");
            By byTitle  = By.XPath("//span[@class='ui-dialog-title' and text()='" + title + "']");

            System.TimeSpan waitTime = new System.TimeSpan(0, 0, 60);
            OpenQA.Selenium.Support.UI.WebDriverWait wait = new OpenQA.Selenium.Support.UI.WebDriverWait(BrowserWindow.Instance.Driver, waitTime);
            dialog       = BrowserWindow.Instance.Driver.FindElement(byDialog);
            titleElement = dialog.FindElement(byTitle);
        }
コード例 #24
0
 public static void WaitForElementNotVisible(By locator)
 {
     try
     {
         var wait = new OpenQA.Selenium.Support.UI.WebDriverWait(Browser.GetDriver(), TimeSpan.FromMilliseconds(Convert.ToDouble(Configuration.GetTimeout())));
         wait.Until(driver1 => !visibility(locator));
     }
     catch (WebDriverTimeoutException)
     {
     }
 }
コード例 #25
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="we"></param>
 public QA.IWebElement WaitForElement(QA.By locator, int seconds)
 {
     UI.WebDriverWait _wait = new UI.WebDriverWait(wd, TimeSpan.FromSeconds(seconds));
     _wait.Until((d) => { return(SeleniumExtras.WaitHelpers.ExpectedConditions.PresenceOfAllElementsLocatedBy(locator)); });
     QA.IWebElement theElement = null;
     try
     {
         theElement = (QA.IWebElement)wd.FindElement(locator);
     }
     catch { }
     return(theElement);
 }
コード例 #26
0
ファイル: ScraperEx.cs プロジェクト: dt-bet/Scrape.Utility
        public static IWebElement WaitForElement(this IWebDriver driver, string css, int time = 120)
        {
            OpenQA.Selenium.Support.UI.WebDriverWait wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(time));

            var pagelinks = wait.Until((d) =>
            {
                return(d.FindElement(By.CssSelector(css)));
            });


            return(pagelinks);
        }
コード例 #27
0
    public void WaitOnWebPageLoad(double time)
    {
        try
        {
            IWait <IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(this, TimeSpan.FromSeconds(time));
            wait.Until(driver1 => ((IJavaScriptExecutor)this).ExecuteScript("return document.readyState").Equals("complete"));
        }

        catch (Exception ex)
        {
            tb.LogMe("GoToURL", ex);
        }
    }
コード例 #28
0
ファイル: Config.cs プロジェクト: vidyutron/UnifiedFramework
 public void TestIntialise()
 {
     #region Code Injection
     ClearBrowser();
     string ieServerFilePath = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName, "UnifiedTools", "IEWebDriver");
     driver = UnifiedWebControlConfig.IWebDriverConfig(ieServerFilePath);
     driver.Manage().Window.Maximize();
     driver.Manage().Cookies.DeleteAllCookies();
     wait                 = UnifiedWebControlConfig.ExplicitWaitConfig(driver, 60);
     unifiedReport        = Instance;
     unifiedLogCollection = new List <UnifiedTest>();
     WiniumDriver.WiniumInitiate();
     #endregion
 }
コード例 #29
0
ファイル: BrowserBase.cs プロジェクト: RodrigoINM/SOM
        public void PageLoad()
        {
            try
            {
                IWait <IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(Driver, TimeSpan.FromSeconds(30));

                wait.Until(driver1 => ((IJavaScriptExecutor)Driver).ExecuteScript("return document.readyState").Equals("complete"));
            }
            catch
            {
                RefreshPage();
            }
            #endregion
        }
コード例 #30
0
        public bool Click(string path)
        {
            //IWebElement element = _driver.FindElement(By.XPath(path));
            //do
            //{
            //    thread.sleep(300);
            //} while (!element.enabled && !element.displayed);
            IWait <IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(_driver, TimeSpan.FromSeconds(100));

            wait.Until(driver1 => driver1.FindElement(By.XPath(path)).Enabled&& driver1.FindElement(By.XPath(path)).Displayed);

            _driver.FindElement(By.XPath(path)).Click();
            CapturaImagem();
            return(true);
        }
コード例 #31
0
    protected void Button4_Click(object sender, EventArgs e)
    {
        // Response.Write(marker_place);
        List<string> lst_zipscodes = new List<string>();
        IGeocoder geocoder = new GoogleGeocoder() { };
        DataSet ds = new DataSet("Sites_Collection");
        string connection_string = ConfigurationManager.ConnectionStrings["UA_NAVConnectionString"].ConnectionString;
        SqlConnection conn = new SqlConnection(connection_string);

        WeatherReference.WeatherSoapClient weather = new WeatherReference.WeatherSoapClient("WeatherSoap");

        // my source starting placeplace

        for (int i = 0; i < marker_place.Count; i++)
        {
            string source = marker_place[i];
            string[] addr_string = source.Split(',');
            string[] zipcode = null;
            if (addr_string.Count() == 4)
            {
                zipcode = addr_string[2].Trim().Split(' ');
                source = addr_string[1] + "," + zipcode[0];
                lst_zipscodes.Add(zipcode[1]);
            }
            else
            {
                continue;
            }
            IWebDriver driver = null;
            try
            {
                driver = new FirefoxDriver();

                driver.Navigate().GoToUrl("http://www.nwf.org/naturefind.aspx");
                driver.Manage().Window.Maximize();

                var place_name = driver.FindElement(By.Id("content_0_txtBasicSearch"));
                place_name.Clear();
                place_name.SendKeys(source);
                driver.FindElement(By.Id("content_0_btnSearchSites")).Click();
                //driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));

                IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(15.00));
                // IWait<IWebDriver> wait = null;
                wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));

                DataTable dt = new DataTable("Places_" + i);

                DataColumn place_Coulumn = new DataColumn("Scenic_Place_Name", Type.GetType("System.String"));
                DataColumn lat_Coulumn = new DataColumn("Latitude", Type.GetType("System.String"));
                DataColumn lng_Coulumn = new DataColumn("Longitude", Type.GetType("System.String"));
                DataColumn address_of_place = new DataColumn("Address", Type.GetType("System.String"));
                DataColumn Zipscode = new DataColumn("Zipcode", Type.GetType("System.String"));
                DataColumn weather_desc = new DataColumn("Weather", Type.GetType("System.String"));
                DataColumn temperature = new DataColumn("Temperature", Type.GetType("System.String"));
                DataColumn traffic = new DataColumn("Traffic", Type.GetType("System.String"));
                DataColumn safety = new DataColumn("Safety", Type.GetType("System.String"));
                dt.Columns.Add(place_Coulumn);
                dt.Columns.Add(lat_Coulumn);
                dt.Columns.Add(lng_Coulumn);
                dt.Columns.Add(address_of_place);
                dt.Columns.Add(Zipscode);
                dt.Columns.Add(weather_desc);
                dt.Columns.Add(temperature);
                dt.Columns.Add(traffic);
                dt.Columns.Add(safety);

                DataRow dr;
                int count1 = 0;

                try
                {

                    wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//div[@id='content_0_grdSiteList']//tr[@class='rgRow']//u")));
                    wait.Until(ExpectedConditions.ElementExists(By.XPath("//div[@id='content_0_grdSiteList']//tr[@class='rgRow']//u")));
                    IList<IWebElement> lst_places = driver.FindElements(By.XPath(".//div[@id='content_0_grdSiteList']//tr[@class='rgRow']//u"));

                    if (lst_places == null)
                        continue;
                    int count = 0;
                    foreach (IWebElement place in lst_places)
                    {
                        //   if (count1!= -1)
                        //    {
                        try
                        {
                            dr = dt.NewRow();
                            Thread.Sleep(200);
                            dr["Scenic_Place_Name"] = place.Text;
                            IEnumerable<Address> addresses = geocoder.Geocode(place.Text + "," + zipcode[0]);
                            string place_addr = null;
                            Location ltng = null;

                            foreach (Address adr in addresses)
                            {
                                if (count == 0)
                                {
                                    place_addr = adr.FormattedAddress;
                                    ltng = adr.Coordinates;
                                    dr["Address"] = place_addr;
                                    break;
                                }
                            }

                            dr["Latitude"] = ltng.Latitude;
                            dr["Longitude"] = ltng.Longitude;

                            //tokenize place address

                            string[] array = place_addr.Split(',');
                            string[] waypoints = place_addr.Split(','); ///////*******************
                            string zip = array[array.Length - 2];
                            string[] arr = zip.Trim().Split(' ');
                            string webservicezip = null;
                            if (arr.Length == 1)
                            {
                                dr["Zipcode"] = zipcode[1];
                                webservicezip = zipcode[1];
                            }
                            else if (Regex.IsMatch(place_addr, @"\d"))
                            {
                                arr = zip.Trim().Split(' ');
                                dr["Zipcode"] = arr[1].Trim();
                                webservicezip = arr[1].Trim();
                            }

                            //weather update

                            WeatherReference.WeatherReturn weather_of_place = weather.GetCityWeatherByZIP(webservicezip);  //  arr[1].Trim()
                            dr["Weather"] = weather_of_place.Description;
                            dr["Temperature"] = weather_of_place.Temperature;

                            Random rnd = new Random();
                            dr["Traffic"] = rnd.Next(2, 5);
                            dr["Safety"] = rnd.Next(60, 100);
                            dt.Rows.Add(dr);
                            //break;
                        }

                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                            continue;
                        }
                    }

                }
                finally
                {

                    ds.Tables.Add(dt);
                }

            }

            finally
            {
                driver.Close();
                driver.Dispose();
            }
        }

        WriteDataToDATABASE(ds);
        string[] scenic_places = CreateListScenicPlaces();
        //    DrawScenicDirection();
        foreach (string s in scenic_places)
        {
            ClientScript.RegisterArrayDeclaration("scenic_places", "\"" + s + "\"");
        }

        ClientScript.RegisterStartupScript(Page.GetType(), "Scenic", "scenic_route();", true);
    }
コード例 #32
0
ファイル: Instance.cs プロジェクト: buonan/SeleniumTests
		/// <summary>
		/// Waits for element.
		/// </summary>
		/// <param name="elemId">Element identifier.</param>
		public void WaitForElement(string elemId)
		{
			IWebDriver driver = Factory.Instance;
            Console.WriteLine("WaitForElement id '{0}'", elemId);
			IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(Browsers.DefaultTimeoutInSeconds));
			wait.Until(d => d.FindElement(By.Id(elemId)));
		}
コード例 #33
0
ファイル: Browser.cs プロジェクト: Thinksys/krypton
        /// <summary>
        ///  Method to Method to verify page display by verifying page title.
        /// </summary>
        /// <param name="title">Title of web page</param>
        /// <returns>boolean value</returns>
        public bool VerifyPageDisplayed(Dictionary<int, string> keyWorddic)
        {
            try
            {
                bool isKeyVerified;
                string url = this.GetData(KryptonConstants.WHAT);
                if (!keyWorddic.Count.Equals(0))
                {
                    try
                    {
                        IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));
                        wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
                        Browser.switchToMostRecentBrowser();
                    }
                    catch { }
                    isKeyVerified = Common.Utility.doKeywordMatch(url, driver.Url);
                }
                else
                {
                    //By Default regular expression match would be done for Url entry in OR.
                    try
                    {
                        IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));
                        wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
                        Browser.switchToMostRecentBrowser();
                    }
                    catch { }
                    try
                    {
                        driver.SwitchTo().DefaultContent();
                    }
                    catch (Exception ed)
                    {
                        //do nothing
                    }
                    Regex regExp = new Regex(url.ToLower());
                    Match m = regExp.Match((driver.Url).ToLower());
                    isKeyVerified = m.Success;
                }

                if (!isKeyVerified)
                {
                    Common.Property.Remarks = "Page with URL: \"" + url + "\" is not displayed." +
                                              "Actual displayed page was: " + driver.Url;
                }

                return isKeyVerified;
            }
            catch (WebDriverException e)
            {
                if (e.Message.Contains(Common.exceptions.ERROR_NORESPONSEURL))
                {
                    throw new WebDriverException(Common.Utility.GetCommonMsgVariable("KRYPTONERRCODE0007") + ":" + e.Message);
                }
                throw new Exception(Common.Utility.GetCommonMsgVariable("KRYPTONERRCODE0054") + ":" + e.Message);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
コード例 #34
0
ファイル: Browser.cs プロジェクト: Thinksys/krypton
        /// <summary>
        ///  Method to Verify specified text is present in web page view source code .
        /// </summary>
        /// <param name="text">Text to verify</param>
        /// <returns>boolean value</returns>
        public bool VerifyTextInPageSource(string text, Dictionary<int, string> KeyWordDic)
        {
            try
            {
                try
                {
                    IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));
                    wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
                    Browser.switchToMostRecentBrowser();
                }
                catch { }

                bool isKeyVerified;
                string s = driver.PageSource;
                s = s.Replace("<br />", "<br>");
                s = s.Replace("<BR/>", "<br>");
                if (!KeyWordDic.Count.Equals(0))
                {
                    isKeyVerified = Common.Utility.doKeywordMatch(text, s);
                }
                else
                {
                    isKeyVerified = s.Contains(text);
                }
                if (!isKeyVerified)
                {
                    Common.Property.Remarks = "Actual text : \"" + text + "\" is not found";
                }
                return isKeyVerified;
            }
            catch (WebDriverException e)
            {
                if (e.Message.Contains(Common.exceptions.ERROR_NORESPONSEURL))
                {
                    throw new WebDriverException(Common.Utility.GetCommonMsgVariable("KRYPTONERRCODE0007") + ":" + e.Message);
                }
                throw new Exception(Common.Utility.GetCommonMsgVariable("KRYPTONERRCODE0054") + ":" + e.Message);
            }
            catch (Exception)
            {
                throw;
            }
        }
コード例 #35
0
ファイル: Browser.cs プロジェクト: Thinksys/krypton
        /// <summary>
        ///  Method to verify specied text on web page.
        /// </summary>
        /// <param name="text">Text to verify on web page</param>
        /// <returns>boolean value</returns>
        ///
        public bool VerifyTextPresentOnPage(string text, Dictionary<int, string> KeywordDic)
        {
            try
            {

                bool isKeyVerified = true;
                text = text.Trim();
                // Replace special characters here
                text = Common.Utility.ReplaceSpecialCharactersInString(text);
                try
                {
                    IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));
                    wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
                    Browser.switchToMostRecentBrowser();
                }
                catch { }
                IWebElement element = driver.FindElement(By.XPath("//html"));
                string pageText = element.Text.ToString().Trim();

                if (!KeywordDic.Count.Equals(0))
                {
                    isKeyVerified = Common.Utility.doKeywordMatch(text, pageText);
                }
                else
                {
                    isKeyVerified = pageText.Contains(text);
                }
                if (!isKeyVerified)
                {
                    Common.Property.Remarks = "Text : \"" + text + "\" is not found";
                }
                return isKeyVerified;
            }
            catch (WebDriverException e)
            {
                if (e.Message.Contains(Common.exceptions.ERROR_NORESPONSEURL))
                {
                    throw new WebDriverException(Common.Utility.GetCommonMsgVariable("KRYPTONERRCODE0007") + ":" + e.Message);
                }
                throw new Exception(Common.Utility.GetCommonMsgVariable("KRYPTONERRCODE0054") + ":" + e.Message);
            }
            catch (Exception e1)
            {
                throw;
            }
        }
コード例 #36
0
ファイル: Browser.cs プロジェクト: Thinksys/krypton
        /// <summary>
        ///  This method initialize specified web driver.
        ///  Updated for Window Resizing 
        /// /// </summary>
        private void initDriver(bool DeleteCookie=true)
        {
            try
            {

                Property.isSauceLabExecution = false;
                if (string.Compare(isRemoteExecution, "false", true) == 0)
                {
                    switch (browserName.ToLower())
                    {
                        case KryptonConstants.BROWSER_FIREFOX:
                            // If "firefoxProfilePath" contains path then load profile from that directory path.
                            if ((Browser.firefoxProfilePath.Length != 0) && Directory.Exists(Browser.firefoxProfilePath) && (Browser.firefoxProfilePath.Split('.').Last().ToString().ToLower() != "zip"))

                            {
                                string ffProfileSourcePath = Browser.firefoxProfilePath;
                                DirectoryInfo ffProfileSourceDir = new DirectoryInfo(ffProfileSourcePath);

                                if (!ffProfileSourceDir.Exists)
                                    throw new Exception(Common.Utility.GetCommonMsgVariable("KRYPTONERRCODE0012"));

                                if ((Common.Utility.GetParameter("FirefoxProfilePath")).Equals(Common.Utility.GetVariable("FirefoxProfilePath")))
                                {
                                    #region  This section works for 2.0rc2 release of selenium

                                    ffProfile = new FirefoxProfile(ffProfileSourceDir.ToString());
                                    //Support for Firefox version 5.0
                                    ffProfile.SetPreference("extensions.checkCompatibility.5.0", false);
                                    #region Handling Downloading Window.
                                    ffProfile.SetPreference("browser.download.dir", Common.Utility.GetParameter("downloadpath"));
                                    ffProfile.SetPreference("browser.download.useDownloadDir", true);
                                    ffProfile.SetPreference("browser.download.defaultFolder", Common.Utility.GetParameter("downloadpath"));
                                    ffProfile.SetPreference("browser.download.folderList", 2);
                                    ffProfile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/x-msdos-program, application/x-unknown-application-octet-stream, application/vnd.ms-powerpoint, application/excel, application/vnd.ms-publisher, application/x-unknown-message-rfc822, application/vnd.ms-excel, application/msword, application/x-mspublisher, application/x-tar, application/zip, application/x-gzip,application/x-stuffit,application/vnd.ms-works, application/powerpoint, application/rtf, application/postscript, application/x-gtar, video/quicktime, video/x-msvideo, video/mpeg, audio/x-wav, audio/x-midi, audio/x-aiff");
                                    #endregion
                                    #region Handling Unresponsive Script Warning.
                                    ffProfile.SetPreference("dom.max_script_run_time", 10 * 60);
                                    ffProfile.SetPreference("dom.max_chrome_script_run_time", 10 * 60);
                                    #endregion
                                    driver = new FirefoxDriver(ffProfile);
                                    driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(150));
                                    driver.Manage().Window.Maximize();
                                    if (IsBrowserDimendion)
                                        driver.Manage().Window.Size = new System.Drawing.Size(width, height);
                                    driverlist.Add(driver);
                                    DirectoryInfo ffProfileDestDir = new DirectoryInfo(ffProfile.ProfileDirectory);

                                    //Assigning profile location so that firefox can next time use same profile to open
                                    Common.Utility.SetVariable("FirefoxProfilePath", ffProfileDestDir.ToString());
                                    #endregion
                                }

                               // This else loop approches where there is a profile already created within same test case
                                else
                                {
                                    ffProfile = new FirefoxProfile(ffProfileSourceDir.ToString());
                                    //If Profile path is empty in parameter file then add setpreference to profile.:
                                    if (Common.Utility.GetParameter("FirefoxProfilePath").Equals(""))
                                    {
                                        ffProfile.SetPreference("webdriver_assume_untrusted_issuer", false);
                                    }
                                    //For ff5.0 version support.
                                    ffProfile.SetPreference("extensions.checkCompatibility.5.0", false);
                                    #region Handling Downloading Window.
                                    ffProfile.SetPreference("browser.download.dir", Common.Utility.GetParameter("downloadpath"));
                                    ffProfile.SetPreference("browser.download.useDownloadDir", true);
                                    ffProfile.SetPreference("browser.download.defaultFolder", Common.Utility.GetParameter("downloadpath"));
                                    ffProfile.SetPreference("browser.download.folderList", 2);
                                    ffProfile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/x-msdos-program, application/x-unknown-application-octet-stream, application/vnd.ms-powerpoint, application/excel, application/vnd.ms-publisher, application/x-unknown-message-rfc822, application/vnd.ms-excel, application/msword, application/x-mspublisher, application/x-tar, application/zip, application/x-gzip,application/x-stuffit,application/vnd.ms-works, application/powerpoint, application/rtf, application/postscript, application/x-gtar, video/quicktime, video/x-msvideo, video/mpeg, audio/x-wav, audio/x-midi, audio/x-aiff");
                                    #endregion
                                    #region Handling Unresponsive Script Warning.
                                    ffProfile.SetPreference("dom.max_script_run_time", 10 * 60);
                                    ffProfile.SetPreference("dom.max_chrome_script_run_time", 10 * 60);
                                    #endregion
                                    ffProfile.Port = 9966;
                                    driver = new FirefoxDriver(ffProfile);
                                    driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(150));
                                    driver.Manage().Window.Maximize();
                                    if (IsBrowserDimendion)
                                        driver.Manage().Window.Size = new System.Drawing.Size(width, height);
                                    driverlist.Add(driver);
                                }

                            }
                            else
                            {
                                // If "addonsPath" contains path then load addons from that directory path.
                                if (Browser.addonsPath.Length != 0)
                                {
                                    try
                                    {
                                        string adPath = Browser.addonsPath;

                                        if (!Directory.Exists(adPath))
                                            throw new Exception(Common.Utility.GetCommonMsgVariable("KRYPTONERRCODE0014"));

                                        DirectoryInfo adDir = new DirectoryInfo(adPath);
                                        DirectoryInfo adDirTemp = new DirectoryInfo("AddonsTemp");
                                        adDirTemp.Create();
                                        foreach (FileInfo fi in adDir.GetFiles())
                                        {
                                            fi.CopyTo(Path.Combine(adDirTemp.FullName, fi.Name), true);
                                        }

                                        int firebugCount = 0;
                                        string[] addonFilePaths = Directory.GetFiles(adPath);
                                        ffProfile = new FirefoxProfile();
                                        ffProfile.SetPreference("webdriver_assume_untrusted_issuer", false);
                                        ffProfile.SetPreference("network.cookie.lifetimePolicy", 0);
                                        ffProfile.SetPreference("privacy.sanitize.sanitizeOnShutdown", false);
                                        ffProfile.SetPreference("privacy.sanitize.promptOnSanitize", false);
                                        // for ff5 support.
                                        ffProfile.SetPreference("extensions.checkCompatibility.5.0", false);
                                        #region Handling Downloading Window.
                                        ffProfile.SetPreference("browser.download.dir", Common.Utility.GetParameter("downloadpath"));
                                        ffProfile.SetPreference("browser.download.useDownloadDir", true);
                                        ffProfile.SetPreference("browser.download.defaultFolder", Common.Utility.GetParameter("downloadpath"));
                                        ffProfile.SetPreference("browser.download.folderList", 2);
                                        ffProfile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/x-msdos-program, application/x-unknown-application-octet-stream, application/vnd.ms-powerpoint, application/excel, application/vnd.ms-publisher, application/x-unknown-message-rfc822, application/vnd.ms-excel, application/msword, application/x-mspublisher, application/x-tar, application/zip, application/x-gzip,application/x-stuffit,application/vnd.ms-works, application/powerpoint, application/rtf, application/postscript, application/x-gtar, video/quicktime, video/x-msvideo, video/mpeg, audio/x-wav, audio/x-midi, audio/x-aiff");
                                        #endregion
                                        #region Handling Unresponsive Script Warning.
                                        ffProfile.SetPreference("dom.max_script_run_time", 10 * 60);
                                        ffProfile.SetPreference("dom.max_chrome_script_run_time", 10 * 60);
                                        #endregion
                                        //Assigning profile location so that firefox can next time use same profile to open
                                        Common.Utility.SetVariable("FirefoxProfilePath", ffProfile.ProfileDirectory.ToString());

                                        // Add all the addons found in the specified addon directory
                                        foreach (FileInfo afi in adDirTemp.GetFiles())
                                        {
                                            if (afi.Name.ToLower().Contains("firebug"))
                                                firebugCount++;

                                            ffProfile.AddExtension(adDirTemp.Name + '/' + afi.Name);
                                        }

                                        // If user placed multiple versions of firebug in Addons directory then give error
                                        if (firebugCount > 1)
                                            throw new Exception(Common.Utility.GetCommonMsgVariable("KRYPTONERRCODE0015"));

                                        // Start firefox with the profile that contains all the addons in addon directory
                                        driver = new FirefoxDriver(ffProfile);
                                        driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(150));
                                        driver.Manage().Window.Maximize();
                                        if (IsBrowserDimendion)
                                            driver.Manage().Window.Size = new System.Drawing.Size(width, height);
                                        driverlist.Add(driver);
                                    }
                                    catch (Exception e)
                                    {
                                        throw new Exception(Common.Utility.GetCommonMsgVariable("KRYPTONERRCODE0009").Replace("{MSG}", e.Message));
                                    }
                                }
                                else
                                {
                                    int webDriverPort = 7055;
                                    ffProfile = new FirefoxProfile();
                                    ffProfile.SetPreference("webdriver_assume_untrusted_issuer", false);
                                    ffProfile.SetPreference("network.cookie.lifetimePolicy", 0);
                                    ffProfile.SetPreference("privacy.sanitize.sanitizeOnShutdown", false);
                                    ffProfile.SetPreference("privacy.sanitize.promptOnSanitize", false);
                                    ffProfile.SetPreference("extensions.checkCompatibility.5.0", false);//For FF5 version support.

                                    #region Handling Downloading Window.
                                    ffProfile.SetPreference("browser.download.dir", Common.Utility.GetParameter("downloadpath"));
                                    ffProfile.SetPreference("browser.download.useDownloadDir", true);
                                    ffProfile.SetPreference("browser.download.defaultFolder", Common.Utility.GetParameter("downloadpath"));
                                    ffProfile.SetPreference("browser.download.folderList", 2);
                                    ffProfile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/x-msdos-program, application/x-unknown-application-octet-stream, application/vnd.ms-powerpoint, application/excel, application/vnd.ms-publisher, application/x-unknown-message-rfc822, application/vnd.ms-excel, application/msword, application/x-mspublisher, application/x-tar, application/zip, application/x-gzip,application/x-stuffit,application/vnd.ms-works, application/powerpoint, application/rtf, application/postscript, application/x-gtar, video/quicktime, video/x-msvideo, video/mpeg, audio/x-wav, audio/x-midi, audio/x-aiff");
                                    #endregion
                                    #region Handling Unresponsive Script Warning.
                                    ffProfile.SetPreference("dom.max_script_run_time", 10 * 60);
                                    ffProfile.SetPreference("dom.max_chrome_script_run_time", 10 * 60);
                                    #endregion
                                    for (int port = webDriverPort; port <= webDriverPort + 5; port++)
                                    {
                                        // Allowing security exception to appear and being able to handle
                                        ffProfile.SetPreference("browser.xul.error_pages.expert_bad_cert", true);
                                        ffProfile.AcceptUntrustedCertificates = true;
                                        string profileDir = ffProfile.ProfileDirectory;
                                        ffProfile.Port = port;
                                        driver = new FirefoxDriver(ffProfile);
                                        driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(150));
                                        driver.Manage().Window.Maximize();
                                        if (IsBrowserDimendion)
                                            driver.Manage().Window.Size = new System.Drawing.Size(width, height);
                                        driverlist.Add(driver);
                                        //Assigning profile location so that firefox can next time use same profile to open
                                        Common.Utility.SetVariable("FirefoxProfilePath", ffProfile.ProfileDirectory.ToString());

                                        break;
                                    }

                                    if (driver == null)
                                    {
                                        throw new Exception(Common.Utility.GetCommonMsgVariable("KRYPTONERRCODE0016"));
                                    }
                                }
                                //Add WebDriver Profile File to list of files that need to be deleted in temp folder.
                                Common.Property.listOfFilesInTempFolder.Add(Common.Utility.GetVariable("FirefoxProfilePath"));
                            }
                            break;
                        case KryptonConstants.BROWSER_IE:

                            InternetExplorerOptions options = new InternetExplorerOptions();
                            // Commented to check CSA related problem
                            options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
                         //for merging mobile build

                         options.EnablePersistentHover = false; //added for IE-8 certificate related issue.
                            if (DeleteCookie)
                            {
                                options.EnsureCleanSession = true;
                            }
                            driver = new InternetExplorerDriver(Property.ApplicationPath+@"\Exes",options);
                            driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(150));
                            driver.Manage().Window.Maximize();    //  Added to maximize IE window forcibely, as this code is updated Action file.
                            if (IsBrowserDimendion)
                                driver.Manage().Window.Size = new System.Drawing.Size(width, height);
                            driverlist.Add(driver);
                            break;

                        case Common.KryptonConstants.BROWSER_CHROME:
                            // Selenium v 2.1.17 states to use chrome options instead of capabilities
                            if(signal==0)
                            {
                                if ((Directory.Exists(Browser.chromeProfilePath)))
                                {
                                    string chromeProfileSourcePath = Browser.chromeProfilePath;
                                    DirectoryInfo chromeProfileSourceDir = new DirectoryInfo(chromeProfileSourcePath);

                                    if (!chromeProfileSourceDir.Exists)
                                        throw new Exception(Common.Utility.GetCommonMsgVariable("KRYPTONERRCODE0012"));
                                    if (File.Exists(chromeProfilePath+ @"\ChromeOptions.txt"))
                                    {
                                        using (StreamReader reader = new StreamReader(chromeProfilePath + @"\ChromeOptions.txt"))
                                        {
                                            string line = string.Empty;
                                            while ((line = reader.ReadLine()) != null)
                                            {
                                                chromeOpt.AddArgument(line);
                                            }

                                        }
                                    }
                                }
                            chromeOpt.AddArguments("--test-type");
                            chromeOpt.AddArgument("--ignore-certificate-errors");
                            chromeOpt.AddArgument("--start-maximized");
                            System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(chromecookPath);
                            Empty(directory);
                            chromeOpt.AddArguments("user-data-dir="+chromecookPath);
                            signal = 1;
                            }
                            driver = new ChromeDriver(Property.ApplicationPath+@"\Exes", chromeOpt);
                            driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(150));
                            driver.Manage().Window.Maximize();
                            if (IsBrowserDimendion)
                                driver.Manage().Window.Size = new System.Drawing.Size(width, height);
                            driverlist.Add(driver);
                            break;
                        case KryptonConstants.BROWSER_SAFARI:
                            driver = new SafariDriver();
                            driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(150));
                            driver.Manage().Window.Maximize();
                            if (IsBrowserDimendion)
                                driver.Manage().Window.Size = new System.Drawing.Size(width, height);
                            driverlist.Add(driver);
                            break;
                        default:
                            Console.WriteLine("No browser is defined.");
                            break;
                    }
                    WebDriverWait wdw = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, new TimeSpan(1000));
                }
                else
                {
                    // Attempt by  for sauce execution
                    //Start
                    if (Common.Property.RemoteUrl.ToLower().Contains("saucelabs"))
                    {
                        DesiredCapabilities capabilities = new DesiredCapabilities();
                            Utility.SetParameter("CloseBrowserOnCompletion", "true");//Forcing the close browser to true.
                            Utility.SetVariable("CloseBrowserOnCompletion", "true");
                            Property.isSauceLabExecution = true;
                            capabilities.SetCapability("username", Common.Utility.GetParameter("username"));//Registered user name of Sauce labs
                            capabilities.SetCapability("accessKey", Common.Utility.GetParameter("password"));// Accesskey provided by the Sauce labs
                            capabilities.SetCapability("platform", Common.Utility.GetParameter("Platform"));// OS on which execution is to be done Eg: Windows 7 , mac , Linux etc..
                            capabilities.SetCapability("name", Common.Utility.GetParameter("TestCaseId"));
                            capabilities.SetCapability("browser", Common.Utility.GetParameter("SauceBrowser"));
                            capabilities.SetCapability("version", Common.Utility.GetParameter("VersionofBrowser"));
                            string RemoteHost = string.Empty;
                            remoteUrl = Common.Property.RemoteUrl + "/wd/hub";

                            // if Sauce connect is required...
                            string isSauceConnectRequired = Common.Utility.GetParameter("IsTestEnvironment");
                            if (isSauceConnectRequired.ToLower()=="true")
                            {
                                executeSauceConnect();
                                Thread.Sleep(20 * 1000);
                            }

                            SeleniumGrid oSeleniumGrid = new SeleniumGrid(remoteUrl, Common.Utility.GetParameter("SauceBrowser"), capabilities);
                            Browser.driver = oSeleniumGrid.GetDriverSauce();
                            if (!string.IsNullOrEmpty(RemoteHost))
                            {
                                Common.Property.RCMachineId = RemoteHost;
                                Utility.SetVariable(Common.Property.RCMachineId, RemoteHost);
                                Utility.SetParameter(Common.Property.RCMachineId, RemoteHost);
                            }
                            driverActions = new Actions(driver);

                    }
                    else
                    {
                        string RemoteHost = string.Empty;
                    remoteUrl = Common.Property.RemoteUrl + "/wd/hub";
                     // (management of remote driver in a seperate class)
                    SeleniumGrid oSeleniumGrid = new SeleniumGrid(remoteUrl, browserName);
                    Browser.driver = oSeleniumGrid.GetDriver(out RemoteHost);
                    if (!string.IsNullOrEmpty(RemoteHost))
                    {
                        Common.Property.RCMachineId = RemoteHost;
                        Utility.SetVariable(Common.Property.RCMachineId, RemoteHost);
                        Utility.SetParameter(Common.Property.RCMachineId, RemoteHost);

                    }

                    //Initializing actions object for later usage
                    driverActions = new Actions(driver);
                    }
                }
            }
            catch (WebDriverException e)
            {
                if (e.Message.Contains(Common.exceptions.ERROR_NORESPONSEURL) || e.Message.IndexOf("Connection refused", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    if (isRemoteExecution.Equals("true"))
                    {

                        this.initDriver();

                    }
                    throw new WebDriverException(Common.Utility.GetCommonMsgVariable("KRYPTONERRCODE0007") + ":" + e.Message);
                }
                throw e;
            }
            catch (Exception e)
            {
                if (e.Message.IndexOf(Common.exceptions.ERROR_PARSINGVALUE, StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    if (isRemoteExecution.Equals("true"))
                    {
                        this.initDriver();
                    }
                    throw new WebDriverException(Common.Utility.GetCommonMsgVariable("KRYPTONERRCODE0007") + ":" + e.Message);
                }
                throw e;
            }
        }
コード例 #37
0
ファイル: Browser.cs プロジェクト: Thinksys/krypton
        /// <summary>
        ///  Method to return value of property if found other wise return null
        /// </summary>
        /// <param name="propertyType"> Type of property to get from test object.</param>
        /// <returns>Property value</returns>
        public string GetPageProperty(string propertyType)
        {
            try
            {
                try
                {
                    IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));
                    wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
                    Browser.switchToMostRecentBrowser();
                }
                catch
                {
                // will not affect normal test case flow.
                }

                switch (propertyType.ToLower())
                {
                    case "title":
                        return driver.Title;
                    case "url":
                        return driver.Url;
                    default:
                        return null; ;
                }
            }
            catch (WebDriverException e)
            {
                if (e.Message.Contains(Common.exceptions.ERROR_NORESPONSEURL))
                {
                    throw new WebDriverException(Common.Utility.GetCommonMsgVariable("KRYPTONERRCODE0007") + ":" + e.Message);
                }
                throw new Exception(Common.Utility.GetCommonMsgVariable("KRYPTONERRCODE0054") + ":" + e.Message);
            }
            catch (Exception)
            {
                throw;
            }
        }
コード例 #38
0
ファイル: WebDriverExtensions.cs プロジェクト: c0d3m0nky/mty
 public static IEnumerable<IWebElement> FindAllElements(this IWebDriver driver, By findExpression)
 {
     var wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(MaxTimeToWaitForResponse));
     return driver.FindElements(findExpression);
 }
コード例 #39
0
        private static void Wait(ChromeDriver driver)
        {
            IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));

            wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
        }
コード例 #40
0
 //Wait till loading completed
 public void WaitforLoading(int timeout)
 {
     IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(timeout));
     wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
 }
コード例 #41
0
ファイル: Instance.cs プロジェクト: buonan/SeleniumTests
 /// <summary>
 /// Retries the wait for document loaded.
 /// </summary>
 private void _RetryWaitForDocumentLoaded()
 {
     IWebDriver driver = Factory.Instance;
     IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(Browsers.DefaultTimeoutInSeconds));
     wait.Until(d => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
 }