public override IWebDriver CreateDriver(DriverProperty driverProperty)
        {
            ParameterValidator.ValidateNotNull(driverProperty, "Driver Property");

            ChromeOptions options = new ChromeOptions();

            if (driverProperty.Headless)
            {
                options.AddArgument("--headless");
                options.AddArgument("--disable-gpu");
                options.AddUserProfilePreference("disable-popup-blocking", "true");
                options.AddUserProfilePreference("intl.accept_languages", "en,en_US");
            }

            if (driverProperty.DownloadLocation != null)
            {
                options.AddUserProfilePreference("download.default_directory", driverProperty.DownloadLocation);
            }

            if (driverProperty.Arguments != null)
            {
                options.AddArguments(driverProperty.GetArgumentsAsArray());
            }

            if (DriverVersion == null)
            {
                lock (Instancelock)
                {
                    if (DriverVersion == null)
                    {
                        if (string.IsNullOrEmpty(driverProperty.DriverVersion))
                        {
                            DriverVersion = GetStableVersion();
                        }
                        else
                        {
                            DriverVersion = driverProperty.DriverVersion;
                        }
                    }
                }
            }

            // Use custom Chrome binary (81)
            // https://chromium.cypress.io/win64/stable/81.0.4044.92
            // options.BinaryLocation = "C:\\Users\\sbaltuonis\\Downloads\\chrome-win\\chrome.exe";

            // Run in private mode
            options.AddArgument("--incognito");

            // Enable mobile emulation
            if (!string.IsNullOrEmpty(driverProperty.DeviceName))
            {
                options.EnableMobileEmulation(driverProperty.DeviceName);
            }
            else if (!string.IsNullOrEmpty(driverProperty.CustomUserAgent))
            {
                if (driverProperty.CustomWidth <= 0 ||
                    driverProperty.CustomHeight <= 0 ||
                    driverProperty.CustomPixelRatio <= 0)
                {
                    throw new Exception("Custom device width, height and pixel ratio must be greater than 0");
                }

                ChromeMobileEmulationDeviceSettings emulationSettings = new ChromeMobileEmulationDeviceSettings
                {
                    UserAgent  = driverProperty.CustomUserAgent,
                    Width      = driverProperty.CustomWidth,
                    Height     = driverProperty.CustomHeight,
                    PixelRatio = driverProperty.CustomPixelRatio
                };

                options.EnableMobileEmulation(emulationSettings);
            }

            // Setup driver binary
            try
            {
                new WebDriverManager.DriverManager().SetUpDriver(new ChromeConfig(), DriverVersion);
            }
            catch (Exception)
            {
                throw new Exception($"Cannot get Chrome driver version {DriverVersion}");
            }

            #pragma warning disable CA2000 // Dispose objects before losing scope
            return(new ChromeDriver(ChromeDriverService.CreateDefaultService(), options, TimeSpan.FromSeconds(180)));

            #pragma warning restore CA2000 // Dispose objects before losing scope
        }
        /// <summary>
        ///     Create a instance of the selected browser if configured
        ///     appsettings.browserstack.json
        /// </summary>
        /// <param name="browserName"></param>
        public Browser(string browserName)
        {
            var configFile = "appsettings.browserstack.json";

            if (!File.Exists(configFile))
            {
                var exampleConfig = @"
{
  ""_comment"": ""https://www.browserstack.com/automate/capabilities"",
  ""DefaultTimeout"": 30,
  ""BrowserstackLocal"": true,
  ""Project"": ""BaseHooks Test"",
  ""Environment"": ""LocalHorst"",
  ""Project"": ""Enter your project"",
  ""Environment"": ""Enter your Environment"",
  ""BROWSERSTACK_USERNAME"": ""yourUserName"",
  ""BROWSERSTACK_ACCESS_KEY"": ""**********"",
  ""Browsers"": [
        {
          ""Name"": ""Chrome"",
          ""AccuracyInPromille"": 930,
          ""isDesktop"":  true,
          ""Capabilities"":{
              ""browser"": ""Chrome"",
              ""os"": ""Windows"",
              ""os_version"": ""10"",
              ""resolution"": ""1920x1080""
            }
        }
    ]
}";
                File.WriteAllText(configFile, exampleConfig);
                Status = $"The configuration file '{configFile}' did not exist. It was now created with an example. Please complete the configuration.";
            }

            var config = JObject.Parse(File.ReadAllText(configFile));

            #region Read the base configuration
            if (config.ContainsKey("DefaultTimeout"))
            {
                DefaultTimeout = (int)config["DefaultTimeout"];
            }
            if (config.ContainsKey("BrowserstackLocal"))
            {
                BrowserstackLocal = (bool)config["BrowserstackLocal"];
            }
            if (config.ContainsKey("Project") && BrowserstackProject == "")
            {
                BrowserstackProject = (string)config["BrowserstackProject"];
            }
            if (config.ContainsKey("Environment") && BrowserstackEnvironment == "")
            {
                BrowserstackEnvironment = (string)config["Environment"];
            }
            if (config.ContainsKey("BROWSERSTACK_USERNAME") && BrowserstackUser == "")
            {
                BrowserstackUser = (string)config["BROWSERSTACK_USERNAME"];
            }
            if (config.ContainsKey("BROWSERSTACK_ACCESS_KEY") && BrowserstackKey == "")
            {
                BrowserstackKey = (string)config["BROWSERSTACK_ACCESS_KEY"];
            }
            #endregion

            IEnumerable <JToken> result = from browser in config["Browsers"].Children()
                                          where (string)browser["Name"] == browserName
                                          select browser;

            if (result.Any())
            {
                JToken browserConfig = result.FirstOrDefault();

                AccuracyInPromille = (int)(browserConfig["AccuracyInPromille"] ?? 1000);
                IsDesktop          = (bool)(browserConfig["isDesktop"] ?? false);

                var capabilities = new DesiredCapabilities();
                capabilities.SetCapability("browserstack.user", BrowserstackUser);
                capabilities.SetCapability("browserstack.key", BrowserstackKey);
                capabilities.SetCapability("project", BrowserstackProject);
                capabilities.SetCapability("name", BrowserstackEnvironment);
                capabilities.SetCapability("browserstack.console", "errors");
                capabilities.SetCapability("browserstack.networkLogs", "false");
                if (BrowserstackLocalIdentifier != null)
                {
                    capabilities.SetCapability("browserstack.localIdentifier", BrowserstackLocalIdentifier);
                }
                IEnumerable <JToken> capabilityConfig = from capability in browserConfig["Capabilities"]
                                                        select capability;
                foreach (JProperty capability in capabilityConfig)
                {
                    capabilities.SetCapability(capability.Name, (string)capability.Value);
                }

                Driver = new RemoteWebDriver(
                    new Uri("http://hub-cloud.browserstack.com/wd/hub/"), capabilities, TimeSpan.FromSeconds(DefaultTimeout)
                    );
                Status = $"OK - {browserName}";
            }
            else
            {
                var chromeOptions = new ChromeOptions();
                chromeOptions.AcceptInsecureCertificates = true;
                chromeOptions.AddArguments("-purgecaches", "-private", "--disable-gpu", "--disable-direct-write", "--disable-display-color-calibration", "--allow-http-screen-capture", "--disable-accelerated-2d-canvas");
                if (Headless != "false")
                {
                    chromeOptions.AddArguments("-headless");
                }

                IsDesktop = true;
                Driver    = new ChromeDriver("./", chromeOptions, TimeSpan.FromSeconds(DefaultTimeout));
                Status    = $"Firefox - '{browserName}' not found in the config '{configFile}'";
            }

            if (IsDesktop)
            {
                try
                {
                    Driver.Manage().Window.Maximize();
                }
                catch (Exception)
                {
                    // if not supported by the device
                }
            }
        }
        public void Start()
        {
            switch (BaseConfiguration.TestBrowser)
            {
            case Factories.BrowserType.Firefox:
                if (!string.IsNullOrEmpty(BaseConfiguration.FirefoxBrowserExecutableLocation))
                {
                    this.FirefoxOptions.BrowserExecutableLocation = BaseConfiguration.FirefoxBrowserExecutableLocation;
                }

                this.driver = string.IsNullOrEmpty(BaseConfiguration.PathToFirefoxDriverDirectory) ? new FirefoxDriver(this.SetDriverOptions(this.FirefoxOptions)) : new FirefoxDriver(BaseConfiguration.PathToFirefoxDriverDirectory, this.SetDriverOptions(this.FirefoxOptions));
                break;

            case Factories.BrowserType.InternetExplorer:
            case BrowserType.IE:
                this.driver = string.IsNullOrEmpty(BaseConfiguration.PathToInternetExplorerDriverDirectory) ? new InternetExplorerDriver(this.SetDriverOptions(this.InternetExplorerOptions)) : new InternetExplorerDriver(BaseConfiguration.PathToInternetExplorerDriverDirectory, this.SetDriverOptions(this.InternetExplorerOptions));
                break;

            case BrowserType.Chrome:
                if (!string.IsNullOrEmpty(BaseConfiguration.ChromeBrowserExecutableLocation))
                {
                    this.ChromeOptions.BinaryLocation = BaseConfiguration.ChromeBrowserExecutableLocation;
                }

                this.driver = string.IsNullOrEmpty(BaseConfiguration.PathToChromeDriverDirectory) ? new ChromeDriver(this.SetDriverOptions(this.ChromeOptions)) : new ChromeDriver(BaseConfiguration.PathToChromeDriverDirectory, this.SetDriverOptions(this.ChromeOptions));
                break;

            case BrowserType.Safari:
                this.driver = new SafariDriver(this.SetDriverOptions(this.SafariOptions));
                this.CheckIfProxySetForSafari();
                break;

            case BrowserType.RemoteWebDriver:
                var driverCapabilitiesConf   = ConfigurationManager.GetSection("DriverCapabilities") as NameValueCollection;
                NameValueCollection settings = ConfigurationManager.GetSection("environments/" + this.CrossBrowserEnvironment) as NameValueCollection;
                var browserType = this.GetBrowserTypeForRemoteDriver(settings);

                switch (browserType)
                {
                case BrowserType.Firefox:
                    FirefoxOptions firefoxOptions = new FirefoxOptions();
                    this.SetRemoteDriverBrowserOptions(driverCapabilitiesConf, settings, firefoxOptions);
                    this.driver = new RemoteWebDriver(BaseConfiguration.RemoteWebDriverHub, this.SetDriverOptions(firefoxOptions).ToCapabilities());
                    break;

                case BrowserType.Android:
                case BrowserType.Chrome:
                    ChromeOptions chromeOptions = new ChromeOptions();
                    this.SetRemoteDriverBrowserOptions(driverCapabilitiesConf, settings, chromeOptions);
                    this.driver = new RemoteWebDriver(BaseConfiguration.RemoteWebDriverHub, this.SetDriverOptions(chromeOptions).ToCapabilities());
                    break;

                case BrowserType.Iphone:
                case BrowserType.Safari:
                    SafariOptions safariOptions = new SafariOptions();
                    this.SetRemoteDriverOptions(driverCapabilitiesConf, settings, safariOptions);
                    this.driver = new RemoteWebDriver(BaseConfiguration.RemoteWebDriverHub, this.SetDriverOptions(safariOptions).ToCapabilities());
                    break;

                case BrowserType.Edge:
                    EdgeOptions egEdgeOptions = new EdgeOptions();
                    this.SetRemoteDriverOptions(driverCapabilitiesConf, settings, egEdgeOptions);
                    this.driver = new RemoteWebDriver(BaseConfiguration.RemoteWebDriverHub, this.SetDriverOptions(egEdgeOptions).ToCapabilities());
                    break;

                case BrowserType.IE:
                case BrowserType.InternetExplorer:
                    InternetExplorerOptions internetExplorerOptions = new InternetExplorerOptions();
                    this.SetRemoteDriverBrowserOptions(driverCapabilitiesConf, settings, internetExplorerOptions);
                    this.driver = new RemoteWebDriver(BaseConfiguration.RemoteWebDriverHub, this.SetDriverOptions(internetExplorerOptions).ToCapabilities());
                    break;

                default:
                    throw new NotSupportedException(
                              string.Format(CultureInfo.CurrentCulture, "Driver {0} is not supported", this.CrossBrowserEnvironment));
                }

                break;

            case BrowserType.Edge:
                this.driver = new EdgeDriver(EdgeDriverService.CreateDefaultService(BaseConfiguration.PathToEdgeDriverDirectory, "MicrosoftWebDriver.exe", 52296), this.SetDriverOptions(this.EdgeOptions));
                break;

            default:
                throw new NotSupportedException(
                          string.Format(CultureInfo.CurrentCulture, "Driver {0} is not supported", BaseConfiguration.TestBrowser));
            }

            if (BaseConfiguration.EnableEventFiringWebDriver)
            {
                // this.driver = new MyEventFiringWebDriver(this.driver);
            }
        }
Example #4
0
        static void Main(string[] args)
        {
            MySettings settings = MySettings.Load();

            if (settings.urlTrade == null)
            {
                Console.WriteLine("Input url of trades: ");
                settings.urlTrade = Console.ReadLine();
            }

            settings.Save();

            ChromeOptions chrOptions = new ChromeOptions();

            chrOptions.AddArgument("--user-data-dir=" + settings.userDataDir);
            chrOptions.AddArgument("--profile-directory=Profile 1");
            chrOptions.AddArgument("--start-maximized");

            ChromeDriver chrDriver = new ChromeDriver(chrOptions);

            Random random = new Random();

            WebDriverWait wait = new WebDriverWait(chrDriver, TimeSpan.FromSeconds(5));

            Actions actions = new Actions(chrDriver);

            while (true)
            {
                chrDriver.Navigate().GoToUrl(settings.urlTrade);



                if (chrDriver.FindElementByXPath("//i[@class='fa fa-times']").Displayed)
                {
                    wait.Until(x => x.FindElement(By.XPath("//i[@class='fa fa-times']"))).Click();
                }

                List <IWebElement> chrElements = chrDriver.FindElementsByXPath("//button[@class='rlg-trade__action rlg-trade__bump ']").ToList();

                Console.WriteLine("Number of trades: " + chrElements.Count);

                LinkedList <string> list = new LinkedList <string>();

                foreach (var element in chrElements)
                {
                    list.AddLast("https://rocket-league.com/trade/" + element.GetAttribute("data-alias"));
                }

                foreach (var item in list)
                {
                    Console.WriteLine(item);
                }

                foreach (var item in list)
                {
                    chrDriver.Navigate().GoToUrl(item);

                    if (chrDriver.FindElementByXPath("//button[@class='rlg-trade__action rlg-trade__bump ']").Displayed)
                    {
                        chrDriver.FindElementByXPath("//button[@class='rlg-trade__action rlg-trade__bump ']").Click();
                    }

                    System.Threading.Thread.Sleep(3000);
                }

                Console.WriteLine("Waiting 15 min");
                System.Threading.Thread.Sleep(900000 + random.Next(1, 30000));
            }
        }
Example #5
0
        /// <summary>
        /// The get chrome options options.
        /// </summary>
        /// <returns>
        /// The <see cref="ChromeOptions"/>.
        /// </returns>
        private ChromeOptions GetChromeOptionsOptions()
        {
            var retVal = new ChromeOptions();

            return(retVal);
        }
Example #6
0
        /// <summary>
        /// Instantiates a RemoteWebDriver instance based on the browser passed to this method. Opens the browser and maximizes its window.
        /// </summary>
        /// <param name="browser">The browser to get instantiate the Web Driver for.</param>
        /// <param name="browserProfilePath">The folder path to the browser user profile to use with the browser.</param>
        /// <returns>The RemoteWebDriver of the browser passed in to the method.</returns>
        public static RemoteWebDriver CreateDriverAndMaximize(string browser, bool clearBrowserCache, bool enableVerboseLogging = false, string browserProfilePath = "", List <string> extensionPaths = null, int port = 17556, string hostName = "localhost")
        {
            // Create a webdriver for the respective browser, depending on what we're testing.
            RemoteWebDriver driver = null;

            _browser = browser.ToLowerInvariant();

            switch (browser)
            {
            case "opera":
            case "operabeta":
                OperaOptions oOption = new OperaOptions();
                oOption.AddArgument("--disable-popup-blocking");
                oOption.AddArgument("--power-save-mode=on");
                // TODO: This shouldn't be a hardcoded path, but Opera appeared to need this speficied directly to run well
                oOption.BinaryLocation = @"C:\Program Files (x86)\Opera\launcher.exe";
                if (browser == "operabeta")
                {
                    // TODO: Ideally, this code would look inside the Opera beta folder for opera.exe
                    // rather than depending on flaky hard-coded version in directory
                    oOption.BinaryLocation = @"C:\Program Files (x86)\Opera beta\38.0.2220.25\opera.exe";
                }
                ScenarioEventSourceProvider.EventLog.LaunchWebDriver(browser);
                driver = new OperaDriver(oOption);
                break;

            case "firefox":
                ScenarioEventSourceProvider.EventLog.LaunchWebDriver(browser);
                driver = new FirefoxDriver();
                break;

            case "chrome":
                ChromeOptions option = new ChromeOptions();
                option.AddUserProfilePreference("profile.default_content_setting_values.notifications", 1);
                ChromeDriverService chromeDriverService = ChromeDriverService.CreateDefaultService();
                if (enableVerboseLogging)
                {
                    chromeDriverService.EnableVerboseLogging = true;
                }

                if (!string.IsNullOrEmpty(browserProfilePath))
                {
                    option.AddArgument("--user-data-dir=" + browserProfilePath);
                }

                ScenarioEventSourceProvider.EventLog.LaunchWebDriver(browser);
                driver = new ChromeDriver(chromeDriverService, option);
                break;

            default:
                EdgeOptions edgeOptions = new EdgeOptions();
                edgeOptions.AddAdditionalCapability("browserName", "Microsoft Edge");

                EdgeDriverService edgeDriverService = null;

                if (extensionPaths != null && extensionPaths.Count != 0)
                {
                    // Create the extensionPaths capability object
                    edgeOptions.AddAdditionalCapability("extensionPaths", extensionPaths);
                    foreach (var path in extensionPaths)
                    {
                        Logger.LogWriteLine("Sideloading extension(s) from " + path);
                    }
                }

                if (hostName.Equals("localhost", StringComparison.InvariantCultureIgnoreCase))
                {
                    // Using localhost so create a local EdgeDriverService and instantiate an EdgeDriver object with it.
                    // We have to use EdgeDriver here instead of RemoteWebDriver because we need a
                    // DriverServiceCommandExecutor object which EdgeDriver creates when instantiated

                    edgeDriverService = EdgeDriverService.CreateDefaultService();
                    if (enableVerboseLogging)
                    {
                        edgeDriverService.UseVerboseLogging = true;
                    }

                    _port     = edgeDriverService.Port;
                    _hostName = hostName;

                    Logger.LogWriteLine(string.Format("  Instantiating EdgeDriver object for local execution - Host: {0}  Port: {1}", _hostName, _port));
                    ScenarioEventSourceProvider.EventLog.LaunchWebDriver(browser);
                    driver = new EdgeDriver(edgeDriverService, edgeOptions);
                }
                else
                {
                    // Using a different host name.
                    // We will make the assumption that this host name is the host of a remote webdriver instance.
                    // We have to use RemoteWebDriver here since it is capable of being instantiated without automatically
                    // opening a local MicrosoftWebDriver.exe instance (EdgeDriver automatically launches a local process with
                    // MicrosoftWebDriver.exe).

                    _port     = port;
                    _hostName = hostName;
                    var remoteUri = new Uri("http://" + _hostName + ":" + _port + "/");

                    Logger.LogWriteLine(string.Format("  Instantiating RemoteWebDriver object for remote execution - Host: {0}  Port: {1}", _hostName, _port));
                    ScenarioEventSourceProvider.EventLog.LaunchWebDriver(browser);
                    driver = new RemoteWebDriver(remoteUri, edgeOptions.ToCapabilities());
                }

                driver.Wait(2);

                if (clearBrowserCache)
                {
                    Logger.LogWriteLine("   Clearing Edge browser cache...");
                    ScenarioEventSourceProvider.EventLog.ClearEdgeBrowserCacheStart();
                    // Warning: this blows away all Microsoft Edge data, including bookmarks, cookies, passwords, etc
                    HttpClient client = new HttpClient();
                    client.DeleteAsync($"http://{_hostName}:{_port}/session/{driver.SessionId}/ms/history").Wait();
                    ScenarioEventSourceProvider.EventLog.ClearEdgeBrowserCacheStop();
                }

                _edgeBrowserBuildNumber = GetEdgeBuildNumber(driver);
                Logger.LogWriteLine(string.Format("   Browser Version - MicrosoftEdge Build Version: {0}", _edgeBrowserBuildNumber));

                string webDriverServerVersion = GetEdgeWebDriverVersion(driver);
                Logger.LogWriteLine(string.Format("   WebDriver Server Version - MicrosoftWebDriver.exe File Version: {0}", webDriverServerVersion));
                _edgeWebDriverBuildNumber = Convert.ToInt32(webDriverServerVersion.Split('.')[2]);

                break;
            }

            ScenarioEventSourceProvider.EventLog.MaximizeBrowser(browser);
            driver.Manage().Window.Maximize();
            driver.Wait(1);
            return(driver);
        }
Example #7
0
        static void Main(string[] args)
        {
            try
            {
                loadConfigFile();

                ChromeDriverService _driverService = ChromeDriverService.CreateDefaultService();
                _driverService.HideCommandPromptWindow = true;

                ChromeOptions _options = new ChromeOptions();
                _options.AddArgument("disable-gpu");

                ChromeDriver  _driver = new ChromeDriver(_driverService, _options);
                WebDriverWait wait    = new WebDriverWait(_driver, TimeSpan.FromSeconds(10));


                _driver.Navigate().GoToUrl("https://eis.cbnu.ac.kr/");

                var uid = wait.Until(ElementExists(By.XPath("//*[@id='uid']")));
                uid.SendKeys(userId);

                var pswd = _driver.FindElementByXPath("//*[@id='pswd']");
                pswd.SendKeys(userPW);

                var loginButton = _driver.FindElementByXPath("//*[@id='commonLoginBtn']");
                loginButton.Click();

                try
                {
                    wait.Until(ElementExists(By.XPath("//*[@id='mainframe_VFS_LoginFrame_ssoLoginTry_form_btn_y']"))).Click();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                while (true)
                {
                    try
                    {
                        wait.Until(ElementExists(By.XPath("//*[@id='mainframe_VFS_HFS_SubFrame_form_tab_subMenu_tpg_bssMenu_grd_menu_body_gridrow_8']"))).Click();
                        break;
                    }
                    catch (Exception ex)
                    {
                        Thread.Sleep(1000);
                    }
                }

                wait.Until(ElementExists(By.XPath("//*[@id='mainframe_VFS_HFS_SubFrame_form_tab_subMenu_tpg_bssMenu_grd_menu_body_gridrow_9']"))).Click();
                wait.Until(ElementExists(By.XPath("//*[@id='mainframe_VFS_HFS_SubFrame_form_tab_subMenu_tpg_bssMenu_grd_menu_body_gridrow_16']"))).Click();
                wait.Until(ElementExists(By.XPath("//*[@id='mainframe_VFS_HFS_INVFS_WorkFrame_win_2275_form_div_work_btn_search']"))).Click();


                Dictionary <int, ArrayList> list = new Dictionary <int, ArrayList>();

                var downButton = _driver.FindElementByXPath("//*[@id='mainframe_VFS_HFS_INVFS_WorkFrame_win_2275_form_div_work_grd_master_vscrollbar_incbutton']");

                while (list.Count < 3880)
                {
                    var table = wait.Until(ElementExists(By.XPath("//*[@id='mainframe_VFS_HFS_INVFS_WorkFrame_win_2275_form_div_work_grd_master_bodyGridBandContainerElement_inner']")));
                    if (table.FindElements(By.TagName("div")).Count <= 2)
                    {
                        continue;
                    }


                    var test  = table.FindElement(By.XPath($"//*[@id='mainframe_VFS_HFS_INVFS_WorkFrame_win_2275_form_div_work_grd_master_body_gridrow_{(list.Count + 1) % 12}']"));
                    var index = Int32.Parse(test.FindElement(By.XPath($"//*[@id='mainframe_VFS_HFS_INVFS_WorkFrame_win_2275_form_div_work_grd_master_body_gridrow_{list.Count % 12}_cell_{list.Count % 12}_0']")).GetAttribute("aria-label"));

                    if (list.ContainsKey(index))
                    {
                        continue;
                    }

                    if (list.Count >= 3880)
                    {
                        break;
                    }

                    ArrayList row = new ArrayList();
                    for (var j = 1; j <= 20; j++)
                    {
                        try
                        {
                            row.Add(test.FindElement(By.XPath($"//*[@id='mainframe_VFS_HFS_INVFS_WorkFrame_win_2275_form_div_work_grd_master_body_gridrow_{list.Count % 12}_cell_{list.Count % 12}_{j}']")).GetAttribute("aria-label"));
                        }
                        catch (Exception ex)
                        {
                            row.Add("");
                        }
                    }
                    Console.WriteLine(row[2]);
                    list.Add(index, row);
                    if (list.Count % 12 == 0)
                    {
                        for (var i = 1; i <= 12; i++)
                        {
                            downButton.Click();
                        }
                        _driver.FindElementByXPath($"//*[@id='mainframe_VFS_HFS_INVFS_WorkFrame_win_2275_form_div_work_grd_master_body_gridrow_0_cell_0_1']").Click();
                    }
                }

                for (var i = 1; i <= 3880; i++)
                {
                    for (var j = 0; j < 20; j++)
                    {
                        Console.Write($"{((ArrayList)list[i])[j]} ");
                    }
                    Console.WriteLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Example #8
0
        public void SearchMine()
        {
            ChromeOptions options = new ChromeOptions();

            options.AddExtensions( //"libraries\\AdBIock-Plus_v2.1.crx",
                                   //"libraries\\Block-image_v1.1.crx",
                "dependencies\\AdBlock.crx",
                "dependencies\\ImgBlock.crx");

            //"libraries\\Adguard-AdBlocker_v2.5.11.crx");
            driver = new ChromeDriver(options);
            driver.Manage().Window.Maximize();
            driver.Manage().Timeouts().SetScriptTimeout(awaitDisplay);
            driver.Manage().Timeouts().ImplicitlyWait(awaitDisplay);
            driver.Manage().Timeouts().SetPageLoadTimeout(awaitDisplay);
            //driver.Manage().Window.Position = new System.Drawing.Point(0, 0);
            try
            {
                //Incase i didnt logout or someone is using the account #thuglife
                driver.Navigate().GoToUrl(Utils.LogoutUrl);
                //I was kind of hoping to avoid these but screw it, we're on the clock.
                //Just give it an extra second to do it's work.
                Thread.Sleep(1000);
            }
            catch
            {
            }
            driver.Url = @"http://www.loopnet.com";
            //
            driver.FindElementByXPath(Utils.LoginButtonXPath).Click();
            //Go to login page
            //driver.Navigate().GoToUrl(loginUrl);
            //uid
            var loginUidTextBox = driver.FindElement(By.Id("ctlLogin_LogonEmail"));

            loginUidTextBox.SendKeys(UID);
            //login
            var loginPwdTextBox = driver.FindElement(By.Id("ctlLogin_LogonPassword"));

            loginPwdTextBox.SendKeys(PWD);
            //
            //Click the login button
            //
            var loginBtn = driver.FindElementById("ctlLogin_btnLogon");

            loginBtn.Click();
            //
            //Fast track to the lease polygons (Collier's submarket)
            //
            //string namesXPath = "/html/body/form/div[5]/div/div/table/tbody/tr[1]";
            string savedSearchesUrl = "http://www.loopnet.com/xNet/MainSite/Listing/SavedSearches/MySavedSearches_FSFL.aspx?LinkCode=29400&ShowBasicLoggedInMsg=N";

            driver.Url = savedSearchesUrl;
            //
            List <String> collierSearchAreaNames = driver.FindElementsByXPath(Utils.SearchNameTDsXPath).Select(name => name.Text).ToList <string>();
            //
            //Get the lease and search area urls and then combine them.
            //
            List <String> collierSearchAreaUrls = driver.FindElementsByXPath(Utils.SearchLinksXPath).Select(href => href.GetAttribute("href")).ToList <string>();

            //
            if (collierSearchAreaNames.Count != collierSearchAreaUrls.Count || collierSearchAreaNames.Count == 0)
            {
                throw new Exception($"Search area count {collierSearchAreaNames.Count} not inline with link count {collierSearchAreaUrls}");
            }
            for (int i = 0; i < collierSearchAreaNames.Count; i++)
            {
                if (collierSearchAreaNames[i].ToLower().Contains("sale"))
                {
                    searchAreas.Add(new SearchArea(collierSearchAreaNames[i], collierSearchAreaUrls[i]));
                }
            }
            //
            //Iterate through types then pages for the type
            //

            List <string> propertyTypes = new List <string>();

            for (int i = 0; i < searchAreas.Count; i++)
            {
                driver.Url = searchAreas[i].BaseUrl;
                //
                //Make the property types visible

                //
                if (i == 0)
                {
                    //Need my overlay killer.
                    //
                    driver.FindElementByXPath(Utils.AllPropertyTypesBtnXPath).Click();
                    //
                    //Uncheck all Types
                    IWebElement selectAllElement = driver.FindElementByXPath(Utils.SelectAllPropertyTypesChkBoxXPath);
                    if (selectAllElement.GetAttribute("checked") == "checked")
                    {
                        selectAllElement.Click();
                    }
                    //
                    propertyTypes.AddRange(driver.FindElementsByXPath(Utils.PropertyTypeNamesXPath).ToList().Select(x => x.Text));
                }
                else
                {
                    //List<IWebElement> propertyTypeLIs = driver.FindElementsByXPath(Utils.PropertyTypesLIElementsXPath).ToList();
                    //IWebElement prevPropertyBox = propertyTypeLIs.s
                }

                //Need to process properties on each page.

                //Move to next.
            }
        }
Example #9
0
        private void UploadAdvs()
        {
            if (!_db.Connect())
            {
                MessageBox.Show(General.ERROR_DB_CONNECT);
                _db.Close();
                Invoke(new Action(() =>
                {
                    statusLabel.Text      = STATUS_BAR_DEFAULT;
                    uploadButton.Enabled  = true;
                    exploreButton.Enabled = true;
                    parseButton.Enabled   = true;
                    exportButton.Enabled  = true;
                    textBox2.Enabled      = true;
                    stopButton.Enabled    = false;
                    fromBox.Enabled       = true;
                    toBox.Enabled         = true;
                }));
                return;
            }

            var targets = textBox2.Text.Split(';');
            var i       = 0;

            foreach (var target in targets)
            {
                var paths = Directory.GetDirectories(target);
                Invoke(new Action(() =>
                {
                    statusLabel.Text = "Инициализация Selenium...";
                }));
                IWebDriver browser;
                var        option = new ChromeOptions();
                option.AddArgument("--headless");
                option.AddArgument("--user-agent=" + General.DEFAULT_USER_AGENT);
                //option.AddArgument("--proxy-server=socks5://109.234.35.41:8888");
                var service = ChromeDriverService.CreateDefaultService();
                service.HideCommandPromptWindow = true;
                browser = new ChromeDriver(service, option);
                // Нужно сделать проверку является-ли фарпостовской сессией
                var defaultPageAddress = "https://www.farpost.ru/vladivostok/realty/sell_flats/?page=1";
                browser.Navigate().GoToUrl(defaultPageAddress);
                var def = (int)(toBox.Value - fromBox.Value) + 1;
                foreach (var path in paths)
                {
                    if (_stopFlag)
                    {
                        break;
                    }
                    var pathSplit = path.Split('\\');
                    var advName   = pathSplit[pathSplit.Length - 1];
                    var nlink     = target + "\\" + advName;
                    if (File.Exists(nlink + ".html") || File.Exists(nlink + "_arch.html"))
                    {
                        i++;
                        continue;
                    }
                    var idStr = pathSplit[pathSplit.Length - 1].Split('_')[0];
                    if (!int.TryParse(idStr, out int id))
                    {
                        i++;
                        continue;
                    }
                    if (id < fromBox.Value || id > toBox.Value)
                    {
                        i++;
                        continue;
                    }
                    Invoke(new Action(() =>
                    {
                        statusLabel.Text = "Загрузка объявления #" + idStr + " [" + i + "/" + def + "]";
                    }));
                    var link = _db.GetLinkById(id);
                    while (true)
                    {
                        if (_stopFlag)
                        {
                            break;
                        }
                        try
                        {
                            browser.Navigate().GoToUrl(link);
                            if (browser.PageSource.Contains("Из вашей подсети наблюдается подозрительная активность"))
                            {
                                _db.Close();
                                Invoke(new Action(() =>
                                {
                                    statusLabel.Text      = STATUS_BAR_DEFAULT;
                                    uploadButton.Enabled  = true;
                                    exploreButton.Enabled = true;
                                    parseButton.Enabled   = true;
                                    exportButton.Enabled  = true;
                                    textBox2.Enabled      = true;
                                    stopButton.Enabled    = false;
                                    fromBox.Enabled       = true;
                                    toBox.Enabled         = true;
                                }));
                                service.Dispose();
                                browser.Dispose();
                                MessageBox.Show("Капча! Завершаем работу.");
                                return;
                            }
                            break;
                        }
                        catch (Exception ex)
                        {
                            General.WriteLog(ex.Message);
                            Thread.Sleep(10000);
                        }
                    }
                    if (!browser.PageSource.Contains("Объявление находится в архиве и может быть неактуальным."))
                    {
                        for (var k = 0; k < 5; k++)
                        {
                            if (_stopFlag)
                            {
                                break;
                            }
                            try
                            {
                                var element = browser.FindElement(By.PartialLinkText("Показать контакты"));
                                element.Click();
                                var isf = false;
                                for (var ti = 0; ti < 20 && !_stopFlag; ti++)
                                {
                                    try
                                    {
                                        browser.FindElement(By.ClassName("dummy-listener_new-contacts"));
                                        isf = true;
                                        break;
                                    }
                                    catch
                                    {
                                        Thread.Sleep(500);
                                    }
                                }
                                if (isf)
                                {
                                    break;
                                }
                            }
                            catch (Exception ex)
                            {
                                General.WriteLog(ex.Message);
                                Thread.Sleep(1000);
                            }
                        }
                    }
                    else
                    {
                        nlink += "_arch";
                    }
                    try
                    {
                        var element = browser.FindElement(By.ClassName("expand--button"));
                        element.Click();
                        for (var ti = 0; ti < 20 && !_stopFlag; ti++)
                        {
                            try
                            {
                                browser.FindElement(By.ClassName("mod__active"));
                                break;
                            }
                            catch
                            {
                            }
                            Thread.Sleep(1000);
                        }
                    }
                    catch (Exception)
                    {
                    }
                    var content = browser.PageSource;


                    var images = new List <string>();
                    var doc    = new HtmlAgilityPack.HtmlDocument();
                    doc.LoadHtml(content);
                    var nodes = doc.DocumentNode.SelectNodes("//img");
                    if (nodes != null)
                    {
                        var nodesArray = nodes.ToArray();
                        foreach (var node in nodesArray)
                        {
                            images.Add(node.Attributes["src"].Value);
                        }
                    }

                    int img_name = 0;
                    using (var wc = new WebClient())
                    {
                        foreach (var imageSrc in images)
                        {
                            if (_stopFlag)
                            {
                                break;
                            }
                            try
                            {
                                var ext = imageSrc;
                                var idx = ext.LastIndexOf("/");
                                if (idx == -1)
                                {
                                    continue;
                                }
                                ext = ext.Remove(0, idx + 1);
                                idx = ext.LastIndexOf(".");
                                ext = idx != -1 ? ext.Remove(0, idx) : ".jpg";
                                var pictureName = img_name.ToString() + ext;

                                content = content.Replace(imageSrc, Path.Combine(advName, pictureName));
                                wc.DownloadFile(imageSrc, Path.Combine(path, pictureName));
                                img_name++;
                            }
                            catch (Exception ex)
                            {
                                General.WriteLog(ex.Message);
                            }
                        }
                    }
                    nodes = doc.DocumentNode.SelectNodes("//*[href]");
                    if (nodes != null)
                    {
                        var nodesArray = nodes.ToArray();
                        foreach (var node in nodesArray)
                        {
                            var value = node.Attributes["href"].Value;
                            if (!value.StartsWith("http://") && !value.StartsWith("https://"))
                            {
                                var newValue = value;
                                if (newValue.StartsWith("/"))
                                {
                                    newValue.Remove(0, 1);
                                }
                                content = content.Replace(value, "https://www.farpost.ru/" + newValue);
                            }
                        }
                    }

                    var htmled = nlink + ".html";
                    File.WriteAllText(htmled, content, Encoding.UTF8);
                    FileInfo fileInfo = new FileInfo(htmled);
                    string   newname;
                    if (fileInfo.Length <= 25600)
                    {
                        newname = nlink + "_udalen.html";
                        File.Move(htmled, newname);
                    }
                    _db.ChangeAdvNLink(id, htmled);
                    General.Delay();
                    i++;
                }
                _db.Close();
                Invoke(new Action(() =>
                {
                    statusLabel.Text      = STATUS_BAR_DEFAULT;
                    uploadButton.Enabled  = true;
                    exploreButton.Enabled = true;
                    parseButton.Enabled   = true;
                    exportButton.Enabled  = true;
                    textBox2.Enabled      = true;
                    stopButton.Enabled    = false;
                    fromBox.Enabled       = true;
                    toBox.Enabled         = true;
                }));
                service.Dispose();
                browser.Dispose();
            }
        }
Example #10
0
        public string FTP_Cowlitz(string streetno, string direction, string streetname, string streettype, string parcelNumber, string ownername, string searchType, string orderNumber, string directParcel, string unitnumber)
        {
            GlobalClass.global_orderNo             = orderNumber;
            HttpContext.Current.Session["orderNo"] = orderNumber;
            GlobalClass.global_parcelNo            = parcelNumber;
            List <string> mcheck = new List <string>();

            string StartTime = "", AssessmentTime = "", TaxTime = "", CitytaxTime = "", LastEndTime = "";

            //driver = new c();
            //driver = new PhantomJSDriver();

            //var option = new ChromeOptions();
            //option.AddArgument("No-Sandbox");

            var driverService = PhantomJSDriverService.CreateDefaultService();

            driverService.HideCommandPromptWindow = true;
            //  using (driver = new ChromeDriver())
            using (driver = new PhantomJSDriver())
            {
                try
                {
                    StartTime = DateTime.Now.ToString("HH:mm:ss");

                    driver.Navigate().GoToUrl("http://www.cowlitzinfo.net/applications/cowlitzassessorparcelsearch/Default.aspx");
                    Thread.Sleep(3000);


                    if (searchType == "titleflex")
                    {
                        string address = "";
                        if (direction != "")
                        {
                            address = streetno + " " + streetname + " " + direction;
                        }
                        else
                        {
                            address = streetno + " " + streetname;
                        }
                        gc.TitleFlexSearch(orderNumber, parcelNumber, ownername, address.Trim(), "WA", "Cowlitz");
                        if ((HttpContext.Current.Session["TitleFlex_Search"] != null && HttpContext.Current.Session["TitleFlex_Search"].ToString() == "Yes"))
                        {
                            driver.Quit();
                            return("MultiParcel");
                        }
                        else if (HttpContext.Current.Session["titleparcel"].ToString() == "")
                        {
                            HttpContext.Current.Session["Cowlitz_Zero"] = "Zero";
                            driver.Quit();
                            return("No Data Found");
                        }
                        parcelNumber = HttpContext.Current.Session["titleparcel"].ToString().Replace("-", "");
                        searchType   = "parcel";
                    }


                    if (searchType == "address")
                    {
                        driver.FindElement(By.XPath("//*[@id='address_input_street_number']")).Click();
                        driver.FindElement(By.XPath("//*[@id='address_input_street_number']")).SendKeys(streetno);

                        driver.FindElement(By.XPath("//*[@id='address_input_street_name']")).Click();
                        driver.FindElement(By.XPath("//*[@id='address_input_street_name']")).SendKeys(streetname);

                        try
                        {
                            driver.FindElement(By.XPath("//*[@id='address_input_street_direction']")).SendKeys(direction);
                        }
                        catch
                        { }

                        gc.CreatePdf_WOP(orderNumber, "Address Search", driver, "WA", "Cowlitz");
                        driver.FindElement(By.Id("submit_input")).SendKeys(Keys.Enter);
                        Thread.Sleep(12000);
                        gc.CreatePdf_WOP(orderNumber, "Address Search Result", driver, "WA", "Cowlitz");

                        ChkMultiParcel = driver.FindElement(By.XPath("//*[@id='search-filter']/figure")).Text.Replace("\r\n", "");

                        if (ChkMultiParcel == "Search Results:1Sort By ")
                        {
                            driver.FindElement(By.XPath("//*[@id='properties_section']/div/a/div/div/div[2]/div/div[2]")).Click();
                            Thread.Sleep(10000);
                        }
                        else
                        {
                            try
                            {
                                int AddressmaxCheck = 0;

                                IWebElement         add_search   = driver.FindElement(By.XPath("//*[@id='properties_section']/div"));
                                IList <IWebElement> TRadd_search = add_search.FindElements(By.TagName("div"));
                                IList <IWebElement> TDadd_search;

                                foreach (IWebElement row in TRadd_search)
                                {
                                    if (AddressmaxCheck <= 25)
                                    {
                                        string addrerss1 = row.GetAttribute("class");
                                        if (addrerss1 == "info")
                                        {
                                            TDadd_search = row.FindElements(By.TagName("div"));
                                            if (TDadd_search.Count != 0)
                                            {
                                                parcelno = TDadd_search[0].Text;
                                                Pro_Id1  = TDadd_search[1].Text;
                                                Pro_Id1  = WebDriverTest.After(Pro_Id1, "Prop ID: ");
                                            }

                                            TDadd_search = row.FindElements(By.TagName("h3"));
                                            if (TDadd_search.Count != 0)
                                            {
                                                fulladdress = TDadd_search[0].Text;
                                            }

                                            multi_details = Pro_Id1 + "~" + fulladdress;
                                            gc.insert_date(orderNumber, parcelno, 815, multi_details, 1, DateTime.Now);
                                        }
                                        AddressmaxCheck++;
                                    }
                                }

                                if (TRadd_search.Count < 27)
                                {
                                    gc.CreatePdf_WOP(orderNumber, "Multi Address search result", driver, "WA", "Cowlitz");
                                    HttpContext.Current.Session["multiparcel_CowlitzWA"] = "Yes";
                                    driver.Quit();
                                    return("MultiParcel");
                                }
                                if (TRadd_search.Count >= 27)
                                {
                                    HttpContext.Current.Session["multiParcel_CowlitzWA_Multicount"] = "Maximum";
                                    driver.Quit();
                                    return("Maximum");
                                }
                            }
                            catch
                            { }
                        }

                        try
                        {
                            string Nodata = driver.FindElement(By.XPath("//*[@id='search-filter']/figure/h3")).Text;
                            if (Nodata.Contains("Search Results:"))
                            {
                                HttpContext.Current.Session["Cowlitz_Zero"] = "Zero";
                                driver.Quit();
                                return("No Data Found");
                            }
                        }
                        catch { }

                        //IWebElement add_search = driver.FindElement(By.XPath("//*[@id='ctl00_cphParcelSearch_gvSearchResults']/tbody"));
                        //IList<IWebElement> TRadd_search = add_search.FindElements(By.TagName("tr"));

                        //IList<IWebElement> TDadd_search;
                        //foreach (IWebElement row in TRadd_search)
                        //{
                        //    TDadd_search = row.FindElements(By.TagName("td"));
                        //    if (TRadd_search.Count > 2 && TDadd_search.Count != 0)
                        //    {
                        //        string straccount_no = TDadd_search[1].Text;
                        //        string parcel_no = TDadd_search[9].Text;
                        //        string Address_Details = TDadd_search[2].Text + " " + TDadd_search[3].Text + " " + TDadd_search[4].Text + " " + TDadd_search[5].Text + " " + TDadd_search[6].Text + " " + TDadd_search[7].Text;

                        //        gc.insert_date(orderNumber, parcel_no, 815, straccount_no + "~" + Address_Details, 1, DateTime.Now);
                        //    }
                        //    if (TRadd_search.Count == 2)
                        //    {
                        //        driver.FindElement(By.XPath("//*[@id='ctl00_cphParcelSearch_gvSearchResults']/tbody/tr[2]/td[1]/a")).SendKeys(Keys.Enter);
                        //        Thread.Sleep(5000);
                        //        break;
                        //    }
                        //}
                        //if (TRadd_search.Count < 27 && TRadd_search.Count > 2)
                        //{
                        //    gc.CreatePdf_WOP(orderNumber, "Multi Address search result", driver, "WA", "Cowlitz");
                        //    HttpContext.Current.Session["multiparcel_CowlitzWA"] = "Yes";
                        //    driver.Quit();
                        //    return "MultiParcel";
                        //}
                        //if (TRadd_search.Count >= 27 && TRadd_search.Count > 2)
                        //{
                        //    HttpContext.Current.Session["multiParcel_CowlitzWA_Multicount"] = "Maximum";
                        //    driver.Quit();
                        //    return "Maximum";
                        //}
                    }

                    if (searchType == "parcel")
                    {
                        driver.FindElement(By.Id("radSearchType_1")).Click();
                        Thread.Sleep(2000);

                        driver.FindElement(By.XPath("//*[@id='parcel_input']")).Click();
                        driver.FindElement(By.XPath("//*[@id='parcel_input']")).SendKeys(parcelNumber);
                        gc.CreatePdf(orderNumber, parcelNumber, "Parcel search", driver, "WA", "Cowlitz");
                        driver.FindElement(By.XPath("//*[@id='submit_input']")).SendKeys(Keys.Enter);
                        gc.CreatePdf(orderNumber, parcelNumber, "Parcel search result", driver, "WA", "Cowlitz");
                        Thread.Sleep(2000);

                        driver.FindElement(By.XPath("//*[@id='properties_section']/div/div/div/div[1]/a")).SendKeys(Keys.Enter);
                        Thread.Sleep(12000);

                        try
                        {
                            string Nodata = driver.FindElement(By.XPath("//*[@id='search-filter']/figure/h3")).Text;
                            if (Nodata.Contains("Search Results:"))
                            {
                                HttpContext.Current.Session["Cowlitz_Zero"] = "Zero";
                                driver.Quit();
                                return("No Data Found");
                            }
                        }
                        catch { }
                    }

                    try
                    {
                        // Property Details
                        Parcel_Id     = driver.FindElement(By.XPath("//*[@id='general_property_info']/dl/dd[1]")).Text;
                        Pro_Id        = driver.FindElement(By.XPath("//*[@id='general_property_info']/dl/dd[2]")).Text;
                        Jurisdiction  = driver.FindElement(By.XPath("//*[@id='general_property_info']/dl/dd[3]")).Text;
                        Acres         = driver.FindElement(By.XPath("//*[@id='general_property_info']/dl/dd[4]")).Text;
                        Township      = driver.FindElement(By.XPath("//*[@id='general_property_info']/dl/dd[7]")).Text;
                        Pro_Use       = driver.FindElement(By.XPath("//*[@id='general_property_info']/dl/dd[8]")).Text;
                        Neighberhood  = driver.FindElement(By.XPath("//*[@id='general_property_info']/dl/dd[9]")).Text;
                        Tax_Code      = driver.FindElement(By.XPath("//*[@id='general_property_info']/dl/dd[10]")).Text;
                        Exemptions    = driver.FindElement(By.XPath("//*[@id='general_property_info']/dl/dd[11]")).Text;
                        Leavy_Rate    = driver.FindElement(By.XPath("//*[@id='general_property_info']/dl/dt[12]")).Text;
                        Leavy_Rate    = WebDriverTest.Between(Leavy_Rate, "Rate = ", ")");
                        Primary_Owner = driver.FindElement(By.XPath("//*[@id='owner_info']/dl/dd[1]")).Text;
                        Address1      = driver.FindElement(By.XPath("//*[@id='owner_info']/dl/dd[2]")).Text;
                        Address2      = driver.FindElement(By.XPath("//*[@id='owner_info']/dl/dd[3]")).Text;

                        Address    = Address1 + " " + Address2;
                        Year_Built = driver.FindElement(By.XPath("//*[@id='property_detail_info']/dl/dd[1]")).Text;

                        gc.CreatePdf(orderNumber, parcelNumber, "Property Details", driver, "WA", "Cowlitz");
                        propertydetails = Primary_Owner + "~" + Address + "~" + Pro_Id + "~" + Jurisdiction + "~" + Acres + "~" + Township + "~" + Pro_Use + "~" + Neighberhood + "~" + Tax_Code + "~" + Exemptions + "~" + Leavy_Rate + "~" + Year_Built;
                        gc.insert_date(orderNumber, Parcel_Id, 763, propertydetails, 1, DateTime.Now);

                        //Assessment Details

                        IWebElement         AssessmentTB = driver.FindElement(By.XPath("//*[@id='assess_value_table']/table/tbody"));
                        IList <IWebElement> AssessmentTR = AssessmentTB.FindElements(By.TagName("tr"));
                        IList <IWebElement> AssessmentTD;

                        foreach (IWebElement Assessment in AssessmentTR)
                        {
                            AssessmentTD = Assessment.FindElements(By.TagName("td"));
                            if (AssessmentTD.Count != 0)
                            {
                                Asse_Year      = AssessmentTD[0].Text;
                                TaxPay_year    = AssessmentTD[1].Text;
                                Land_Value     = AssessmentTD[2].Text;
                                Impr_Value     = AssessmentTD[3].Text;
                                Totl_AsseValue = AssessmentTD[4].Text;
                                Notice_Value   = AssessmentTD[5].Text;

                                Assessment_details = Asse_Year + "~" + TaxPay_year + "~" + Land_Value + "~" + Impr_Value + "~" + Totl_AsseValue + "~" + Notice_Value;
                                gc.insert_date(orderNumber, Parcel_Id, 765, Assessment_details, 1, DateTime.Now);
                            }
                        }

                        gc.CreatePdf(orderNumber, parcelNumber, "Assessment Details", driver, "WA", "Cowlitz");

                        //Tax Payment Details

                        IWebElement         TaxPaymentTB = driver.FindElement(By.XPath("//*[@id='tax_value_table']/table/tbody"));
                        IList <IWebElement> TaxPaymentTR = TaxPaymentTB.FindElements(By.TagName("tr"));
                        IList <IWebElement> TaxPaymentTD;

                        foreach (IWebElement TaxPayment in TaxPaymentTR)
                        {
                            TaxPaymentTD = TaxPayment.FindElements(By.TagName("td"));
                            if (TaxPaymentTD.Count != 0)
                            {
                                Tax_Year     = TaxPaymentTD[0].Text;
                                Stmt_Id      = TaxPaymentTD[1].Text;
                                Taxes        = TaxPaymentTD[2].Text;
                                Assesments   = TaxPaymentTD[3].Text;
                                Totl_Charges = TaxPaymentTD[4].Text;
                                Totl_Paid    = TaxPaymentTD[5].Text;
                                Totl_Due     = TaxPaymentTD[6].Text;

                                TaxPayment_details = Tax_Year + "~" + Stmt_Id + "~" + Taxes + "~" + Assesments + "~" + Totl_Charges + "~" + Totl_Paid + "~" + Totl_Due;
                                gc.insert_date(orderNumber, Parcel_Id, 773, TaxPayment_details, 1, DateTime.Now);
                            }
                        }

                        //Pdf download
                        IWebElement         Receipttable    = driver.FindElement(By.XPath("//*[@id='tax_value_table']/table/tbody"));
                        IList <IWebElement> ReceipttableRow = Receipttable.FindElements(By.TagName("tr"));
                        int rowcount = ReceipttableRow.Count;

                        for (int p = 1; p <= rowcount; p++)
                        {
                            if (p < 4)
                            {
                                string Parent_Window1 = driver.CurrentWindowHandle;

                                driver.FindElement(By.XPath("//*[@id='tax_value_table']/table/tbody/tr[" + p + "]/td[10]/a")).Click();
                                Thread.Sleep(10000);


                                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                                driver.SwitchTo().Window(driver.WindowHandles.Last());
                                Thread.Sleep(4000);



                                try
                                {
                                    var chromeOptions     = new ChromeOptions();
                                    var downloadDirectory = ConfigurationManager.AppSettings["AutoPdf"];
                                    chromeOptions.AddUserProfilePreference("download.default_directory", downloadDirectory);
                                    chromeOptions.AddUserProfilePreference("download.prompt_for_download", false);
                                    chromeOptions.AddUserProfilePreference("disable-popup-blocking", true);
                                    chromeOptions.AddUserProfilePreference("plugins.always_open_pdf_externally", true);
                                    var chDriver = new ChromeDriver(chromeOptions);
                                    Array.ForEach(Directory.GetFiles(@downloadDirectory), File.Delete);
                                    chDriver.Navigate().GoToUrl(driver.Url);
                                    Thread.Sleep(8000);

                                    //PopUp
                                    try
                                    {
                                        chDriver.SwitchTo().Alert().Accept();
                                        Thread.Sleep(1000);
                                    }
                                    catch
                                    { }
                                    IWebElement         ISpan12 = chDriver.FindElement(By.Id("PdfDialog_PdfDownloadLink"));
                                    IJavaScriptExecutor js12    = chDriver as IJavaScriptExecutor;
                                    js12.ExecuteScript("arguments[0].click();", ISpan12);
                                    Thread.Sleep(5000);

                                    chDriver.FindElement(By.Id("PdfDialog_download")).Click();
                                    Thread.Sleep(20000);

                                    string fileName1 = latestfilename();
                                    Thread.Sleep(2000);
                                    gc.AutoDownloadFile(orderNumber, Parcel_Id, "Cowlitz", "WA", fileName1);
                                    chDriver.Quit();
                                }
                                catch { }

                                driver.SwitchTo().Window(Parent_Window1);
                                Thread.Sleep(2000);
                            }
                        }

                        //Tax Authority
                        driver.FindElement(By.XPath("//*[@id='top']/nav/ul/li[2]/a")).Click();
                        Thread.Sleep(2000);

                        //driver.SwitchTo().Window(driver.WindowHandles.Last());
                        //Thread.Sleep(2000);

                        Tax_Authority = driver.FindElement(By.XPath("//*[@id='address']")).Text;
                        Tax_Authority = WebDriverTest.Between(Tax_Authority, "Address", "Option 1").Replace("\r\n", "");

                        Taxauthority_Details = Tax_Authority;
                        gc.insert_date(orderNumber, Parcel_Id, 780, Taxauthority_Details, 1, DateTime.Now);
                    }
                    catch
                    { }

                    //IWebElement parcel_id = driver.FindElement(By.Id("ctl00_cphParcelSearch_txtParcel"));
                    //string Parcel_Id = parcel_id.GetAttribute("value");
                    //gc.CreatePdf(orderNumber, Parcel_Id, "Property Details", driver, "WA", "Cowlitz");
                    //IWebElement account_no = driver.FindElement(By.XPath("//*[@id='ctl00_cphParcelSearch_lnkAccount']"));
                    //string Account_No = account_no.Text;
                    //IWebElement jurisdiction = driver.FindElement(By.XPath("//*[@id='ctl00_cphParcelSearch_txtJurisdiction']"));
                    //string Jurisdiction = jurisdiction.GetAttribute("value");
                    //IWebElement owner_name = driver.FindElement(By.XPath("//*[@id='ctl00_cphParcelSearch_txtOwner']"));
                    //string Owner_Name = owner_name.GetAttribute("value");
                    //IWebElement mailing_address1 = driver.FindElement(By.XPath("//*[@id='ctl00_cphParcelSearch_txtAddress1']"));
                    //string Mailing_Address1 = mailing_address1.GetAttribute("value");
                    //IWebElement mailing_address2 = driver.FindElement(By.XPath("//*[@id='ctl00_cphParcelSearch_txtAddress2']"));
                    //string Mailing_Address2 = mailing_address2.GetAttribute("value");
                    //IWebElement tax_district = driver.FindElement(By.XPath("//*[@id='ctl00_cphParcelSearch_lnkTaxDistrict']"));
                    //string Tax_District = tax_district.Text;
                    //IWebElement neighbor_hood = driver.FindElement(By.XPath("//*[@id='ctl00_cphParcelSearch_txtNeighborhood']"));
                    //string Neighbor_Hood = neighbor_hood.GetAttribute("value");
                    //IWebElement levy_rate = driver.FindElement(By.XPath("//*[@id='ctl00_cphParcelSearch_txtLevyRate']"));
                    //string Levy_Rate = levy_rate.GetAttribute("value");
                    //IWebElement legal_desc = driver.FindElement(By.XPath("//*[@id='ctl00_cphParcelSearch_txtLegalDescr']"));
                    //string Legal_Desc = legal_desc.GetAttribute("value");
                    //IWebElement property_address = driver.FindElement(By.XPath("//*[@id='ctl00_cphParcelSearch_txtSitus']"));
                    //string Property_Address = property_address.GetAttribute("value");
                    //string propertydetails = Account_No + "~" + Jurisdiction + "~" + Owner_Name + "~" + Mailing_Address1 + Mailing_Address2 + "~" + Legal_Desc + "~" + Property_Address + "~" + Tax_District + "~" + Neighbor_Hood + "~" + Levy_Rate;
                    //gc.insert_date(orderNumber, Parcel_Id, 763, propertydetails, 1, DateTime.Now);

                    // Assessment Details table

                    //IWebElement tbmulti = driver.FindElement(By.XPath("//*[@id='ctl00_cphParcelSearch_tblAssessmentInformation']/tbody"));
                    //IList<IWebElement> TRmulti = tbmulti.FindElements(By.TagName("tr"));

                    //IList<IWebElement> TDmulti;
                    //foreach (IWebElement row in TRmulti)
                    //{

                    //    TDmulti = row.FindElements(By.TagName("td"));
                    //    if (TDmulti.Count == 7 && !row.Text.Contains("Assessment\r\nYear"))
                    //    {
                    //        string multi1 = TDmulti[0].Text + "~" + TDmulti[1].Text + "~" + TDmulti[2].Text + "~" + TDmulti[3].Text + "~" + TDmulti[4].Text + "~" + TDmulti[5].Text;
                    //        gc.insert_date(orderNumber, Parcel_Id, 765, multi1, 1, DateTime.Now);
                    //    }
                    //}

                    //  Payment History Table
                    //string currenturl = "";
                    //driver.FindElement(By.XPath("//*[@id='ctl00_cphParcelSearch_lnkbtnTransactionHistoricalValues']")).SendKeys(Keys.Enter);
                    //Thread.Sleep(5000);
                    //gc.CreatePdf(orderNumber, Parcel_Id, "TaxPaymentHistory", driver, "WA", "Cowlitz");
                    //try
                    //{
                    //    currenturl = driver.CurrentWindowHandle;
                    //    driver.FindElement(By.XPath("//*[@id='ctl00_cphParcelSearch_tblTransactionValues']/tbody/tr[3]/td[9]/a")).SendKeys(Keys.Enter);
                    //    Thread.Sleep(5000);

                    //    driver.SwitchTo().Window(driver.WindowHandles.Last());

                    //    IWebElement tbDelinq = driver.FindElement(By.XPath("//*[@id='ctl00_cphParcelSearch_tblTrxDetail']/tbody"));
                    //    IList<IWebElement> TRDelinq = tbDelinq.FindElements(By.TagName("tr"));

                    //    IList<IWebElement> TDDelinq;
                    //    foreach (IWebElement row in TRDelinq)
                    //    {

                    //        TDDelinq = row.FindElements(By.TagName("td"));
                    //        if (TDDelinq.Count == 5 && !row.Text.Contains("Assess\r\nYear") && !row.Text.Contains("Total Tax"))
                    //        {
                    //            string Delinq = TDDelinq[0].Text + "~" + TDDelinq[1].Text + "~" + TDDelinq[2].Text + "~" + TDDelinq[3].Text + "~" + TDDelinq[4].Text;
                    //            gc.insert_date(orderNumber, Parcel_Id, 817, Delinq, 1, DateTime.Now);
                    //        }

                    //        if (TDDelinq.Count == 5 && row.Text.Contains("Total Tax") && !row.Text.Contains("Assess\r\nYear"))
                    //        {
                    //            string Delinq = TDDelinq[3].Text + "~" + "~" + "~" + "~" + TDDelinq[4].Text;
                    //            gc.insert_date(orderNumber, Parcel_Id, 817, Delinq, 1, DateTime.Now);
                    //        }
                    //    }


                    //}
                    //catch (Exception ex)
                    //{

                    //}
                    //driver.SwitchTo().Window(currenturl);
                    //List<string> TaxYearDetails = new List<string>();
                    //List<string> TaxBillDetails = new List<string>();
                    //IWebElement tbmulti1 = driver.FindElement(By.XPath("//*[@id='ctl00_cphParcelSearch_tblTransactionValues']/tbody"));
                    //IList<IWebElement> TRmulti1 = tbmulti1.FindElements(By.TagName("tr"));
                    //IList<IWebElement> TDmulti1;
                    //foreach (IWebElement row in TRmulti1)
                    //{
                    //    TDmulti1 = row.FindElements(By.TagName("td"));
                    //    if ((TDmulti1.Count == 9 || TDmulti1.Count == 8) && !(row.Text.Contains("Assessment\r\nYear")))
                    //    {
                    //        string multi2 = TDmulti1[0].Text + "~" + TDmulti1[1].Text + "~" + TDmulti1[2].Text + "~" + TDmulti1[3].Text + "~" + TDmulti1[4].Text + "~" + TDmulti1[5].Text + "~" + TDmulti1[6].Text;

                    //        gc.insert_date(orderNumber, Parcel_Id, 773, multi2, 1, DateTime.Now);

                    //        if (TDmulti1.Count != 0 && TaxYearDetails.Count < 3)
                    //        {
                    //            IWebElement IYear = TDmulti1[1].FindElement(By.TagName("a"));
                    //            string strYear = IYear.GetAttribute("href");
                    //            TaxYearDetails.Add(strYear);
                    //        }
                    //        if (TDmulti1.Count != 0 && TaxBillDetails.Count < 3)
                    //        {
                    //            IWebElement ITaxBill = TDmulti1[7].FindElement(By.TagName("a"));
                    //            string strTaxBill = ITaxBill.GetAttribute("href");
                    //            TaxBillDetails.Add(strTaxBill);
                    //        }

                    //    }
                    //}

                    //int k = 0, l = 0;
                    //foreach (string yearURL in TaxYearDetails)
                    //{
                    //    driver.Navigate().GoToUrl(yearURL);

                    //    gc.CreatePdf(orderNumber, Parcel_Id, "Tax Detail" + k, driver, "WA", "Cowlitz");
                    //    k++;
                    //    try
                    //    {
                    //        IWebElement tbmulti2 = driver.FindElement(By.XPath("//*[@id='ctl00_cphParcelSearch_tblTrxDetail']/tbody"));
                    //        IList<IWebElement> TRmulti2 = tbmulti2.FindElements(By.TagName("tr"));
                    //        IList<IWebElement> TDmulti2;
                    //        foreach (IWebElement Tax in TRmulti2)
                    //        {
                    //            TDmulti2 = Tax.FindElements(By.TagName("td"));
                    //            if ((TDmulti2.Count == 6) && !Tax.Text.Contains("Tax Detail") && !Tax.Text.Contains("Account"))
                    //            {
                    //                string taxing_authority = "Cowlitz County Treasurer 207 4th Ave. N.Kelso, WA 98626";
                    //                string multi3 = TDmulti2[0].Text + "~" + TDmulti2[1].Text + "~" + TDmulti2[2].Text + "~" + TDmulti2[3].Text + "~" + TDmulti2[4].Text + "~" + TDmulti2[5].Text;
                    //                string multi4 = multi3 + "~" + taxing_authority;
                    //                gc.insert_date(orderNumber, Parcel_Id, 780, multi4, 1, DateTime.Now);
                    //            }
                    //        }
                    //    }
                    //    catch { }
                    //}
                    //int j = 0;
                    //foreach (string billURL in TaxBillDetails)
                    //{
                    //    driver.Navigate().GoToUrl(billURL);
                    //    IWebElement Ibill = driver.FindElement(By.XPath("//*[@id='PageToolbar']"));
                    //    IList<IWebElement> TRmulti5 = Ibill.FindElements(By.TagName("a"));
                    //    IList<IWebElement> TDmulti5;
                    //    foreach (IWebElement Tax in TRmulti5)
                    //    {
                    //        TDmulti5 = Tax.FindElements(By.TagName("img"));
                    //        if (TDmulti5.Count != 0)
                    //        {
                    //            IWebElement itaxbill = TDmulti5[0];
                    //            string strtaxbill = itaxbill.GetAttribute("id");
                    //            if (strtaxbill.Contains("FullScreenButton"))
                    //            {

                    //                IJavaScriptExecutor js = driver as IJavaScriptExecutor;
                    //                js.ExecuteScript("arguments[0].click();", itaxbill);
                    //                Thread.Sleep(6000);
                    //            }

                    //        }
                    //    }
                    //    gc.CreatePdf(orderNumber, Parcel_Id, "TaxBill Download" + j, driver, "WA", "Cowlitz");
                    //    try
                    //    {
                    //        //gc.downloadfile(billURL, orderNumber, Parcel_Id, "Paid Bill" + j, "WA", "Cowlitz");
                    //    }
                    //    catch { }
                    //    j++;
                    //}

                    LastEndTime = DateTime.Now.ToString("HH:mm:ss");
                    gc.insert_TakenTime(orderNumber, "WA", "Cowlitz", StartTime, AssessmentTime, TaxTime, CitytaxTime, LastEndTime);

                    driver.Quit();
                    gc.mergpdf(orderNumber, "WA", "Cowlitz");
                    return("Data Inserted Successfully");
                }
                catch (Exception ex)
                {
                    driver.Quit();
                    GlobalClass.LogError(ex, orderNumber);
                    throw ex;
                }
            }
        }
        bool LoginRCB(string Cnpj, string UserRcb, string PassRcb)
        {
            WebDriverExtensions.KillDriversAndBrowsers();
            ChromeOptions options = new ChromeOptions();/*FirefoxDriver(@"c:\");*/

            options.AddArguments("no-sandbox");
            options.AddArguments("disable-extensions");
            options.AddAdditionalCapability("useAutomationExtension", false);
            //string chromePath = @"C:\ProgramData\Microsoft\AppV\Client\Integration\8F06C98E - CE78 - 4FCF - B8E3 - 68C443159F3F\Root\VFS\ProgramFilesX86\Google\Chrome\Application\chrome.exe";
            driver = new ChromeDriver(options);

            driver.Url = "https://negocios.santander.com.br/RcbWeb";
            driver.Manage().Window.Maximize();
            driver.Navigate().Refresh();
            WebDriverExtensions.WaitForPageLoad(driver);

            WebDriverWait wait   = new WebDriverWait(driver, TimeSpan.FromSeconds(40));
            WebDriverWait wait1  = new WebDriverWait(driver, TimeSpan.FromSeconds(1));
            WebDriverWait wait5  = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
            WebDriverWait wait10 = new WebDriverWait(driver, TimeSpan.FromSeconds(10));


            wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.Id("_id35:_id48")));
            driver.FindElement(By.Id("_id35:_id48")).SendKeys(Cnpj);
            Thread.Sleep(200);

            wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.Id("_id35:_id52")));
            driver.FindElement(By.Id("_id35:_id52")).SendKeys(UserRcb);
            Thread.Sleep(200);

            wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.Name("_id35:_id56")));
            driver.FindElement(By.Name("_id35:_id56")).SendKeys(PassRcb);
            Thread.Sleep(200);

            //js.ExecuteScript("iceSubmit(form,this,event);return false;");
            SendKeys.SendWait("{ENTER}");

            try
            {
                // continua se estiver ja logado

                wait5.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.Id("_id411:_id431")));
                IWebElement btconfirmar = driver.FindElement(By.Id("_id411:_id431"));
                btconfirmar.Click();
            }
            catch { }

            try
            {
                //erro usuario ou senha
                wait5.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.Name("_id70:_id95")));
                IWebElement btok = driver.FindElement(By.Name("_id70:_id95"));
                Thread.Sleep(500);
                driver.Close();
                Logger.LoginRCBError();

                DialogResult result2 = MessageBox.Show("ERRO SENHA NÃO CONFERE.", "Facilita", MessageBoxButtons.OK, MessageBoxIcon.Error);

                //Thread.Sleep(500);
                return(false);
            }
            catch { return(true); }
        }
Example #12
0
        static void Main(string[] args)
        {
            IWebDriver          driver        = new ChromeDriver();
            ChromeDriverService Chrome_Servis = ChromeDriverService.CreateDefaultService();
            ChromeOptions       Chrome_Ayar   = new ChromeOptions();

            string[] mobileTarayici =
            {
                //"Galaxy S5",
                //"iPhone 5/SE",
                //"iPhone 6/7/8",
                "iPhone 6/7/8 Plus",
                "iPhone X"
                //"iPad",
                //"iPad Pro"
            };
            Random rand_tarayici  = new Random();
            int    index_tarayici = rand_tarayici.Next(mobileTarayici.Length);

            Chrome_Ayar.EnableMobileEmulation(mobileTarayici[index_tarayici]);


            // Gizli sekme
            Chrome_Ayar.AddArguments("--incognito");
            Chrome_Ayar.AddArgument("disable-infobars");
            Chrome_Ayar.AddArguments("--allow-file-access");
            Chrome_Ayar.AddArgument("--disable-web-security");
            Chrome_Ayar.AddArgument("--allow-running-insecure-content");

            driver = new ChromeDriver(Chrome_Servis, Chrome_Ayar);



            driver.Navigate().GoToUrl("http://localhost/google-login/index.php");
            Thread.Sleep(2000);

            driver.FindElement(By.XPath("//a")).Click();
            Thread.Sleep(2000);


            driver.FindElement(By.XPath("//input[@name='identifier']")).SendKeys("");
            Thread.Sleep(5000);


            driver.FindElement(By.XPath("//div[@id='identifierNext']")).Click();
            Thread.Sleep(5000);



            driver.FindElement(By.XPath("//input[@name='password']")).SendKeys("");
            Thread.Sleep(5000);


            driver.FindElement(By.XPath("//div[@id='passwordNext']")).Click();
            Thread.Sleep(5000);


            driver.Navigate().GoToUrl("https://www.youtube.com/upload");

            /*IWebElement element = Chrome_Sekme.FindElement(By.XPath("//div[@class='XX1Wc']//div//input[@class='tb_sK']"));
             * element.SendKeys(filePath);*/
        }
Example #13
0
        public async Task GivenPatientIdAndSmartAppUrl_WhenLaunchingApp_LaunchSequenceAndSignIn()
        {
            // There is no remote FHIR server. Skip test
            if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable($"TestEnvironmentUrl{Constants.TestEnvironmentVariableVersionSuffix}")))
            {
                return;
            }

            var options = new ChromeOptions();

            options.AddArgument("--headless");
            options.AddArgument("--disable-gpu");
            options.AddArgument("--incognito");

            // TODO: We are accepting insecure certs to make it practical to run on build systems. A valid cert should be on the build system.
            options.AcceptInsecureCertificates = true;

            using FhirResponse <Patient> response = await _fixture.TestFhirClient.CreateAsync(Samples.GetDefaultPatient ().ToPoco <Patient>());

            Assert.Equal(HttpStatusCode.Created, response.StatusCode);
            Patient patient = response.Resource;

            // VSTS Hosted agents set the ChromeWebDriver Env, locally that is not the case
            // https://docs.microsoft.com/en-us/azure/devops/pipelines/test/continuous-test-selenium?view=vsts#decide-how-you-will-deploy-and-test-your-app
            if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("ChromeWebDriver")))
            {
                Environment.SetEnvironmentVariable("ChromeWebDriver", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
            }

            using (var driver = new ChromeDriver(Environment.GetEnvironmentVariable("ChromeWebDriver"), options))
            {
                // TODO: This parameter has been set (too) conservatively to ensure that content
                //       loads on build machines. Investigate if one could be less sensitive to that.
                driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);

                void Advance()
                {
                    while (true)
                    {
                        try
                        {
                            var button = driver.FindElementById("idSIButton9");
                            if (button.Enabled)
                            {
                                button.Click();
                                return;
                            }
                        }
                        catch (StaleElementReferenceException)
                        {
                        }
                    }
                }

                driver.Navigate().GoToUrl(_fixture.SmartLauncherUrl);

                var patientElement = driver.FindElement(By.Id("patient"));
                patientElement.SendKeys(patient.Id);

                var launchButton = driver.FindElement(By.Id("launchButton"));
                if (launchButton.Enabled)
                {
                    launchButton.Click();
                }

                var testUserName     = TestUsers.AdminUser.UserId;
                var testUserPassword = TestUsers.AdminUser.Password;

                // Launcher opens a new tab, switch to it
                driver.SwitchTo().Window(driver.WindowHandles[1]);

                int waitCount = 0;
                while (!driver.Url.StartsWith($"https://login.microsoftonline.com"))
                {
                    Thread.Sleep(TimeSpan.FromMilliseconds(1000));
                    Assert.InRange(waitCount++, 0, 10);
                }

                driver.FindElementByName("loginfmt").SendKeys(testUserName);
                Advance();

                // We need to add some delay before we start entering the password (to make sure
                // the element is available and we do not miss sending some keys).
                Thread.Sleep(TimeSpan.FromMilliseconds(1000));

                driver.FindElementByName("passwd").SendKeys(testUserPassword);
                Advance();

                // Consent, should only be done if we can find the button
                try
                {
                    // Sleep in case a light box is shown.
                    Thread.Sleep(TimeSpan.FromMilliseconds(1000));
                    var button = driver.FindElementById("idSIButton9");
                    Advance();
                }
                catch (NoSuchElementException)
                {
                    // Nothing to do, we are assuming that we are at the SMART App screen.
                }

                var tokenResponseElement = driver.FindElement(By.Id("tokenresponsefield"));
                var tokenResponseText    = tokenResponseElement.GetAttribute("value");

                // It can take some time for the token to appear, we will wait
                waitCount = 0;
                while (string.IsNullOrWhiteSpace(tokenResponseText))
                {
                    Thread.Sleep(TimeSpan.FromMilliseconds(1000));
                    tokenResponseText = tokenResponseElement.GetAttribute("value");
                    Assert.InRange(waitCount++, 0, 10);
                }

                // Check the token response, should have right audience
                var tokenResponse = JObject.Parse(tokenResponseElement.GetAttribute("value"));
                var jwtHandler    = new JwtSecurityTokenHandler();
                Assert.True(jwtHandler.CanReadToken(tokenResponse["access_token"].ToString()));
                var token = jwtHandler.ReadJwtToken(tokenResponse["access_token"].ToString());
                var aud   = token.Claims.Where(c => c.Type == "aud").ToList();
                Assert.Single(aud);
                var tokenAudience = aud.First().Value;
                Assert.Equal(Environment.GetEnvironmentVariable("TestEnvironmentUrl"), tokenAudience);

                // Check the patient
                var patientResponseElement = driver.FindElement(By.Id("patientfield"));
                var patientResource        = JObject.Parse(patientResponseElement.GetAttribute("value"));
                Assert.Equal(patient.Id, patientResource["id"].ToString());
            }
        }
        public string FTP_SanFrancisco(string address, string parcelNumber, string searchType, string orderNumber, string directParcel)
        {
            GlobalClass.global_orderNo             = orderNumber;
            HttpContext.Current.Session["orderNo"] = orderNumber;
            GlobalClass.global_parcelNo            = parcelNumber;

            string StartTime = "", AssessmentTime = "", TaxTime = "", CitytaxTime = "", LastEndTime = "";

            string     parceno = "-", property_address = "-", year_built = "-";
            string     Land_Value = "=", Building_Value = "-", Fixtures = "-", Personal_Property = "-";
            IWebDriver chdriver;
            var        driverService = PhantomJSDriverService.CreateDefaultService();

            driverService.HideCommandPromptWindow = true;
            //driver = new ChromeDriver();
            //driver = new PhantomJSDriver();
            using (driver = new PhantomJSDriver())
            {
                var option = new ChromeOptions();
                option.AddArgument("No-Sandbox");
                chdriver = new ChromeDriver(option);

                try
                {
                    StartTime = DateTime.Now.ToString("HH:mm:ss");

                    if (searchType == "titleflex")
                    {
                        string titleaddress = address;
                        gc.TitleFlexSearch(orderNumber, "", "", titleaddress.Trim(), "CA", "San Francisco");
                        if ((HttpContext.Current.Session["TitleFlex_Search"] != null && HttpContext.Current.Session["TitleFlex_Search"].ToString() == "Yes"))
                        {
                            driver.Quit();
                            return("MultiParcel");
                        }
                        else if (HttpContext.Current.Session["titleparcel"].ToString() == "")
                        {
                            HttpContext.Current.Session["Nodata_SanFrascisco"] = "Yes";
                            driver.Quit();
                            return("No Data Found");
                        }
                        parcelNumber = HttpContext.Current.Session["titleparcel"].ToString();
                        searchType   = "parcel";
                    }
                    chdriver.Navigate().GoToUrl("http://sfplanninggis.org/pim/");
                    if (searchType == "address")
                    {
                        //IWebElement iframeElement = driver.FindElement(By.XPath("/html/frameset/frame[1]"));
                        ////now use the switch command
                        //driver.SwitchTo().Frame(iframeElement);
                        //Thread.Sleep(3000);
                        chdriver.FindElement(By.Id("addressInput")).SendKeys(address.ToUpper());
                        Thread.Sleep(10000);
                        IWebElement         Iviewtax = chdriver.FindElement(By.XPath("//*[@id='Search-icon']"));
                        IJavaScriptExecutor js       = chdriver as IJavaScriptExecutor;
                        js.ExecuteScript("arguments[0].click();", Iviewtax);

                        Thread.Sleep(10000);
                        gc.CreatePdf_WOP(orderNumber, "Address Search", chdriver, "CA", "San Francisco");
                        //   gc.CreatePdf_WOP(orderNumber, "Address Search result", driver, "CA", "San Francisco");
                    }
                    if (searchType == "parcel")
                    {
                        if (HttpContext.Current.Session["titleparcel"] != null)
                        {
                            parcelNumber = HttpContext.Current.Session["titleparcel"].ToString();
                        }
                        if (HttpContext.Current.Session["titleparcel"] != null && (HttpContext.Current.Session["titleparcel"].ToString().Contains(".") || HttpContext.Current.Session["titleparcel"].ToString().Contains("-")))
                        {
                            parcelNumber = HttpContext.Current.Session["titleparcel"].ToString().Replace(".", "");
                        }

                        //1 driver.Navigate().GoToUrl("http://propertymap.sfplanning.org/");
                        //driver.Navigate().GoToUrl("http://sfplanninggis.org/pim/");
                        // IWebElement iframeElement = driver.FindElement(By.XPath("/html/frameset/frame"));
                        //now use the switch command
                        //driver.SwitchTo().Frame(iframeElement);
                        chdriver.FindElement(By.Id("addressInput")).SendKeys(parcelNumber);
                        Thread.Sleep(2000);
                        chdriver.FindElement(By.Id("Search-icon")).Click();
                        Thread.Sleep(2000);
                        gc.CreatePdf(orderNumber, parcelNumber, "Parcel search", chdriver, "CA", "San Francisco");
                        try
                        {
                            IWebElement INodata = chdriver.FindElement(By.XPath("/html/body/div[3]"));
                            if (INodata.Text.Contains("does not appear to be a valid"))
                            {
                                HttpContext.Current.Session["Nodata_SanFrascisco"] = "Yes";
                                driver.Quit();
                                return("No Data Found");
                            }
                        }
                        catch { }
                    }
                    try
                    {
                        IWebElement INodata = chdriver.FindElement(By.XPath("//*[@id='Report_DynamicContent_Property']/div[1]/div[3]"));
                        if (INodata.Text.Contains("no parcels at this location"))
                        {
                            HttpContext.Current.Session["Nodata_SanFrascisco"] = "Yes";
                            driver.Quit();
                            return("No Data Found");
                        }
                    }
                    catch { }

                    //Thread.Sleep(6000);
                    //driver.FindElement(By.Id("propertyButton")).SendKeys(Keys.Enter);
                    //Thread.Sleep(6000);
                    //property details
                    //chdriver.FindElement(By.LinkText("Assessor Summary")).Click();
                    //Thread.Sleep(2000);
                    try
                    {////*[@id="Report_DynamicContent_Property"]/div[1]/div[2]/div/div[2]/div[4]/a[1]
                        chdriver.FindElement(By.XPath("//*[@id='Report_DynamicContent_Property']/div[1]/div[2]/div/div[3]/div[4]/a[1]")).Click();
                        Thread.Sleep(2000);
                    }
                    catch { }
                    chdriver.SwitchTo().Window(chdriver.WindowHandles.Last());

                    //chdriver.FindElement(By.LinkText("Assessor Summary")).Click();
                    try
                    {
                        parceno          = chdriver.FindElement(By.XPath("//*[@id='modalContent']/div[1]/div/div[1]/div[2]")).Text.Trim();
                        property_address = chdriver.FindElement(By.XPath("//*[@id='modalContent']/div[1]/div/div[2]/div[2]")).Text;
                        year_built       = chdriver.FindElement(By.XPath("//*[@id='modalContent']/div[4]/div/div[8]/div[2]")).Text;
                        string Usetype      = chdriver.FindElement(By.XPath("//*[@id='modalContent']/div[4]/div/div[2]/div[4]")).Text;
                        string prop_details = property_address + "~ " + year_built + "~" + Usetype;
                        gc.insert_date(orderNumber, parceno, 72, prop_details, 1, DateTime.Now);
                    }
                    catch { }
                    try
                    {
                        //Assessment Details
                        Land_Value        = chdriver.FindElement(By.XPath("//*[@id='modalContent']/div[4]/div/div[2]/div[2]")).Text;
                        Building_Value    = chdriver.FindElement(By.XPath("//*[@id='modalContent']/div[4]/div/div[3]/div[2]")).Text;
                        Fixtures          = chdriver.FindElement(By.XPath("//*[@id='modalContent']/div[4]/div/div[4]/div[2]")).Text;
                        Personal_Property = chdriver.FindElement(By.XPath("//*[@id='modalContent']/div[4]/div/div[5]/div[2]")).Text;

                        string ass_details = Land_Value + "~ " + Building_Value + "~ " + Fixtures + "~ " + Personal_Property;
                        gc.insert_date(orderNumber, parceno, 73, ass_details, 1, DateTime.Now);
                        gc.CreatePdf_WOP(orderNumber, "Property details", chdriver, "CA", "San Francisco");
                        AssessmentTime = DateTime.Now.ToString("HH:mm:ss");
                    }
                    catch { }
                    chdriver.Quit();
                    //download bill
                    //driver.FindElement(By.ClassName("NoPrint")).SendKeys(Keys.Enter);
                    //driver.SwitchTo().Window(driver.WindowHandles.Last());
                    //Thread.Sleep(5000);
                    //IWebElement element = driver.FindElement(By.XPath("//*[@id='mapPrintOptions']/tbody/tr[1]/td[2]/button"));
                    //Actions actions = new Actions(driver);
                    //actions.MoveToElement(element).Click().Perform();
                    //Thread.Sleep(2000);
                    //string billurl = driver.Url;


                    //  CreatePdf_WOP(orderNumber, "Bill pdf");

                    //Tax Details
                    driver.Navigate().GoToUrl("https://ttxonlineportal.sfgov.org/content/San-Francisco-Forms-Portal/Residents/propertyTaxAndLicense.html");
                    // driver.Navigate().GoToUrl("c");
                    string block_num = "";
                    string lot_num   = "";
                    if (parceno.Count() == 8)
                    {
                        block_num = parceno.Substring(0, 4);
                        lot_num   = parceno.Substring(4, 3);
                    }
                    else if (parceno.Count() == 8)
                    {
                        block_num = parceno.Substring(0, 4);
                        lot_num   = parceno.Substring(4, 3);
                    }
                    else if (parceno.Count() == 7)
                    {
                        block_num = parceno.Substring(0, 4);
                        lot_num   = parceno.Substring(4, 3);
                    }

                    if (block_num.Trim() == "" && lot_num.Trim() == "")
                    {
                        string[] splitno = parceno.Split('-');
                        block_num = splitno[0];
                        lot_num   = splitno[1];
                        parceno   = parcelNumber;
                    }

                    driver.FindElement(By.Id("addressBlockNumber")).SendKeys(block_num);
                    driver.FindElement(By.Id("addressLotNumber")).SendKeys(lot_num);
                    gc.CreatePdf_WOP(orderNumber, "Tax details", driver, "CA", "San Francisco");
                    driver.FindElement(By.Id("submit")).SendKeys(Keys.Enter);
                    gc.CreatePdf_WOP(orderNumber, "Tax Details result", driver, "CA", "San Francisco");
                    Thread.Sleep(2000);
                    try
                    {
                        driver.FindElement(By.XPath("//*[@id='block-system-main']/div/div/article/div/div/div/div[3]/div/div/div[1]/ul/li[2]/a")).Click();
                        Thread.Sleep(3000);
                    }
                    catch { }
                    //string paymenthistory
                    //Bill_Type~Tax_Year~Installment~Bill~Total_Paid~Paid_Date
                    IWebElement         TBpayment_history = driver.FindElement(By.XPath("//*[@id='priorYearTaxTable']/tbody"));
                    IList <IWebElement> TRpayment_history = TBpayment_history.FindElements(By.TagName("tr"));
                    IList <IWebElement> TDpayment_history;

                    foreach (IWebElement row2 in TRpayment_history)
                    {
                        if (!row2.Text.Contains("There are no properties that match your search criteria"))
                        {
                            TDpayment_history = row2.FindElements(By.TagName("td"));
                            string paymenthistory = TDpayment_history[0].GetAttribute("innerText") + "~ " + TDpayment_history[1].GetAttribute("innerText") + "~ " + TDpayment_history[2].GetAttribute("innerText") + "~ " + TDpayment_history[4].GetAttribute("innerText") + "~ " + TDpayment_history[5].GetAttribute("innerText") + "~ " + TDpayment_history[6].GetAttribute("innerText");
                            gc.insert_date(orderNumber, parceno, 76, paymenthistory, 1, DateTime.Now);
                        }
                    }
                    //   gc.CreatePdf_WOP(orderNumber, "Payment History Details", driver, "CA", "San Francisco");

                    //Current property tax statements
                    string text = "";
                    string Property_Address = "-", Bill_Type = "-", Bill_Number = "-", Installment = "-", Due_Date = "-", Amount_Due = "-", Total_Due = "-";
                    driver.FindElement(By.XPath("//*[@id='block-system-main']/div/div/article/div/div/div/div[3]/div/div/div[1]/ul/li[1]/a")).SendKeys(Keys.Enter);
                    Thread.Sleep(3000);
                    IList <IWebElement> trc = driver.FindElements(By.XPath("//*[@id='taxTable']/tbody/tr"));
                    int trcount             = trc.Count();
                    if (trcount == 1)
                    {
                        try
                        {
                            IWebElement tr1 = driver.FindElement(By.XPath(" //*[@id='taxTable']/tbody/tr/td"));
                            text = driver.FindElement(By.XPath("//*[@id='taxTable']/tbody/tr/td")).Text;
                        }

                        catch { }
                        if (!text.Contains("There are no current property tax statements due at this time."))
                        {
                            try
                            {
                                Property_Address = driver.FindElement(By.XPath("//*[@id='taxTable']/tbody/tr/td[1]/div/div/h5[1]")).Text;
                                Bill_Type        = driver.FindElement(By.XPath("//*[@id='taxTable']/tbody/tr/td[1]/div/div/h4")).Text;
                                Bill_Number      = driver.FindElement(By.XPath("//*[@id='taxTable']/tbody/tr/td[2]/strong")).Text;
                                Installment      = driver.FindElement(By.XPath("//*[@id='taxTable']/tbody/tr/td[3]/strong")).Text;
                                Due_Date         = driver.FindElement(By.XPath("//*[@id='taxTable']/tbody/tr/td[4]/strong")).Text;
                                Amount_Due       = driver.FindElement(By.XPath("//*[@id='taxTable']/tbody/tr/td[5]/strong")).Text;
                                Total_Due        = driver.FindElement(By.XPath("//*[@id='taxTable']/tbody/tr/td[6]/strong")).Text;

                                string current_tax = Property_Address + "~ " + Bill_Type + "~ " + Bill_Number + "~ " + Installment + "~ " + Due_Date + "~ " + Amount_Due + "~ " + Total_Due;
                                gc.insert_date(orderNumber, parceno, 78, current_tax, 1, DateTime.Now);
                            }
                            catch { }
                            String Parent_Window = driver.CurrentWindowHandle;

                            IWebElement view = driver.FindElement(By.XPath("//*[@id='taxTable']/tbody/tr/td[1]/div/div/a/button"));
                            view.SendKeys(Keys.Enter);

                            try
                            {
                                driver.SwitchTo().Window(driver.WindowHandles.Last());
                                string url     = driver.Url;
                                string billpdf = outputPath + Bill_Number + "currenttax_bill.pdf";
                                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                                WebClient downloadpdf = new WebClient();
                                downloadpdf.DownloadFile(url, billpdf);
                            }
                            catch { }

                            //parent window
                            driver.SwitchTo().Window(Parent_Window);

                            string paybutton = driver.FindElement(By.XPath("//*[@id='taxTable']/tbody/tr/td[7]/button")).Text.Trim();
                            paybutton += paybutton + " ";

                            if (paybutton.Trim().Contains("Special Handling"))
                            {
                                HttpContext.Current.Session["SpecialHandling_SanFrancisco"] = "Yes";
                            }
                        }

                        gc.CreatePdf_WOP(orderNumber, "Current Property Tax Statements", driver, "CA", "San Francisco");
                    }

                    else
                    {
                        for (int i = 1; i <= trcount; i++)
                        {
                            try
                            {
                                Property_Address = driver.FindElement(By.XPath("//*[@id='taxTable']/tbody/tr[" + i + "]/td[1]/div/div/h5[1]")).Text;
                                Bill_Type        = driver.FindElement(By.XPath("//*[@id='taxTable']/tbody/tr[" + i + "]/td[1]/div/div/h4")).Text;
                                Bill_Number      = driver.FindElement(By.XPath("//*[@id='taxTable']/tbody/tr[" + i + "]/td[2]/strong")).Text;
                                Installment      = driver.FindElement(By.XPath("//*[@id='taxTable']/tbody/tr[" + i + "]/td[3]/strong")).Text;
                                Due_Date         = driver.FindElement(By.XPath("//*[@id='taxTable']/tbody/tr[" + i + "]/td[4]/strong")).Text;
                                Amount_Due       = driver.FindElement(By.XPath("//*[@id='taxTable']/tbody/tr[" + i + "]/td[5]/strong")).Text;
                                Total_Due        = driver.FindElement(By.XPath("//*[@id='taxTable']/tbody/tr[" + i + "]/td[6]/strong")).Text;

                                string current_tax = Property_Address + "~ " + Bill_Type + "~ " + Bill_Number + "~ " + Installment + "~ " + Due_Date + "~ " + Amount_Due + "~ " + Total_Due;
                                gc.insert_date(orderNumber, parceno, 78, current_tax, 1, DateTime.Now);
                            }
                            catch { }
                            String Parent_Window = driver.CurrentWindowHandle;

                            IWebElement view = driver.FindElement(By.XPath("//*[@id='taxTable']/tbody/tr[" + i + "]/td[1]/div/div/a/button"));

                            view.SendKeys(Keys.Enter);
                            try
                            {
                                driver.SwitchTo().Window(driver.WindowHandles.Last());
                                string url     = driver.Url;
                                string billpdf = outputPath + Bill_Number + "Propertycurrenttax_bill.pdf";
                                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                                WebClient downloadpdf = new WebClient();
                                downloadpdf.DownloadFile(url, billpdf);
                            }
                            catch (Exception e) { }
                            //parent window
                            driver.SwitchTo().Window(Parent_Window);

                            string paybutton = driver.FindElement(By.XPath("//*[@id='taxTable']/tbody/tr[" + i + "]/td[7]/button")).Text.Trim();
                            paybutton += paybutton + " ";

                            if (paybutton.Trim().Contains("Special Handling"))
                            {
                                HttpContext.Current.Session["SpecialHandling_SanFrancisco"] = "Yes";
                            }
                        }
                    }
                    gc.CreatePdf_WOP(orderNumber, "Current Property Tax Statements", driver, "CA", "San Francisco");
                    driver.FindElement(By.XPath("//*[@id='block-system-main']/div/div/article/div/div/div/div[3]/div/div/div[1]/ul/li[2]/a")).Click();
                    Thread.Sleep(3000);
                    gc.CreatePdf_WOP(orderNumber, "Payment History Details", driver, "CA", "San Francisco");

                    TaxTime = DateTime.Now.ToString("HH:mm:ss");

                    LastEndTime = DateTime.Now.ToString("HH:mm:ss");
                    gc.insert_TakenTime(orderNumber, "CA", "San Francisco", StartTime, AssessmentTime, TaxTime, CitytaxTime, LastEndTime);


                    driver.Quit();
                    HttpContext.Current.Session["titleparcel"] = null;
                    gc.mergpdf(orderNumber, "CA", "San Francisco");
                    return("Data Inserted Successfully");
                }
                catch (Exception ex)
                {
                    driver.Quit();
                    chdriver.Quit();
                    GlobalClass.LogError(ex, orderNumber);
                    throw ex;
                }
            }
        }
Example #15
0
        internal static void CreateInstagramProfiles(List <string> freeUsernames)
        {
            string[] arguments =
            {
                "--disable-extensions",
                "--profile-directory=Default",
                "--incognito",
                "--disable-plugins-discovery",
                "--start-maximized"
            };

            foreach (string username in freeUsernames)
            {
                Console.WriteLine($"Creating account: '{username}' with password: '******' ...");

                ChromeOptions options = new ChromeOptions();

                ChromeDriverService service = null;
                options.AddArguments(arguments);
                try
                {
                    service = ChromeDriverService.CreateDefaultService(@"chromedriver_win32");
                }
                catch (Exception)
                {
                    Console.WriteLine("ERROR: 'chromedriver_win32/chrome_driver.exe' not found!");
                    Console.WriteLine("Aborting...");
                    Thread.Sleep(6000);
                    Environment.Exit(2);
                }
                service.SuppressInitialDiagnosticInformation = true;
                service.HideCommandPromptWindow = true;

                ChromeDriver cd = new ChromeDriver(service, options);
                cd.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
                cd.Url = @"https://www.instagram.com/accounts/emailsignup/";
                cd.Navigate();

                int    uniqueNums  = Utils.GetRandomInt(10, 99);
                int    uniqueNums2 = Utils.GetRandomInt(24, 54);
                string fullName    = $"{Utils.GetRandomString(5)} {Utils.GetRandomString(7)}";

                IWebElement e = cd.FindElementByName("emailOrPhone");
                e.Click();
                e.SendKeys($"define{uniqueNums}telynotfa{uniqueNums2}[email protected]");
                Thread.Sleep(1000);

                e = cd.FindElementByName("fullName");
                e.Click();
                e.SendKeys(fullName);
                Thread.Sleep(1200);

                e = cd.FindElementByName("username");
                e.Click();
                e.SendKeys(username);
                Thread.Sleep(1300);

                e = cd.FindElementByName("password");
                e.Click();
                e.SendKeys(Utils.DefaultPassForNewAccounts);
                Thread.Sleep(1000);

                e = cd.FindElementByXPath(@"//*[@id=""react-root""]/section/main/div/article/div/div[1]/div/form/div[2]/div[2]");
                e.Click();
                Thread.Sleep(1100);

                e = cd.FindElementByXPath(@"//*[@id=""react-root""]/section/main/div/article/div/div[1]/div/form/div[7]/div/button");
                e.Click();
                Thread.Sleep(1200);

                // if we didnt pass the creation field by any reason, these ones will not exists
                try
                {
                    e = cd.FindElementByName("ageRadio");
                    e.Click();
                    Thread.Sleep(1300);

                    e = cd.FindElementByXPath(@"//html/body/div[3]/div/div[3]/div/button");
                    e.Click();
                }
                catch (Exception)
                {
                    Console.WriteLine($"{username} cannot be created! Try creating it manually.");
                    cd.Quit();
                    continue;
                }

                string[] lines =
                {
                    $"User: {username}",
                    $"Password: {Utils.DefaultPassForNewAccounts}",
                    $"Full name: {fullName}",
                    $"Email(fake): define{uniqueNums}telynotfa{uniqueNums2}[email protected]"
                };
                System.IO.File.WriteAllLines($"USER_{username}.txt", lines);

                Thread.Sleep(5000);

                cd.Quit();

                /// TODO create only 1 account for now
                break;
            }
        }
Example #16
0
        public static void RunScraper()
        {
            ChromeOptions option = new ChromeOptions();

            option.AddArgument("--headless");
            option.AddArgument("window-size=1200,1100");
            IWebDriver driver = new ChromeDriver(option);

            driver.Navigate().GoToUrl("https://finance.yahoo.com/");

            WebDriverWait waitLogin = new WebDriverWait(driver, TimeSpan.FromSeconds(60));

            waitLogin.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.Id("uh-signedin")));

            IWebElement loginButton = driver.FindElement(By.Id("uh-signedin"));

            loginButton.Click();

            WebDriverWait waitEnterUsername = new WebDriverWait(driver, TimeSpan.FromSeconds(10));

            waitEnterUsername.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.Id("login-username")));

            IWebElement userName = driver.FindElement(By.Id("login-username"));

            userName.SendKeys("meshberge");
            userName.SendKeys(Keys.Enter);

            WebDriverWait waitEnterPassword = new WebDriverWait(driver, TimeSpan.FromSeconds(10));

            waitEnterPassword.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(By.Id("login-passwd")));
            IWebElement password = driver.FindElement(By.Id("login-passwd"));

            password.SendKeys("toonfan1!");
            password.SendKeys(Keys.Enter);

            driver.Navigate().GoToUrl("https://finance.yahoo.com/portfolio/p_1/view/v1");

            WebDriverWait waitDataTable = new WebDriverWait(driver, TimeSpan.FromSeconds(30));

            waitDataTable.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.XPath("//tr")));

            IWebElement        stockTable = driver.FindElement(By.XPath("//tbody"));
            List <IWebElement> stocks     = driver.FindElements(By.XPath("//tr")).ToList();

            List <IWebElement> rows = stockTable.FindElements(By.XPath("//tr")).ToList();
            int rowsCount           = rows.Count;

            using (var context = new FinanceDB())
            {
                for (int row = 1; row < rowsCount; row++)
                {
                    List <IWebElement> cells = rows.ElementAt(row).FindElements(By.TagName("td")).ToList();
                    int cellsCount           = cells.Count;

                    string   symbolData        = cells.ElementAt(0).Text;
                    string   lastPriceData     = cells.ElementAt(1).Text;
                    string   changeData        = cells.ElementAt(2).Text;
                    string   changeRateData    = cells.ElementAt(3).Text;
                    string   currencyData      = cells.ElementAt(4).Text;
                    string   marketTimeData    = cells.ElementAt(5).Text;
                    string   volumeData        = cells.ElementAt(6).Text;
                    string   shareData         = cells.ElementAt(7).Text;
                    string   averageVolumeData = cells.ElementAt(8).Text;
                    string   marketCapData     = cells.ElementAt(12).Text;
                    DateTime timeStampData     = DateTime.Now;



                    var stockRecord = new Stock
                    {
                        Symbol        = symbolData,
                        LastPrice     = lastPriceData,
                        Change        = changeData,
                        ChangeRate    = changeRateData,
                        Currency      = currencyData,
                        MarketTime    = marketTimeData,
                        Volume        = volumeData,
                        Shares        = shareData,
                        AverageVolume = averageVolumeData,
                        MarketCap     = marketCapData,
                        Timestamp     = timeStampData
                    };

                    context.Stocks.Add(stockRecord);
                    context.SaveChanges();
                }
                driver.Close();
                // return RedirectToAction("Recent");
            }
        }
Example #17
0
        public void ChromeTest()
        {
            var options = new ChromeOptions();

            Test(options);
        }
Example #18
0
        /// <summary>
        /// Instantiates a RemoteWebDriver instance based on the browser passed to this method. Opens the browser and maximizes its window.
        /// </summary>
        /// <param name="browser">The browser to get instantiate the Web Driver for.</param>
        /// <param name="browserProfilePath">The folder path to the browser user profile to use with the browser.</param>
        /// <returns>The RemoteWebDriver of the browser passed in to the method.</returns>
        public static RemoteWebDriver CreateDriverAndMaximize(string browser, string browserProfilePath = "", List <string> extensionPaths = null)
        {
            // Create a webdriver for the respective browser, depending on what we're testing.
            RemoteWebDriver driver = null;

            ScenarioEventSourceProvider.EventLog.LaunchWebDriver(browser);
            switch (browser)
            {
            case "opera":
            case "operabeta":
                OperaOptions oOption = new OperaOptions();
                oOption.AddArgument("--disable-popup-blocking");
                oOption.AddArgument("--power-save-mode=on");
                // TODO: This shouldn't be a hardcoded path, but Opera appeared to need this speficied directly to run well
                oOption.BinaryLocation = @"C:\Program Files (x86)\Opera\launcher.exe";
                if (browser == "operabeta")
                {
                    // TODO: Ideally, this code would look inside the Opera beta folder for opera.exe
                    // rather than depending on flaky hard-coded version in directory
                    oOption.BinaryLocation = @"C:\Program Files (x86)\Opera beta\38.0.2220.25\opera.exe";
                }
                driver = new OperaDriver(oOption);
                break;

            case "firefox":
                driver = new FirefoxDriver();
                break;

            case "chrome":
                ChromeOptions option = new ChromeOptions();
                option.AddUserProfilePreference("profile.default_content_setting_values.notifications", 1);

                if (!string.IsNullOrEmpty(browserProfilePath))
                {
                    option.AddArgument("--user-data-dir=" + browserProfilePath);
                }

                driver = new ChromeDriver(option);
                break;

            default:
                // Warning: this blows away all Microsoft Edge data, including bookmarks, cookies, passwords, etc
                EdgeDriverService svc = EdgeDriverService.CreateDefaultService();
                _port = svc.Port;

                if (extensionPaths != null && extensionPaths.Count != 0)
                {
                    var edgeOptions = new EdgeOptions();
                    // Create the extensionPaths capability object
                    edgeOptions.AddAdditionalCapability("extensionPaths", extensionPaths);
                    foreach (var path in extensionPaths)
                    {
                        Logger.LogWriteLine("Sideloading extension(s) from " + path);
                    }

                    driver = new EdgeDriver(svc, edgeOptions);
                }
                else
                {
                    driver = new EdgeDriver(svc);
                }

                FileVersionInfo edgeBrowserVersion = GetEdgeFileVersion();
                Logger.LogWriteLine(string.Format("   Browser Version - MicrosoftEdge File Version: {0}", edgeBrowserVersion.FileVersion));
                _edgeBrowserFileVersionBuildPart = edgeBrowserVersion.FileBuildPart;

                string webDriverServerVersion = GetEdgeWebDriverVersion(driver);
                Logger.LogWriteLine(string.Format("   WebDriver Server Version - MicrosoftWebDriver.exe File Version: {0}", webDriverServerVersion));
                _edgeWebDriverFileVersionBuildPart = Convert.ToInt32(webDriverServerVersion.Split('.')[2]);
                Thread.Sleep(2000);
                HttpClient client = new HttpClient();
                client.DeleteAsync($"http://localhost:{svc.Port}/session/{driver.SessionId}/ms/history").Wait();
                break;
            }

            ScenarioEventSourceProvider.EventLog.MaximizeBrowser(browser);
            driver.Manage().Window.Maximize();
            Thread.Sleep(1000);

            return(driver);
        }
Example #19
0
        public static string initiateDriver(IList <RestResponseCookie> cookies, string pr, string delay, string captcha, string proxy)
        {
            try {
                List <Cookie> lst = new List <Cookie>();
                foreach (var cook in cookies)
                {
                    Cookie ss = new Cookie(cook.Name, cook.Value, "www.supremenewyork.com", "/", DateTime.Now.AddDays(1));
                    lst.Add(ss);
                }

                IWebDriver driver;

                var service = ChromeDriverService.CreateDefaultService();
                service.HideCommandPromptWindow = true;
                var useragents = new List <string> {
                    "Mozilla/5.0 (Windows NT 4.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.517 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17"
                };
                int index = new Random().Next(useragents.Count);
                var name  = useragents[index];
                useragents.RemoveAt(index);

                ChromeOptions option = new ChromeOptions();


                //option.AddArgument("--ignore-certificate-errors");
                option.AddArguments("--window-size=600,800");
                //option.AddArguments("--user-data-dir=C:/Users/intel/AppData/Local/Google/Chrome/User Data");

                option.AddArguments("--user-agent='" + name + "'");
                //option.AddArguments("--headless");
                //option.PageLoadStrategy = PageLoadStrategy.Normal;

                driver = new ChromeDriver(service, option);
                var _cookies = driver.Manage().Cookies.AllCookies;
                driver.Manage().Cookies.DeleteAllCookies();

                //var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(2000));

                driver.Navigate().GoToUrl("https://www.supremenewyork.com/");
                foreach (Cookie cookie in lst)
                {
                    driver.Manage().Cookies.AddCookie(cookie);
                }
                //option.AddArguments("--headless");
                //option.PageLoadStrategy = PageLoadStrategy.Normal;

                driver.Navigate().GoToUrl("https://www.supremenewyork.com/checkout");
                var result = "";
                try
                {
                    result = fillDelivery(driver, pr, captcha, delay);
                }catch (Exception ex)
                {
                    result = ex.Message;
                    driver.Quit();
                }
                return(result);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Example #20
0
        public void Opensacconwithcredential(string strafterPKIverified)
        {
            string strDasID          = string.Empty;
            string strsacconpassword = string.Empty;
            var    doc = new XmlDocument();

            doc.Load(@"mycre.xml");

            var root = doc.DocumentElement;

            if (root == null)
            {
                return;
            }

            var books = root.SelectNodes("saccon");

            if (books == null)
            {
                return;
            }

            foreach (XmlNode book in books)
            {
                strDasID          = book.SelectSingleNode("dasid").InnerText;
                strsacconpassword = book.SelectSingleNode("password").InnerText;
            }

            ChromeOptions co = new ChromeOptions();
            //co.AddArguments("--disable-notifications");
            ChromeDriver driver = new ChromeDriver();


            driver.Manage().Window.Maximize();
            driver.Navigate().GoToUrl(strafterPKIverified);

            var PKI = driver.FindElementByName("PKI_LOGIN");

            PKI.Click();



            //PKI.SendKeys(Keys.Enter);

            var saaconUserId = driver.FindElementById("user");

            saaconUserId.SendKeys("a647245");
            var saaconPwd = driver.FindElementById("password");

            saaconPwd.SendKeys("December@25032004");

            var saaconbtnLogin = driver.FindElementById("btnLogin");

            saaconbtnLogin.Click();

            var folderLink_21 = driver.FindElementById("folderLink_21");

            folderLink_21.Click();

            var folderLink_44 = driver.FindElementById("folderLink_44");

            folderLink_44.Click();

            var           downloadsFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Downloads";
            DirectoryInfo dinfo2          = new DirectoryInfo(downloadsFolder);

            var originalICAfileCount = dinfo2.GetFiles("*.ica").Count();


            var idCitrix = driver.FindElementById("idCitrix.MPS.App.AdmingateSaaconV2.BMW_0020Europe_0020Farm_0020managed_0020by_0020customer_005fDE");

            idCitrix.Click();

            while (true)
            {
                var newICAfileCount = dinfo2.GetFiles("*.ica").Count();
                if (newICAfileCount > originalICAfileCount)
                {
                    break;
                }
            }

            var myFile = (from f in dinfo2.GetFiles("*.ica")
                          orderby f.LastWriteTime descending
                          select f.FullName).First();

            InternetExplorerDriver iedriver = new InternetExplorerDriver("C:\\Software\\");

            iedriver.Navigate().GoToUrl("https://www.google.com/");

            int windowhandles1 = iedriver.WindowHandles.Count;

            Console.WriteLine("Before Windowhandles" + windowhandles1.ToString());

            Console.WriteLine("Window Name" + iedriver.WindowHandles[0].ToString());

            Process.Start(myFile);

            System.Threading.Thread.Sleep(10000);

            //WinClient uICitrixAccessGatewayIClient = this.UICitrixAccessGatewayIWindow.UICitrixAccessGatewayIClient;

            //IntPtr hWnd = FindWindow("", "Untitled - Notepad");
            //if (hWnd.ToInt32() > 0) //If found
            //{
            //    //Do Something
            //}
            //else //Not Found
            //{
            //    Console.WriteLine("Window Not Found!");
            //}
        }
Example #21
0
        private async Task pullWriteDataByHeadlessBrowserAsync()
        {
            string chromeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            ChromeDriverService driverService = ChromeDriverService.CreateDefaultService(chromeDir);

            driverService.HideCommandPromptWindow = true;//关闭黑色cmd窗口
            driverService.WhitelistedIPAddresses  = "0.0.0.0";


            ChromeOptions options = new ChromeOptions();


            options.AddArgument("enable-automation");
            options.AddArgument("--headless");
            options.AddArgument("--window-size=1920,1080");
            options.AddArgument("--no-sandbox");
            options.AddArgument("--disable-setuid-sandbox");
            options.AddArgument("--disable-extensions");
            options.AddArgument("--dns-prefetch-disable");
            options.AddArgument("--disable-gpu");
            //options.AddArgument("--remote-debugging-port=9222");
            options.PageLoadStrategy = PageLoadStrategy.Normal;

            //禁用图片
            options.AddUserProfilePreference("profile.default_content_setting_values.images", 2);



            System.Diagnostics.Debug.WriteLine("test case started ");
            //create the reference for the browser
            using (IWebDriver driver = new ChromeDriver(driverService, options))
            {
                try
                {
                    driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(20);


                    const string url = "http://data.eastmoney.com/hsgt/index.html";
                    // navigate to URL
                    driver.Navigate().GoToUrl(url);


                    //await Task.Delay(TimeSpan.FromSeconds(10));
                    ////*[@id="north_h_jme"]/span

                    var ele         = driver.FindElement(By.XPath("//*[@id=\"north_h_jme\"]/span"));
                    var huguTongstr = ele.Text;


                    ele = driver.FindElement(By.XPath("//*[@id=\"north_s_jme\"]/span"));

                    var shenguTongstr = ele.Text;


                    ////*[@id="updateTime_bxzj"]
                    ele = driver.FindElement(By.XPath(" //*[@id=\"updateTime_bxzj\"]"));

                    var datestr = ele.Text;


                    //close the browser
                    driver.Close();
                    System.Diagnostics.Debug.WriteLine("test case ended ");


                    //解析时间

                    if (DateTime.TryParseExact(datestr, "yyyy-MM-dd", CultureInfo.InvariantCulture,
                                               DateTimeStyles.None, out DateTime updateTime) == false)
                    {
                        throw new Exception($"解析{url} 中的时间 {datestr}字条串出错");
                    }

                    //写入数据库

                    await writetoDb(updateTime, MarketType.HuGuTong, huguTongstr);
                    await writetoDb(updateTime, MarketType.ShenGuTong, shenguTongstr);
                }
                catch (Exception ex)
                {
                    driver.Quit();
                    throw ex;
                }
            }
        }
        protected BusinessFunctionFlowComponentBase
        (
            ITestBackgroundDataProvider <TUserRole, TTestEnvironment> testBackgroundDataProvider,
            IDecryptor decryptor = null
        )
        {
            // Ensure generic types are enums.
            this.EnsureGenericArgumentsAreEnumTypes();

            this.TestBackgroundDataProvider = testBackgroundDataProvider;
            this.Decryptor = decryptor;

            if (testBackgroundDataProvider != null)
            {
                this.TestEnvironment = testBackgroundDataProvider.GetTargetTestEnvironment();
                this.WebBrowserToUse = testBackgroundDataProvider.GetWebBrowserTypeToUseForAcceptanceTests();

                var appSettings = ConfigurationManager.AppSettings;

                // Selenium Grid related settings.
                var runMode
                    = (appSettings [ConfigKeys.RUN_MODE].Trim().Equals("local"))
                                                ? TestRunMode.Local
                                                : TestRunMode.SeleniumGrid;

                var gridHubUrl = String.Empty;

                if (runMode == TestRunMode.SeleniumGrid)
                {
                    gridHubUrl = appSettings [ConfigKeys.SELENIUM_GRID_HUB_URL];
                }

                // Browser and web driver executable paths.
                var configKeyFirstPart = this.WebBrowserToUse.ToString();

                var browserExeAbsolutePath            = appSettings [configKeyFirstPart + ConfigKeys.BROWSER_EXE_ABSOLUTE_PATH_KEY_PART];
                var webDriverExeDirectoryAbsolutePath = appSettings [configKeyFirstPart + ConfigKeys.WEB_DRIVER_EXE_DIRECTORY_PATH_KEY_PART];

                // Prepare the web driver of choice.
                switch (this.WebBrowserToUse)
                {
                case WebBrowser.MozillaFirefox:
                    if (runMode == TestRunMode.Local)
                    {
                        var firefoxOptions = new FirefoxOptions {
                            BrowserExecutableLocation = browserExeAbsolutePath
                        };
                        this.WebDriver = new FirefoxDriver(webDriverExeDirectoryAbsolutePath, firefoxOptions);
                    }
                    else
                    {
                        var firefoxOptions = new FirefoxOptions();
                        this.WebDriver = new RemoteWebDriver(new Uri(gridHubUrl), firefoxOptions);
                    }
                    break;

                case WebBrowser.GoogleChrome:

                    if (runMode == TestRunMode.Local)
                    {
                        var chromeOptions = new ChromeOptions {
                            BinaryLocation = browserExeAbsolutePath
                        };
                        chromeOptions.AddAdditionalCapability("useAutomationExtension", false);
                        chromeOptions.AddArgument("no-sandbox");
                        this.WebDriver = new ChromeDriver(webDriverExeDirectoryAbsolutePath, chromeOptions);
                    }
                    else
                    {
                        var chromeOptions = new ChromeOptions();
                        chromeOptions.AddAdditionalCapability("useAutomationExtension", false);
                        chromeOptions.AddArgument("no-sandbox");
                        this.WebDriver = new RemoteWebDriver(new Uri(gridHubUrl), chromeOptions);
                    }
                    break;

                case WebBrowser.MicrosoftEdge:
                    if (runMode == TestRunMode.Local)
                    {
                        var edgeOptions = new EdgeOptions
                        {
                            BinaryLocation = browserExeAbsolutePath
                        };
                        var edgeService = EdgeDriverService.CreateDefaultService(webDriverExeDirectoryAbsolutePath, "msedgedriver.exe");
                        this.WebDriver = new EdgeDriver(edgeService, edgeOptions);
                    }
                    else
                    {
                        var edgeOptions = new EdgeOptions {
                            UseChromium = true
                        };
                        this.WebDriver = new RemoteWebDriver(new Uri(gridHubUrl), edgeOptions);
                    }
                    break;

                case WebBrowser.InternetExplorer:
                    if (runMode == TestRunMode.Local)
                    {
                        var ieOptions
                            = new InternetExplorerOptions
                            {
                            EnsureCleanSession = true,
                            RequireWindowFocus = true,
                            IntroduceInstabilityByIgnoringProtectedModeSettings = true
                            };

                        ieOptions.AddAdditionalCapability("useAutomationExtension", false);
                        this.WebDriver = new InternetExplorerDriver(webDriverExeDirectoryAbsolutePath, ieOptions);
                    }
                    else
                    {
                        var ieOptions
                            = new InternetExplorerOptions
                            {
                            EnsureCleanSession = true,
                            RequireWindowFocus = true,
                            IntroduceInstabilityByIgnoringProtectedModeSettings = true
                            };

                        ieOptions.AddAdditionalCapability("useAutomationExtension", false);
                        this.WebDriver = new RemoteWebDriver(new Uri(gridHubUrl), ieOptions);
                    }
                    break;

                default:
                    throw new NotImplementedException($"The specified web browser \"{ this.WebBrowserToUse }\" is not yet implemented for acceptance tests.");
                }
            }
        }
Example #23
0
        private (DriverService, IWebDriver) GetChromeDriver(ILogger logger)
        {
            var options = new ChromeOptions();

            options.SetLoggingPreference(LogType.Browser, SeleniumLogLevel.All);

            options.AddArguments(new List <string>(_arguments.BrowserArgs)
            {
                "--incognito",
                "--headless",

                // added based on https://github.com/puppeteer/puppeteer/blob/main/src/node/Launcher.ts#L159-L181
                "--enable-features=NetworkService,NetworkServiceInProcess",
                "--disable-background-timer-throttling",
                "--disable-backgrounding-occluded-windows",
                "--disable-breakpad",
                "--disable-component-extensions-with-background-pages",
                "--disable-dev-shm-usage",
                "--disable-extensions",
                "--disable-features=TranslateUI",
                "--disable-ipc-flooding-protection",
                "--disable-renderer-backgrounding",
                "--force-color-profile=srgb",
                "--metrics-recording-only"
            });

            logger.LogInformation($"Starting chromedriver with args: {string.Join(' ', options.Arguments)}");

            // We want to explicitly specify a timeout here. This is for for the
            // driver commands, like getLog. The default is 60s, which ends up
            // timing out when getLog() is waiting, and doesn't receive anything
            // for 60s.
            //
            // Since, we almost all the output gets written via the websocket now,
            // getLog() might not see anything for long durations!
            //
            // So -> use a larger timeout!

            string[] err_snippets = new []
            {
                "exited abnormally",
                "Cannot start the driver service"
            };

            foreach (var file in Directory.EnumerateFiles(_arguments.OutputDirectory, "chromedriver-*.log"))
            {
                File.Delete(file);
            }

            int max_retries = 3;
            int retry_num   = 0;

            while (true)
            {
                ChromeDriverService?driverService = null;
                try
                {
                    driverService = ChromeDriverService.CreateDefaultService();
                    driverService.EnableAppendLog      = false;
                    driverService.EnableVerboseLogging = true;
                    driverService.LogPath = Path.Combine(_arguments.OutputDirectory, $"chromedriver-{retry_num}.log");

                    return(driverService, new ChromeDriver(driverService, options, _arguments.Timeout));
                }
                catch (WebDriverException wde) when(err_snippets.Any(s => wde.Message.Contains(s)) && retry_num < max_retries - 1)
                {
                    // chrome can sometimes crash on startup when launching from chromedriver.
                    // As a *workaround*, let's retry that a few times
                    // Example error seen:
                    //     [12:41:07] crit: OpenQA.Selenium.WebDriverException: unknown error: Chrome failed to start: exited abnormally.
                    //    (chrome not reachable)

                    // Log on max-1 tries, and rethrow on the last one
                    logger.LogWarning($"Failed to start chrome, attempt #{retry_num}: {wde}");

                    driverService?.Dispose();
                }
                catch
                {
                    driverService?.Dispose();
                    throw;
                }

                retry_num++;
            }
        }
Example #24
0
        public string FTP_MNDakota(string houseno, string sname, string unitno, string parcelNumber, string searchType, string orderNumber, string ownername, string directParcel)
        {
            string StartTime = "", AssessmentTime = "", TaxTime = "", CitytaxTime = "", LastEndTime = "", AssessTakenTime = "", TaxTakentime = "", CityTaxtakentime = "";
            string TotaltakenTime = "";
            string OwnerName = "", JointOwnerName = "", PropertyAddress = "", MailingAddress = "", Municipality = "", PropertyUse = "", YearBuilt = "", LegalDescription = "", parcel_id = "";

            List<string> strTaxRealestate = new List<string>();
            List<string> strTaxRealestate1 = new List<string>();
            GlobalClass.global_orderNo = orderNumber;
            HttpContext.Current.Session["orderNo"] = orderNumber;
            GlobalClass.global_parcelNo = parcelNumber;
            //IWebElement iframeElement1;
            var driverService = PhantomJSDriverService.CreateDefaultService();
            driverService.HideCommandPromptWindow = true;
            //driver = new PhantomJSDriver();
            driver = new ChromeDriver();
            var option = new ChromeOptions();
            option.AddArgument("No-Sandbox");
            using (driver = new ChromeDriver(option))
            {
                try
                {
                    StartTime = DateTime.Now.ToString("HH:mm:ss");
                    driver.Navigate().GoToUrl("https://gis2.co.dakota.mn.us/WAB/PropertyInformationPublic/index.html");
                    Thread.Sleep(20000);
                    // driver.SwitchTo().Window(driver.WindowHandles.Last());
                    try
                    {

                        IWebElement ISpan12 = driver.FindElement(By.XPath("//*[@id='widgets_Splash_Widget_71']/div[2]/div[2]/div[2]/div[2]"));
                        IJavaScriptExecutor js12 = driver as IJavaScriptExecutor;
                        js12.ExecuteScript("arguments[0].click();", ISpan12);
                        Thread.Sleep(9000);
                    }
                    catch { }
                    if (searchType == "address")
                    {

                        driver.FindElement(By.Id("esri_dijit_Search_0_input")).SendKeys(houseno + " " + sname);
                        gc.CreatePdf_WOP(orderNumber, "Address Search", driver, "MN", "Dakota");
                        driver.FindElement(By.XPath("//*[@id='esri_dijit_Search_0']/div/div[2]")).Click();
                        //   gc.CreatePdf_WOP(orderNumber, "Address Search result", driver, "MN", "Dakota");
                        try
                        {
                            IWebElement Inodata = driver.FindElement(By.XPath("//*[@id='esri_dijit_Search_0']/div/div[4]/div"));
                            if (Inodata.Text.Contains("No results") || Inodata.Text.Contains("no results found"))
                            {
                                HttpContext.Current.Session["Nodata_MNDakota"] = "Yes";
                                driver.Quit();
                                return "No Data Found";
                            }
                        }
                        catch { }
                        Thread.Sleep(10000);
                        try
                        {
                            driver.FindElement(By.XPath("//*[@id='widgets_Search_Widget_60']/div[2]/div[2]/ul/li")).Click();
                            Thread.Sleep(2000);
                        }
                        catch { }
                        try
                        {
                            int i, j = 0;
                            int iRowsCount = driver.FindElements(By.XPath("//*[@id='widgets_Search_Widget_60']/div[2]/div[2]/ul/li")).Count;
                            if (iRowsCount > 1)
                            {
                                if (j < 25)
                                {

                                    for (i = 1; i <= iRowsCount; i++)
                                    {
                                        ////*[@id="widgets_Search_Widget_60"]/div[2]/div[2]/ul
                                        string add1 = driver.FindElement(By.XPath("//*[@id='widgets_Search_Widget_60']/div[2]/div[2]/ul/li[" + i + "]")).Text;
                                        driver.FindElement(By.XPath("//*[@id='widgets_Search_Widget_60']/div[2]/div[2]/ul/li[" + i + "]")).Click();
                                        Thread.Sleep(3000);
                                        driver.SwitchTo().Window(driver.WindowHandles.Last());
                                        Thread.Sleep(1000);
                                        string fulltext4 = driver.FindElement(By.XPath("//*[@id='dijit_layout_ContentPane_0']")).Text.Trim().Replace("\r\n", "");
                                        parcel_id = gc.Between(fulltext4, "Parcel ID:", "Property Details").Trim().Replace("-", "");
                                        PropertyAddress = gc.Between(fulltext4, "Parcel ID:", "Property Details").Trim().Replace("-", "");
                                        // string s1 = parcel_id;
                                        string[] words1 = parcel_id.Split(' ');
                                        parcel_id = words1[0];

                                        parcel_id = parcel_id.Substring(0, 12);
                                        PropertyAddress = WebDriverTest.After(PropertyAddress, parcel_id).Trim();
                                        //string parcel = driver.FindElement(By.XPath("/html/body/div[2]/div[1]/div[4]/div[2]/div/div/div[2]/div/div[1]/div[1]")).Text.Trim().Replace("Parcel ID:", "");
                                        //string fulltext1 = driver.FindElement(By.XPath("/html/body/div[2]/div[1]/div[4]/div[2]/div/div/div[2]/div/div[1]/div[3]/font[4]/table/tbody")).Text.Trim().Replace("\r\n", "");

                                        string Owner = gc.Between(fulltext4, "Owner", "Joint Owner").Trim();
                                        string multi = add1 + "~" + Owner;
                                        gc.insert_date(orderNumber, parcel_id, 464, multi, 1, DateTime.Now);
                                        driver.FindElement(By.XPath("//*[@id='esri_dijit_Search_0']/div/div[2]")).Click();
                                        Thread.Sleep(4000);
                                    }
                                    j++;
                                }

                                if (iRowsCount > 25)
                                {
                                    HttpContext.Current.Session["multiParcel_MNDakota_Multicount"] = "Maximum";
                                }
                                else
                                {
                                    HttpContext.Current.Session["multiparcel_MNDakota"] = "Yes";
                                }
                                driver.Quit();

                                return "MultiParcel";
                            }

                            else
                            {
                                try { 
                                driver.FindElement(By.XPath("//*[@id='widgets_Search_Widget_60']/div[2]/div[2]/ul/li")).Click();
                                Thread.Sleep(8000);
                                }
                                catch { }
                            }


                        }
                        catch { }

                    }

                    if (searchType == "titleflex")
                    {
                        string titleaddress = houseno + " " + sname + " " + unitno;
                        gc.TitleFlexSearch(orderNumber, "", "", titleaddress, "MN", "Dakota");
                        if ((HttpContext.Current.Session["TitleFlex_Search"] != null && HttpContext.Current.Session["TitleFlex_Search"].ToString() == "Yes"))
                        {
                            driver.Quit();
                            return "MultiParcel";
                        }
                        else if (HttpContext.Current.Session["titleparcel"].ToString() == "")
                        {
                            HttpContext.Current.Session["Nodata_MNDakota"] = "Yes";
                            driver.Quit();
                            return "No Data Found";
                        }
                        parcelNumber = HttpContext.Current.Session["titleparcel"].ToString();
                        searchType = "parcel";
                    }


                    if (searchType == "parcel")
                    {
                        if ((HttpContext.Current.Session["TitleFlex_Search"] != null && HttpContext.Current.Session["TitleFlex_Search"].ToString() == "Yes"))
                        {
                            parcelNumber = HttpContext.Current.Session["titleparcel"].ToString();

                        }

                        if (parcelNumber.Contains("-"))
                        {
                            parcel_id = parcelNumber.Replace("-", "");
                        }
                        else
                            parcel_id = parcelNumber;

                        driver.FindElement(By.Id("esri_dijit_Search_0_input")).SendKeys(parcelNumber);
                        gc.CreatePdf(orderNumber, parcel_id, "parcel search", driver, "MN", "Dakota");
                        driver.FindElement(By.XPath("//*[@id='esri_dijit_Search_0']/div/div[2]")).Click();
                        try
                        {
                            IWebElement Inodata = driver.FindElement(By.XPath("//*[@id='esri_dijit_Search_0']/div/div[4]/div"));
                            if (Inodata.Text.Contains("No results") || Inodata.Text.Contains("no results found"))
                            {
                                HttpContext.Current.Session["Nodata_MNDakota"] = "Yes";
                                driver.Quit();
                                return "No Data Found";
                            }
                        }
                        catch { }
                        Thread.Sleep(6000);
                    }


                    //property_details
                    driver.SwitchTo().Window(driver.WindowHandles.Last());
                    //Owner Name~Joint Owner Name~Property Address~Mailing Address~Municipality~Property Use~Year Built~Legal Description
                    gc.CreatePdf(orderNumber, parcel_id, "property info", driver, "MN", "Dakota");
                    string fulltext3 = driver.FindElement(By.XPath("//*[@id='dijit_layout_ContentPane_0']")).Text.Trim().Replace("\r\n", "");
                    parcel_id = gc.Between(fulltext3, "Parcel ID:", "Property Details").Trim().Replace("-", "");
                    PropertyAddress = gc.Between(fulltext3, "Parcel ID:", "Property Details").Trim().Replace("-", "");
                    string s = parcel_id;
                    string[] words = parcel_id.Split(' ');
                    parcel_id = words[0];

                    parcel_id = parcel_id.Substring(0, 12);
                    PropertyAddress = WebDriverTest.After(PropertyAddress, parcel_id).Trim();

                    Thread.Sleep(2000);
                    string fulltext = driver.FindElement(By.XPath("//*[@id='dijit_layout_ContentPane_0']")).Text.Trim().Replace("\r\n", "");
                    OwnerName = gc.Between(fulltext, "Owner", "Joint Owner").Trim();
                    JointOwnerName = gc.Between(fulltext, "Joint Owner", "Owner Address").Trim();
                    MailingAddress = gc.Between(fulltext, "Owner Address", "Municipality").Trim();
                    Municipality = gc.Between(fulltext, "Municipality", "Primary Use").Trim();
                    PropertyUse = gc.Between(fulltext, "Primary Use", "Acres").Trim();
                    LegalDescription = gc.Between(fulltext, "Tax Description", "Lot and Block").Trim();
                    YearBuilt = gc.Between(fulltext, "Year Built", "Building Type").Trim();

                    string property_details = OwnerName + "~" + JointOwnerName + "~" + PropertyAddress + "~" + MailingAddress + "~" + Municipality + "~" + PropertyUse + "~" + YearBuilt + "~" + LegalDescription;
                    gc.insert_date(orderNumber, parcel_id, 461, property_details, 1, DateTime.Now);

                    AssessmentTime = DateTime.Now.ToString("HH:mm:ss");

                    string strCurrentURL = driver.CurrentWindowHandle;
                    //Tax Year~Estimated Market Value~Homestead Exclusion~Taxable Market Value~New Imp/Expired Excl~New Imp/Expired Excl

                    try
                    {
                        var chromeOptions = new ChromeOptions();
                        var downloadDirectory = ConfigurationManager.AppSettings["AutoPdf"];
                        chromeOptions.AddUserProfilePreference("download.default_directory", downloadDirectory);
                        chromeOptions.AddUserProfilePreference("download.prompt_for_download", false);
                        chromeOptions.AddUserProfilePreference("disable-popup-blocking", "true");
                        chromeOptions.AddUserProfilePreference("plugins.always_open_pdf_externally", true);
                        var driver1 = new ChromeDriver(chromeOptions);
                        driver1.Navigate().GoToUrl(driver.Url);
                        Thread.Sleep(20000);
                        string fileName = "PropertyReport";
                        IWebElement ISpan121 = driver1.FindElement(By.XPath("//*[@id='widgets_Splash_Widget_71']/div[2]/div[2]/div[2]/div[2]"));
                        IJavaScriptExecutor js121 = driver1 as IJavaScriptExecutor;
                        js121.ExecuteScript("arguments[0].click();", ISpan121);
                        Thread.Sleep(15000);
                        driver1.FindElement(By.Id("esri_dijit_Search_0_input")).SendKeys(parcel_id);
                        driver1.FindElement(By.XPath("//*[@id='esri_dijit_Search_0']/div/div[2]")).Click();
                        Thread.Sleep(6000);
                        IWebElement Itaxbill = driver1.FindElement(By.LinkText("Property Details"));
                        Itaxbill.Click();
                        Thread.Sleep(6000);
                        gc.AutoDownloadFile(orderNumber, parcelNumber, "Dakota", "MN", "PropertyReport.pdf");

                        driver1.Quit();
                    }
                    catch (Exception e)
                    { }


                    try
                    {
                        IWebElement Itaxstmt = driver.FindElement(By.LinkText("Tax Statement"));
                        string stmt1 = Itaxstmt.GetAttribute("href");
                        strTaxRealestate1.Add(stmt1);
                    }
                    catch { }
                    try
                    {

                        IWebElement Itaxstmt1 = driver.FindElement(By.LinkText("Tax Payment Stub"));
                        string stmt11 = Itaxstmt1.GetAttribute("href");
                        var chDriver = new ChromeDriver();

                        chDriver.Navigate().GoToUrl(stmt11);
                        Thread.Sleep(5000);
                        chDriver.Manage().Window.Size = new Size(480, 320);
                        gc.CreatePdf(orderNumber, parcel_id, "stub", chDriver, "MN", "Dakota");


                        Actions act = new Actions(chDriver);

                        for (int l = 0; l < 13; l++)
                        {
                            act.SendKeys(Keys.Down).Perform();
                        }
                        gc.CreatePdf(orderNumber, parcel_id, "stub2", chDriver, "MN", "Dakota");

                        Thread.Sleep(4000);
                        chDriver.Quit();
                    }
                    catch (Exception e) { }


                    try
                    {
                        IWebElement Itaxstmt2 = driver.FindElement(By.LinkText("Tax Facts"));
                        string stmt12 = Itaxstmt2.GetAttribute("href");
                        gc.downloadfile(stmt12, orderNumber, parcel_id, "TaxFact", "MN", "Dakota");
                    }
                    catch
                    {
                    }

                    List<string> description = new List<string>();
                    List<string> Output1 = new List<string>();
                    List<string> Output2 = new List<string>();

                    List<string> Output1A = new List<string>();
                    List<string> Output2A = new List<string>();
                    foreach (string real in strTaxRealestate1)
                    {
                        driver.Navigate().GoToUrl(real);
                        Thread.Sleep(4000);
                        try {
                            ByVisibleElement(driver.FindElement(By.Id("hplTaxStmntPDF")));
                        }
                        catch { }
                        if (real.Contains("TaxStatement"))
                        {
                            //Taxinfo_Details
                            gc.CreatePdf(orderNumber, parcel_id, "Tax info", driver, "MN", "Dakota");

                            description.Add(driver.FindElement(By.Id("lblLine3")).Text.Trim());
                            Output1.Add(driver.FindElement(By.Id("txtPrevTotalAidTax")).Text.Trim());
                            Output2.Add(driver.FindElement(By.Id("txtCurrentTotalAidTax")).Text.Trim());

                            description.Add(driver.FindElement(By.XPath("//*[@id='txtTaxStatement']/div[52]")).Text.Trim());
                            Output1.Add(driver.FindElement(By.Id("txtPrevHomesteadCredit")).Text.Trim());
                            Output2.Add(driver.FindElement(By.Id("txtCurrentHomesteadCredit")).Text.Trim());

                            description.Add(driver.FindElement(By.Id("Div31")).Text.Trim());
                            Output1.Add(driver.FindElement(By.Id("txtPrevOtherCredits")).Text.Trim());
                            Output2.Add(driver.FindElement(By.Id("txtCurrentOtherCredits")).Text.Trim());

                            description.Add(driver.FindElement(By.Id("Div48")).Text.Trim());
                            Output1.Add(driver.FindElement(By.Id("txtPrevTotalNetTax")).Text.Trim());
                            Output2.Add(driver.FindElement(By.Id("txtCurrentTotalNetTax")).Text.Trim());

                            description.Add(driver.FindElement(By.Id("Div7")).Text.Trim());
                            Output1.Add(driver.FindElement(By.Id("txtPrevCountyTax")).Text.Trim());
                            Output2.Add(driver.FindElement(By.Id("txtCurrentCountyTax")).Text.Trim());

                            description.Add(driver.FindElement(By.Id("Div10")).Text.Trim());
                            Output1.Add(driver.FindElement(By.Id("txtPrevRail")).Text.Trim());
                            Output2.Add(driver.FindElement(By.Id("txtRail")).Text.Trim());

                            description.Add(driver.FindElement(By.Id("txtDistrictName")).Text.Trim());
                            Output1.Add(driver.FindElement(By.Id("txtPrevCityTax")).Text.Trim());
                            Output2.Add(driver.FindElement(By.Id("txtCurrentCityTax")).Text.Trim());

                            description.Add(driver.FindElement(By.Id("Div51")).Text.Trim());
                            Output1.Add(driver.FindElement(By.Id("txtPrevStateTax")).Text.Trim());
                            Output2.Add(driver.FindElement(By.Id("txtCurrentStateTax")).Text.Trim());

                            description.Add(driver.FindElement(By.Id("txtSchoolDistrict")).Text.Trim());
                            Output1.Add(driver.FindElement(By.Id("txtPrevVoterApprovedLevies")).Text.Trim());
                            Output2.Add(driver.FindElement(By.Id("txtCurrentVoterApprovedLevies")).Text.Trim());

                            description.Add(driver.FindElement(By.Id("Div55")).Text.Trim());
                            Output1.Add(driver.FindElement(By.Id("txtPrevOtherLevies")).Text.Trim());
                            Output2.Add(driver.FindElement(By.Id("txtCurrentOtherLevies")).Text.Trim());

                            description.Add(driver.FindElement(By.Id("Div57")).Text.Trim());
                            Output1.Add(driver.FindElement(By.Id("txtPrevMetroTax")).Text.Trim());
                            Output2.Add(driver.FindElement(By.Id("txtCurrentMetroTax")).Text.Trim());

                            description.Add(driver.FindElement(By.Id("Div58")).Text.Trim());
                            Output1.Add(driver.FindElement(By.Id("txtPrevSpecial")).Text.Trim());
                            Output2.Add(driver.FindElement(By.Id("txtCurrentSpecial")).Text.Trim());

                            description.Add(driver.FindElement(By.Id("Div59")).Text.Trim());
                            Output1.Add(driver.FindElement(By.Id("txtPrevTaxIncrement")).Text.Trim());
                            Output2.Add(driver.FindElement(By.Id("txtCurrentTaxIncrement")).Text.Trim());

                            description.Add(driver.FindElement(By.Id("Div60")).Text.Trim());
                            Output1.Add(driver.FindElement(By.Id("txtPrevFiscalDisparity")).Text.Trim());
                            Output2.Add(driver.FindElement(By.Id("txtCurrentFiscalDisparity")).Text.Trim());

                            description.Add(driver.FindElement(By.Id("Div61")).Text.Trim());
                            Output1.Add(driver.FindElement(By.Id("txtPrevNonSchoolVoterLevy")).Text.Trim());
                            Output2.Add(driver.FindElement(By.Id("txtCurrentNonSchoolVoterLevy")).Text.Trim());

                            description.Add(driver.FindElement(By.Id("Div62")).Text.Trim());
                            Output1.Add(driver.FindElement(By.Id("txtPrevTaxBeforeSA")).Text.Trim());
                            Output2.Add(driver.FindElement(By.Id("txtCurrentTaxBeforeSA")).Text.Trim());

                            description.Add(driver.FindElement(By.Id("Div63")).Text.Trim());
                            Output1.Add(driver.FindElement(By.Id("txtTotalSA")).Text.Trim());
                            Output2.Add(" ");

                            description.Add(driver.FindElement(By.Id("Div64")).Text.Trim());
                            Output1.Add(" ");
                            Output2.Add(driver.FindElement(By.Id("txtSAPrincipal")).Text.Trim());

                            description.Add(driver.FindElement(By.Id("Div65")).Text.Trim());
                            Output1.Add(" ");
                            Output2.Add(driver.FindElement(By.Id("txtSAInterest")).Text.Trim());

                            description.Add(driver.FindElement(By.Id("Div66")).Text.Trim());
                            Output1.Add(driver.FindElement(By.Id("txtPriorTaxAndSA")).Text.Trim());
                            Output2.Add(driver.FindElement(By.Id("txtCurrentTaxAndSA")).Text.Trim());

                            description.Add(driver.FindElement(By.Id("Div67")).Text.Trim());
                            Output1.Add(" ");
                            Output2.Add(driver.FindElement(By.Id("txtFirstHalfTax")).Text.Trim());

                            description.Add(driver.FindElement(By.Id("Div69")).Text.Trim());
                            Output1.Add(" ");
                            Output2.Add(driver.FindElement(By.Id("txtSecondHalfTax")).Text.Trim());
                            Output1.Add(driver.FindElement(By.Id("txtPriorYear")).Text.Trim());
                            Output2.Add(driver.FindElement(By.Id("txtCurrentYear")).Text.Trim());

                            string deli = (driver.FindElement(By.Id("txtDelinquentInd")).Text.Trim());
                            string msg = "";

                            if (deli.Contains(""))
                            {
                                deli = "NO";
                                msg = " ";
                            }

                            else
                            {
                                deli = "Yes";
                                msg = "Taxes are Delinquent. Please contact county for tax information";
                            }

                            string tax_address = driver.FindElement(By.Id("lblDeptHeading")).Text.Trim().Replace("\r\n", "");
                            string descriptionN = "Tax Year" + "~" + description[0] + "~" + "Credits that reduce property taxes " + description[1] + "~" + "Credits that reduce property taxes " + description[2] + "~" + description[3] + "~" + "County: " + description[4] + "~" + description[5] + "~" + "City or Town: " + description[6] + "~" + description[7] + "~" + "School District: " + description[8] + " A.  Voter Approved Levies" + "~" + description[9] + "~" + "Special Taxing Districts  " + description[10] + "~" + description[11] + "~" + description[12] + "~" + description[13] + "~" + description[14] + "~" + description[15] + "~" + description[16] + "~" + description[17] + "~" + description[18] + "~" + description[19] + "~" + description[20] + "~" + description[21] + "~" + "Delinquent Taxes" + "~" + "Comments" + "~" + "Tax Address";
                            string taxInfo1 = Output1[22] + "~" + Output1[0] + "~" + Output1[1] + "~" + Output1[2] + "~" + Output1[3] + "~" + Output1[4] + "~" + Output1[5] + "~" + Output1[6] + "~" + Output1[7] + "~" + Output1[8] + "~" + Output1[9] + "~" + Output1[10] + "~" + Output1[11] + "~" + Output1[12] + "~" + Output1[13] + "~" + Output1[14] + "~" + Output1[15] + "~" + Output1[16] + "~" + Output1[17] + "~" + Output1[18] + "~" + Output1[19] + "~" + Output1[20] + "~" + Output1[21] + "~" + deli + "~" + msg + "~" + tax_address;
                            string taxInfo11 = Output2[22] + "~" + Output2[0] + "~" + Output2[1] + "~" + Output2[2] + "~" + Output2[3] + "~" + Output2[4] + "~" + Output2[5] + "~" + Output2[6] + "~" + Output2[7] + "~" + Output2[8] + "~" + Output2[9] + "~" + Output2[10] + "~" + Output2[11] + "~" + Output2[12] + "~" + Output2[13] + "~" + Output2[14] + "~" + Output2[15] + "~" + Output2[16] + "~" + Output2[17] + "~" + Output2[18] + "~" + Output2[19] + "~" + Output2[20] + "~" + Output2[21] + "~" + deli + "~" + msg + "~" + tax_address;

                            DBconnection dbconn = new DBconnection();
                            dbconn.ExecuteQuery("update data_field_master set Data_Fields_Text='" + descriptionN + "' where Id = '" + 463 + "'");

                            gc.insert_date(orderNumber, parcel_id, 463, taxInfo1, 1, DateTime.Now);
                            gc.insert_date(orderNumber, parcel_id, 463, taxInfo11, 1, DateTime.Now);

                            //Assessment details
                            Output1A.Add(driver.FindElement(By.Id("txtPriorYear")).Text.Trim());
                            Output2A.Add(driver.FindElement(By.Id("txtCurrentYear")).Text.Trim());


                            Output1A.Add(driver.FindElement(By.Id("txtPriorMarketValue")).Text.Trim());
                            Output2A.Add(driver.FindElement(By.Id("txtCurrentEstimatedMarketValue")).Text.Trim());


                            Output1A.Add(driver.FindElement(By.Id("txtPriorHmstdExclusion")).Text.Trim());
                            Output2A.Add(driver.FindElement(By.Id("txtCurrentHmstdExclusion")).Text.Trim());

                            Output1A.Add(driver.FindElement(By.Id("txtPriorTaxableMarketValue")).Text.Trim());
                            Output2A.Add(driver.FindElement(By.Id("txtCurrentTaxableMarketValue")).Text.Trim());


                            Output1A.Add(driver.FindElement(By.Id("txtPriorNewImprovements")).Text.Trim());
                            Output2A.Add(driver.FindElement(By.Id("txtCurrentNewImprovements")).Text.Trim());


                            Output1A.Add(driver.FindElement(By.Id("txtPriorValueClass1")).Text.Trim());
                            Output2A.Add(driver.FindElement(By.Id("txtValueClass1")).Text.Trim());
                            string Assessemt1 = Output1A[0] + "~" + Output1A[1] + "~" + Output1A[2] + "~" + Output1A[3] + "~" + Output1A[4] + "~" + Output1A[5];
                            string Assessemt11 = Output2A[0] + "~" + Output2A[1] + "~" + Output2A[2] + "~" + Output2A[3] + "~" + Output2A[4] + "~" + Output2A[5];

                            gc.insert_date(orderNumber, parcel_id, 462, Assessemt1, 1, DateTime.Now);
                            gc.insert_date(orderNumber, parcel_id, 462, Assessemt11, 1, DateTime.Now);



                            //download taxbill
                            try
                            {
                                IWebElement Itaxbill5 = driver.FindElement(By.Id("hplTaxStmntPDF"));
                                string URL15 = Itaxbill5.GetAttribute("href");
                                gc.downloadfile(URL15, orderNumber, parcel_id, "TaxBill1", "MN", "Dakota");
                            }
                            catch
                            { }

                        }



                    }
                    TaxTime = DateTime.Now.ToString("HH:mm:ss");
                    LastEndTime = DateTime.Now.ToString("HH:mm:ss");
                    gc.insert_TakenTime(orderNumber, "MN", "Dakota", StartTime, AssessmentTime, TaxTime, CitytaxTime, LastEndTime);


                    driver.Quit();
                    HttpContext.Current.Session["TitleFlex_Search"] = "";

                    gc.mergpdf(orderNumber, "MN", "Dakota");
                    return "Data Inserted Successfully";
                }

                catch (Exception ex)
                {
                    driver.Quit();
                    throw ex;
                }
            }
        }
Example #25
0
        private static IWebDriver _CreateInstance(DesiredCapabilities caps, Drivers driver)
        {
            IWebDriver _webdriver = null;

            if (caps == null)
            {
                //
                // Loaded default caps for RemoteWebDriver from Selenium.Tests.dll.config in current Dll directory
                // See brian.ku about user/key
                //
                caps = new DesiredCapabilities();
                caps.SetCapability("browserstack.user", ConfigurationManager.AppSettings["browserstack.user"]);
                caps.SetCapability("browserstack.key", ConfigurationManager.AppSettings["browserstack.key"]);
                caps.SetCapability("browser", ConfigurationManager.AppSettings["browser"]);
                caps.SetCapability("browser_version", ConfigurationManager.AppSettings["browser_version"]);
                caps.SetCapability("os", ConfigurationManager.AppSettings["os"]);
                caps.SetCapability("os_version", ConfigurationManager.AppSettings["os_version"]);
                caps.SetCapability("resolution", ConfigurationManager.AppSettings["resolution"]);
                caps.SetCapability("browserstack.debug", ConfigurationManager.AppSettings["browserstack.debug"]);
                caps.SetCapability("browserstack.local", ConfigurationManager.AppSettings["browserstack.local"]);
            }
            switch (driver)
            {
            case Drivers.IEDriver:
                InternetExplorerDriverService ieService = InternetExplorerDriverService.CreateDefaultService();
                _webdriver = new InternetExplorerDriver(ieService, new InternetExplorerOptions(), TimeSpan.FromSeconds(3 * 60));
                break;

            case Drivers.ChromeDriver:
                ChromeOptions chromeOptions = new ChromeOptions();
                chromeOptions.AddExcludedArgument("ignore-certifcate-errors");
                chromeOptions.AddArgument("test-type");
                _webdriver = new ChromeDriver(chromeOptions);
                _webdriver.Manage().Window.Maximize();
                break;

            case Drivers.FirefoxDriver:
                FirefoxProfile profile = new FirefoxProfile();
                _webdriver = new FirefoxDriver(profile);
                _webdriver.Manage().Window.Maximize();
                break;

            case Drivers.BrowserStack:
                caps.SetCapability("ensureCleanSession", true);
                _webdriver = new RemoteWebDriver(new Uri(ConfigurationManager.AppSettings["remotewebdriver_url"]), caps);
                //_webdriver.Manage().Window.Maximize();
                break;

            case Drivers.LocalStack:
                //
                // Start the local BrowserStack proxy for cloud browser access
                //
                bool bConnected = false;
                do
                {
                    //
                    // Reset the stdout capture
                    //
                    sbOutput = new StringBuilder();

                    //
                    // check if connection succeeeded
                    //
                    bConnected = LaunchBrowserStackLocalProcess();
                } while (!bConnected);

                _webdriver = new RemoteWebDriver(new Uri(ConfigurationManager.AppSettings["remotewebdriver_url"]), caps, TimeSpan.FromMinutes(5.0));
                break;
            }
            //
            // Set an implicit timeout for all FindElements
            //
            _webdriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(Factory.DefaultTimeoutValue));

            return(_webdriver);
        }
Example #26
0
        public IWebDriver InitiliaseDriver()
        {
            Excel excel      = new Excel();
            var   configData = new List <string>();

            configData = excel.readBrowserData(_commonFunctions.getSolutionPath() + "\\data.xlsx");
            string hubURL      = configData[4];
            string Browser     = configData[0];
            string HeadlesMode = configData[3];

            BrowserValue = Browser;
            string URL = excel.readExcel(_commonFunctions.getSolutionPath() + "\\data.xlsx", getEnv(), 1, 2);

            string grid_status = configData[2];

            if (grid_status.Equals("No"))
            {
                switch (Browser)
                {
                case "Chrome":
                    if (HeadlesMode.Equals("Yes"))
                    {
                        var chromeOptions = new ChromeOptions();
                        chromeOptions.AddArguments("headless");

                        Driver = new ChromeDriver(chromeOptions);
                        // Starting chrome headless
                    }
                    else
                    {
                        var chromeOptions = new ChromeOptions();

                        Driver = new ChromeDriver();
                    }
                    break;

                case "IE":
                    Driver = new InternetExplorerDriver();
                    break;

                case "Firefox":
                    if (HeadlesMode.Equals("Yes"))
                    {
                        FirefoxOptions options = new FirefoxOptions();
                        options.AddArguments("--headless");
                        Driver = new FirefoxDriver(options);
                        // Starting firefox headless
                    }
                    else
                    {
                        Driver = new FirefoxDriver();
                    }
                    break;
                }

                Driver.Manage().Window.Maximize();
                Driver.Navigate().GoToUrl(URL);

                return(Driver);
            }
            else
            {
                DesiredCapabilities capabilities = new DesiredCapabilities();
                switch (Browser)
                {
                case "Firefox":

                    FirefoxOptions options = new FirefoxOptions();
                    if (HeadlesMode.Equals("Yes"))
                    {
                        options.AddArguments("--headless");
                        Driver = new FirefoxDriver(options);

                        // Starting firefox headless in grid
                    }
                    else
                    {
                        Driver = new FirefoxDriver();
                    }
                    capabilities = options.ToCapabilities() as DesiredCapabilities;

                    capabilities.SetCapability(CapabilityType.BrowserName, "firefox");
                    capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.WinNT));
                    break;

                case "Chrome":

                    var chromeOptions = new ChromeOptions();
                    if (HeadlesMode.Equals("Yes"))
                    {
                        chromeOptions.AddArgument("--headless");
                    }

                    else
                    {
                        // var chromeOptions = new ChromeOptions();
                        chromeOptions.AddArguments("user-data-dir=C:/Users/isa/AppData/Local/Google/Chrom/User Data/Default");
                        Driver = new ChromeDriver(chromeOptions);
                        // Driver = new ChromeDriver();
                    }

                    capabilities = chromeOptions.ToCapabilities() as DesiredCapabilities;
                    // capabilities.SetCapability(ChromeOptions.Capability, chromeOptions);
                    capabilities.SetCapability(CapabilityType.BrowserName, "chrome");
                    capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.WinNT));

                    break;
                }
                Driver = new RemoteWebDriver(new Uri(hubURL), capabilities);
                Driver.Manage().Window.Maximize();
                Driver.Navigate().GoToUrl(URL);

                return(Driver);
            }
        }
        public void SetupTest()

        {
            login = TestContext.Parameters.Get("loginCCM");
            senha = TestContext.Parameters.Get("senhaCCM");

            Global.PathDoProjeto = Directory.GetCurrentDirectory();
            Global.PathDoProjeto = Global.PathDoProjeto.Substring(0, Global.PathDoProjeto.IndexOf("bin"));


            Global.processTest = new ProcessTest();
            if (Global.reportId != 0)
            {
                Global.processTest.ReportID = Global.reportId;
            }

            Global.consulta = new ClsCCM();
            Global.processTest.mostrarLog = false;
            var options = new ChromeOptions();
            var os      = Environment.OSVersion;

            Global.OSLinux = os.Platform == PlatformID.Unix;
            ChromeDriverService service = null;

            PathDoExecutavel = @System.Environment.CurrentDirectory.ToString();


            if (Global.OSLinux)
            {
                PathChromeDriver = "/usr/bin/";
                //PathChromeDriver = Global.PathDoProjeto;
                //PathChromeDriver = Global.PathDoProjeto.Substring(0, Global.PathDoProjeto.IndexOf("NUnit_NetCore"));
                service = ChromeDriverService.CreateDefaultService(PathChromeDriver, "chromedriver");
                options.AddArgument("--headless");
                options.AddArgument("use-fake-ui-for-media-stream");
            }
            else
            {
                PathChromeDriver = PathDoExecutavel;
                service          = ChromeDriverService.CreateDefaultService(PathChromeDriver, "chromedriver.exe");
                //options.AddArgument("--headless");
            }

            Global.processTest.PastaBase    = Global.PathDoProjeto;
            Global.processTest.CustomerName = "Kabum"; //CustomerName evitar Acentuacao e espaço
            Global.processTest.SuiteName    = "CCM";   //CustomerName evitar Acentuacao e espaço
            Global.processTest.ScenarioName = MethodBase.GetCurrentMethod().DeclaringType.Name;


            options.AddArgument("--no-sandbox");
            options.AddArgument("--disable-dev-shm-usage");
            options.AddArgument("--disable-gpu");
            options.AddArgument("--touch-events=enabled");
            options.AddArgument("--start-maximized");
            //options.AddArgument("use-fake-ui-for-media-stream");
            //options.EnableMobileEmulation(tipoTeste);
            Global.driver             = new ChromeDriver(service, options);
            processosCCM              = new ProcessosCCM();
            baseURL                   = "https://www.uol.com.br/";
            Global.verificationErrors = new StringBuilder();
        }
Example #28
0
        public ZoomModel(string username, string password, BackgroundWorker bw, bool justZoom)
        {
            bool looping = true;

            while (looping)
            {
                ChromeDriverService service = ChromeDriverService.CreateDefaultService(App.Folder);
                service.HideCommandPromptWindow = true;

                ChromeOptions options = new ChromeOptions();
                options.AddArgument("start-maximized");
                options.AddArgument("user-data-dir=" + App.Folder + "profileZB");

                IWebDriver driver = new ChromeDriver(service, options);
                driver.Navigate().GoToUrl("http://members.grabpoints.com/#/login?email=" + username);

                try
                {
                    //driver.FindElement(By.Name("email")).SendKeys(username);
                    //driver.FindElement(By.Name("email")).SendKeys(Keys.Enter);
                    ////Helpers.wait(5000);
                    driver.FindElement(By.Id("password")).SendKeys(password);
                    driver.FindElement(By.ClassName("btn-block")).Click();
                }
                catch { }

                Helpers.wait(10000);
                if (!justZoom)
                {
                    try
                    {
                        int counter = 0;
                        IList <IWebElement> turnOffNotifcations = driver.FindElements(By.ClassName("btn-block"));
                        if (!Helpers.findText(driver, "Milestones"))
                        {
                            foreach (IWebElement turnOffNotication in turnOffNotifcations)
                            {
                                if (counter == turnOffNotifcations.Count - 1)
                                {
                                    turnOffNotication.Click();
                                }
                                counter++;
                            }
                        }
                        else
                        {
                            foreach (IWebElement turnOffNotication in turnOffNotifcations)
                            {
                                if (counter == 1)
                                {
                                    turnOffNotication.Click();
                                }
                                counter++;
                            }
                        }
                    }
                    catch { }

                    int hr = DateTime.Now.Hour;

                    try
                    {
                        driver.Navigate().GoToUrl("http://members.grabpoints.com/#/offers/watch_videos");
                    }
                    catch { }

                    while (!viroolBool)
                    {
                        try
                        {
                            System.Collections.ObjectModel.ReadOnlyCollection <string> windowHandles = driver.WindowHandles;

                            foreach (String window in windowHandles)
                            {
                                try
                                {
                                    IWebDriver popup = driver.SwitchTo().Window(window);
                                }
                                catch { }

                                try
                                {
                                    if (driver.Title.Contains("Facebook"))
                                    {
                                        driver.Close();
                                    }
                                }
                                catch { }

                                try
                                {
                                    IList <IWebElement> surveys = driver.FindElements(By.ClassName("btn-block"));
                                    if (surveys.Count > 2)
                                    {
                                        driver.FindElement(By.ClassName("btn-block")).Click();
                                    }
                                }
                                catch { }

                                if (!junVideos)
                                {
                                    junVids(driver);
                                }
                                if (!volume)
                                {
                                    volume11(driver);
                                }
                                if (volume && junVideos && !viroolBool)
                                {
                                    virool(driver);
                                }
                                Helpers.wait(5000);
                            }
                        }
                        catch { }
                    }

                    Helpers.closeWindows(driver, titles);
                    driver.Close();
                    driver.Quit();

                    hr = DateTime.Now.Hour;

                    while (DateTime.Now.Hour == hr)
                    {
                    }
                    junVideos  = false;
                    volume     = false;
                    viroolBool = false;
                }
                else
                {
                    looping = false;
                }
            }
        }
Example #29
0
 protected CustomChromeDriver(ChromeDriverService service, ChromeOptions profile, TimeSpan commandTimeout) :
     base(service, profile, commandTimeout)
 {
     //this.Manage().Timeouts().ImplicitWait = commandTimeout;// svt2 //SetScriptTimeout(commandTimeout);
 }
Example #30
0
        //Pega os arquivos (edital e anexos) da licitação e depois os deleta
        private static void GetFiles(Licitacao licitacao)
        {
            try
            {
                //var webdriver = WebDriverChrome.LoadWebDriver(name);
                //web = webdriver.Item1;
                //wait = webdriver.Item2;
                if (web != null)
                {
                    web.Quit();
                }

                var driver = ChromeDriverService.CreateDefaultService();
                driver.HideCommandPromptWindow = true;
                var op = new ChromeOptions();
                op.AddUserProfilePreference("download.default_directory", pathEditais);
                web = new ChromeDriver(driver, new ChromeOptions(), TimeSpan.FromSeconds(300));
                web.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(300);
                wait = new WebDriverWait(web, TimeSpan.FromSeconds(300));

                //Cria diretório específico para os arquivos
                if (!Directory.Exists(pathEditais))
                {
                    Directory.CreateDirectory(pathEditais);
                }

                web.Navigate().GoToUrl(licitacao.LinkEdital);

                if (web.PageSource.Contains("Arquivos"))
                {
                    var accordionItems = web.FindElements(By.ClassName("ui-accordion-header"));

                    foreach (var item in accordionItems)
                    {
                        try
                        {
                            if (item.Text.Contains("Arquivos"))
                            {
                                item.Click();
                                break;
                            }
                        }
                        catch (Exception e)
                        {
                            RService.Log("Exception (GetFiles/Accordion) " + e.Message + " at {0}", logPath);
                        }
                    }
                }

                var downloadButtons = web.FindElements(By.ClassName("ui-button-text-icon-left"));

                foreach (var button in downloadButtons)
                {
                    try
                    {
                        button.Click();
                        Thread.Sleep(10000);
                    }
                    catch (Exception e)
                    {
                        RService.Log("Exception (GetFiles/FileButton) " + e.Message + " at {0}", logPath);
                    }
                }

                string[] files = Directory.GetFiles(pathEditais);

                foreach (var file in files)
                {
                    string fileName = file.Split('/')[1];
                    if (!string.IsNullOrEmpty(fileName))
                    {
                        #region AWS
                        RService.Log("(GetFiles) " + name + ": Enviando o arquivo para Amazon S3... " + fileName + " at {0}", logPath);

                        if (AWS.SendObject(licitacao, pathEditais, fileName))
                        {
                            LicitacaoArquivo licitacaoArq = new LicitacaoArquivo();
                            licitacaoArq.NomeArquivo         = fileName;
                            licitacaoArq.NomeArquivoOriginal = name + DateTime.Now.ToString("yyyyMMddHHmmss");
                            licitacaoArq.NomeArquivoFonte    = name;
                            licitacaoArq.Status      = 0;
                            licitacaoArq.IdLicitacao = licitacao.Id;

                            LicitacaoArquivoRepository repoArq = new LicitacaoArquivoRepository();
                            repoArq.Insert(licitacaoArq);

                            if (File.Exists(pathEditais + fileName))
                            {
                                File.Delete(pathEditais + fileName);
                            }

                            RService.Log("(GetFiles) " + name + ": Arquivo " + fileName + " enviado com sucesso para Amazon S3" + " at {0}", logPath);
                        }
                        else
                        {
                            RService.Log("Exception (GetFiles) " + name + ": Erro ao enviar o arquivo para Amazon (CreateLicitacaoArquivo) {0}", logPath);
                        }

                        #endregion
                    }
                }
            }
            catch (Exception e)
            {
                RService.Log("Exception (GetFiles) " + name + ": " + e.Message + " / " + e.StackTrace + " / " + e.InnerException + " / " + e.InnerException + " at {0}", logPath);
            }
        }