Example #1
0
        /// <summary>
        /// Open the new Chrome Browser and return the chrome driver as IwebDriver
        /// Note: this fucntion will close the chrome/chromedriver if its opened already, otherwise new chrome driver will not work perfectly
        /// Note: Ensure the chromedriver is downloaded and placed into your exe folder
        /// </summary>
        /// <returns></returns>
        public IWebDriver openChrome()
        {
            OpenQA.Selenium.Chrome.ChromeOptions choptions = new OpenQA.Selenium.Chrome.ChromeOptions();
            //choptions.BinaryLocation = "C:\\Program Files\\Google\\\\Application\\Chrom.exe";
            choptions.AddArgument("--test-type");
            choptions.AddArgument("--disable-plugins");
            choptions.AddArgument("--disable-extensions");
            //choptions.AddArgument("--enable-automation");
            choptions.AddArgument("--no-sandbox");
            choptions.AddUserProfilePreference("credentials_enable_service", false);
            choptions.AddUserProfilePreference("profile.password_manager_enabled", false);
            //choptions.AddArgument("--start-maximized");

            //choptions.AddArgument("--allow-external-pages");
            //choptions.AddArgument("--allow-running-insecure-content");
            //choptions.AddArgument("--new-window");
            //choptions.AddArguments("--enable-strict-powerful-feature-restrictions");
            //choptions.AddUserProfilePreference("profile.default_content_setting_values.images", 0);

            //Close the previous  driver is it have opened
            foreach (System.Diagnostics.Process proTem in System.Diagnostics.Process.GetProcessesByName("chromedriver"))
            {
                proTem.CloseMainWindow();
            }
            //Close the chrome browser if its opened already
            foreach (System.Diagnostics.Process proTem in System.Diagnostics.Process.GetProcessesByName("chrome"))
            {
                proTem.CloseMainWindow();
            }

            //Open the new
            return(new OpenQA.Selenium.Chrome.ChromeDriver(strchromedriver, choptions, new TimeSpan(0, 5, 0)));
        }
Example #2
0
        public void StartGeeTest(Uri uri)
        {
            const int waitTime = 500;
            var       options  = new OpenQA.Selenium.Chrome.ChromeOptions();

            //options.AddArgument("-headless");//不显示界面
            options.AddArgument("--window-size=1920,1050");
            options.AddArgument("log-level=3");
            using OpenQA.Selenium.Chrome.ChromeDriver driver = new OpenQA.Selenium.Chrome.ChromeDriver(options);
            driver.Navigate().GoToUrl(uri);
            //反爬验证webdriver
            driver.ExecuteJavaScript("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})");
            driver.Navigate().GoToUrl(uri);
            Thread.Sleep(waitTime);//等待js执行
            driver.ExecuteScript("header.loginLink(event)");
            Console.WriteLine("点击《登录/注册》按钮");
            Thread.Sleep(waitTime);
            driver.ExecuteScript("loginObj.changeCurrent(1);");
            Console.WriteLine("点击 《密码登录》按钮");
            Thread.Sleep(waitTime);
            driver.ExecuteScript("$('.contactphone').val('17712345678')");
            driver.ExecuteScript("$('.contactword').val('2020')");
            Console.WriteLine("输入账号密码");
            Thread.Sleep(waitTime);
            driver.ExecuteScript("loginObj.loginByPhone(event);");
            Console.WriteLine("点击《登录》按钮");
            Thread.Sleep(waitTime);
            SeleniumVertifyCode slideVerificationCode = new SeleniumVertifyCode();
            var flag = slideVerificationCode.Pass(driver);

            Console.WriteLine($"验证结果{flag}");
        }
        public void Setup()
        {
            var options = new OpenQA.Selenium.Chrome.ChromeOptions();


            //options.AddArgument("--lang=locale-of-choice");
            options.AddArgument("--lang=ru");
            options.AddArgument("--cr=countryRU");


            options.BinaryLocation = @"C:\Program Files\Google\Chrome\Application\chrome.exe";
            driver = new OpenQA.Selenium.Chrome.ChromeDriver(options);
            driver.Manage().Window.Maximize();

            driver.Navigate().GoToUrl("https://www.google.com/preferences?hl=ru-UA&fg=1");

            IWebElement click_slower = driver.FindElement(By.Id("result_slider"));

            click_slower.Click();

            IWebElement click_more = driver.FindElement(By.Id("regionanchormore"));

            click_more.Click();

            IWebElement choose_region = driver.FindElement(By.Id("regionoRU"));

            choose_region.Click();

            Thread.Sleep(1000);

            By  click_save_button    = By.XPath("//div[@class='goog-inline-block jfk-button jfk-button-action']");
            var clicking_save_button = driver.FindElement(click_save_button);

            clicking_save_button.Click();
        }
Example #4
0
        private void button1_Click(object sender, EventArgs e)
        {
            OpenQA.Selenium.Chrome.ChromeOptions co = new OpenQA.Selenium.Chrome.ChromeOptions();
            co.AddArgument(@"user-data-dir=c:\Users\Conroe\AppData\Local\Google\Chrome\User Data\");
            Brouser = new OpenQA.Selenium.Chrome.ChromeDriver(co);
            Brouser.Navigate().GoToUrl("https://vk.com/audio");

            IJavaScriptExecutor jse = Brouser as  IJavaScriptExecutor;

            for (int i = 10; i > 0; i--)
            {
                jse.ExecuteScript("window.scrollBy(1000,2500000)");
                Thread.Sleep(2000);
            }

            jse.ExecuteScript("window.scrollBy(1000,2500000)");
            List <IWebElement> VkAudioArtist        = Brouser.FindElements(By.ClassName("audio_performer")).ToList();
            List <IWebElement> VkAudioTrack         = Brouser.FindElements(By.ClassName("audio_title")).ToList();
            List <IWebElement> VkAudioTrackDuration = Brouser.FindElements(By.ClassName("audio_duration")).ToList();


            for (int i = 0; i < VkAudioArtist.Count; i++)
            {
                textBox1.AppendText(i + ": " + VkAudioArtist[i].Text + "-" + VkAudioTrack[i].Text + " " + VkAudioTrackDuration[i].Text + "\r\n");
            }
        }
Example #5
0
        protected OpenQA.Selenium.Remote.RemoteWebDriver GetWebDriver(WebDriverType webDriver)
        {
            switch (webDriver)
            {
            case WebDriverType.Chrome:
                var driverService = OpenQA.Selenium.Chrome.ChromeDriverService.CreateDefaultService();
                driverService.HideCommandPromptWindow = true;
                var options = new OpenQA.Selenium.Chrome.ChromeOptions();
                options.AddArgument("--headless");
                //options.AddArgument("--window-size=100,100");
                return(new OpenQA.Selenium.Chrome.ChromeDriver(driverService, options));

            case WebDriverType.IE:
                throw new NotImplementedException();

            case WebDriverType.Firefox:
                throw new NotImplementedException();

            case WebDriverType.Safari:
                throw new NotImplementedException();

            default:
                throw new ApplicationException();
            }
        }
Example #6
0
 private void button4_Click(object sender, EventArgs e)
 {
     OpenQA.Selenium.Chrome.ChromeOptions co = new OpenQA.Selenium.Chrome.ChromeOptions();
     co.AddArgument(@"user-data-dir=C:\Users\Aram\AppData\Local\Google\Chrome\User Data\");
     //co.AddArgument("--disable-infobars");
     Browser = new OpenQA.Selenium.Chrome.ChromeDriver(co);
     //Browser.Navigate().GoToUrl("http://yandex.ru");
 }
Example #7
0
        private void EnterOnSite()
        {
            if (selectBrowser == 0)
            {
                var serv = OpenQA.Selenium.Chrome.ChromeDriverService.CreateDefaultService();
                serv.HideCommandPromptWindow = true;
                var options = new OpenQA.Selenium.Chrome.ChromeOptions();
                if (!visBr.Checked)
                {
                    options.AddArgument("--window-position=-32000,-32000");
                }



                //  Brow.SwitchTo
                Brow = new OpenQA.Selenium.Chrome.ChromeDriver(serv, options);
            }
            else
            {
                var serv = OpenQA.Selenium.Firefox.FirefoxDriverService.CreateDefaultService();// Chrome.ChromeDriverService.CreateDefaultService();
                serv.HideCommandPromptWindow = true;
                var options = new OpenQA.Selenium.Firefox.FirefoxOptions();
                if (!visBr.Checked)
                {
                    options.AddArgument("--window-position=-32000,-32000");
                }


                var pos = !visBr.Checked? new Point(32000, 32000): new Point(0, 0);

                Brow = new OpenQA.Selenium.Firefox.FirefoxDriver(serv, options, TimeSpan.FromSeconds(30));
                Brow.Manage().Window.Position = pos;
            }

            //Brow.Manage().Timeouts().ImplicitlyWait( ();
            //Brow.Manage().Window.Size.Heig
            WebDriverWait wait = new WebDriverWait(Brow, TimeSpan.FromSeconds(10));

            //WebDriverWait wait = new WebDriverWait(driver, 10);
            Brow.Navigate().GoToUrl("https://bitrix24.net.ua/");

            //selivanovsky.i
            //    silvergraf


            IWebElement log = wait.Until(ExpectedConditions.ElementIsVisible(By.Name("USER_LOGIN")));

            log.SendKeys(login);
            IWebElement pas = Brow.FindElement(By.Name("USER_PASSWORD"));

            pas.SendKeys(pasword + OpenQA.Selenium.Keys.Enter);
            System.Threading.Thread.Sleep(selectBrowser == 0?700:5000);

            Brow.Close();
            Brow.Dispose();
            Loger.SetLog(login);
        }
Example #8
0
        private void SeleniumVertifyCode(Uri uri)
        {
            var options = new OpenQA.Selenium.Chrome.ChromeOptions();

            options.AddArgument("-headless");
            options.AddArgument("log-level=3");
            using IWebDriver driver = new OpenQA.Selenium.Chrome.ChromeDriver(options);
            driver.Manage().Window.Maximize();
            driver.Navigate().GoToUrl(uri);
            driver.Manage().Cookies.AddCookie(new Cookie("QCCSESSID", Cookie, ".qcc.com", "/", null));
            driver.Navigate().GoToUrl(uri);
            driver.ExecuteJavaScript("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})");
            var slide           = driver.FindElement(By.CssSelector("#nc_1_n1z"));
            var verifyContainer = driver.FindElement(By.CssSelector(".nc-lang-cnt"));
            var width           = verifyContainer.Size.Width;
            var action          = new Actions(driver);

            action.ClickAndHold(slide).Perform();
            Random    random    = new Random();
            int       offset    = 0;
            const int minOffset = 10;
            const int maxOffset = 30;

            while (width > offset)
            {
                offset += random.Next(minOffset, maxOffset);
                action.MoveByOffset(offset, 0).Perform();
                var code = driver.FindElement(By.CssSelector(".nc-lang-cnt")).Text;
                if (code.Contains("验证通过"))
                {
                    break;
                }
                System.Threading.Thread.Sleep(offset * minOffset);
            }
            //截图测试
            //Screenshot screenShotFile = ((ITakesScreenshot)driver).GetScreenshot();
            //string img_url = Environment.CurrentDirectory + "\\test.png";
            //screenShotFile.SaveAsFile(img_url, ScreenshotImageFormat.Png);
            action.Click(driver.FindElement(By.CssSelector("#verify"))).Perform();
            driver.Quit();
        }
Example #9
0
        public IWebDriver OpenBrowser(string PathToDrivers)
        {
            if (GetBrowserType() == BrowserType.Chrome)
            {
                OpenQA.Selenium.Chrome.ChromeOptions options = new OpenQA.Selenium.Chrome.ChromeOptions();

                options.AddArgument("--start-maximized");
                options.AddArgument("--ignore-certificate-errors");
                options.AddArgument("--disable-popup-blocking");
                options.AddArgument("--safebrowsing-disable-download-protection");
                options.AddArgument("--incognito");
                if (headless.ToLower() == "yes")
                {
                    options.AddArgument("--headless");
                }
                options.AddUserProfilePreference("download.prompt_for_download", false);
                options.AddUserProfilePreference("disable-popup-blocking", true);
                //options.AddUserProfilePreference("safebrowsing.enabled", true);
                options.AddUserProfilePreference("safebrowsing", "enabled");

                driv = new OpenQA.Selenium.Chrome.ChromeDriver(PathToDrivers, options);
            }

            return(driv);
        }
Example #10
0
        private IWebDriver OpenBrowser(string BrowserType, string Headless = "")
        {
            if (BrowserType.ToLower() == "chrome")
            {
                OpenQA.Selenium.Chrome.ChromeOptions options = new OpenQA.Selenium.Chrome.ChromeOptions();

                options.AddArgument("--start-maximized");
                options.AddArgument("--ignore-certificate-errors");
                options.AddArgument("--disable-popup-blocking");
                options.AddArgument("--safebrowsing-disable-download-protection");
                options.AddArgument("--incognito");

                if (Headless.ToLower() == "yes" || Headless == "")
                {
                    options.AddArgument("--headless");
                }
                options.AddUserProfilePreference("download.prompt_for_download", false);
                options.AddUserProfilePreference("disable-popup-blocking", true);
                options.AddUserProfilePreference("safebrowsing", "enabled");

                IWebDriver driv = new OpenQA.Selenium.Chrome.ChromeDriver(options);
                return(driv);
            }

            else
            {
                return(new OpenQA.Selenium.Firefox.FirefoxDriver());
            }
        }
Example #11
0
        public ScriptRunner(string pathToGecko)
        {
            OpenQA.Selenium.Chrome.ChromeOptions options = new OpenQA.Selenium.Chrome.ChromeOptions();
            options.PageLoadStrategy = PageLoadStrategy.Normal;
            options.AddArgument("--no-sandbox");
            options.AddArgument("--disable-blink-features");
            options.AddArgument("--disable-blink-features=AutomationControlled");
            options.AddArgument("disable-gpu");
            // options.AddArgument("--headless");

            if (string.IsNullOrEmpty(pathToGecko))
            {
                pathToGecko = Directory.GetCurrentDirectory();
            }

            driver = new OpenQA.Selenium.Chrome.ChromeDriver(pathToGecko, options);
            var parameters = new Dictionary <string, object>
            {
                ["source"] = "Object.defineProperty(navigator, 'webdriver', { get: () => undefined })"
            };

            driver.ExecuteChromeCommand("Page.addScriptToEvaluateOnNewDocument", parameters);
        }
Example #12
0
 public void StartBrowser()
 {
     OpenQA.Selenium.Chrome.ChromeOptions chromeOptions = new OpenQA.Selenium.Chrome.ChromeOptions();
     chromeOptions.AddArgument("--headless");
     this.driver = new ChromeDriver(chromeOptions: chromeOptions, projectName: "CI - C#");
 }
Example #13
0
        /// <summary>
        /// Método sem recaptcha
        /// </summary>
        /// <param name="linhaDigitavel">Linha digitável do boleto</param>
        public static void Consultar(string cnpj, string id, string linhaDigitavel, string cpfCnpjPagador)
        {
            IWebDriver driver = null;

            try
            {
                //Trata linha digitável
                linhaDigitavel = linhaDigitavel.Replace(".", string.Empty).Replace(" ", string.Empty);

                #region Diretório / Arquivos

                DirectoryInfo directoryInfo = new System.IO.DirectoryInfo("Boletos");
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }

                directoryInfo = new System.IO.DirectoryInfo(Path.Combine(directoryInfo.FullName, cnpj));
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }

                directoryInfo = new System.IO.DirectoryInfo(Path.Combine(directoryInfo.FullName, string.Format("{0:yyyy-MM-dd}", DateTime.Now)));
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }

                FileInfo fileInfo = new System.IO.FileInfo(Path.Combine(directoryInfo.FullName, "Boletos.pdf"));
                if (fileInfo.Exists)
                {
                    fileInfo.Delete();
                }

                #endregion Diretório / Arquivo

                #region Chrome - Options

                if (ConfigurationManager.AppSettings["selenium_webdriver"] == "chrome")
                {
                    OpenQA.Selenium.Chrome.ChromeDriverService chromeService = OpenQA.Selenium.Chrome.ChromeDriverService.CreateDefaultService();
                    chromeService.HideCommandPromptWindow = true;
                    chromeService.SuppressInitialDiagnosticInformation = true;

                    OpenQA.Selenium.Chrome.ChromeOptions chromeOptions = new OpenQA.Selenium.Chrome.ChromeOptions();
                    chromeOptions.AddUserProfilePreference("download.default_directory", directoryInfo.FullName);
                    chromeOptions.AddUserProfilePreference("download.prompt_for_download", false);
                    chromeOptions.AddUserProfilePreference("disable-popup-blocking", "true");

                    //Disable
                    chromeOptions.AddArgument("disable-infobars");
                    //chromeOptions.AddArgument("headless");Utilizado para suprimir a exibição da janela do chrome

                    driver = new OpenQA.Selenium.Chrome.ChromeDriver(chromeService, chromeOptions);
                }

                #endregion Chrome - Options

                #region Firefox - Options

                if (ConfigurationManager.AppSettings["selenium_webdriver"] == "firefox")
                {
                    /*
                     * Firefoz config options
                     *
                     * http://kb.mozillazine.org/About:config_entries#Browser.
                     * */

                    //Create FireFox Service
                    OpenQA.Selenium.Firefox.FirefoxDriverService firefoxService = OpenQA.Selenium.Firefox.FirefoxDriverService.CreateDefaultService();
                    firefoxService.HideCommandPromptWindow = true;
                    firefoxService.SuppressInitialDiagnosticInformation = true;

                    //Create FireFox Profile object
                    OpenQA.Selenium.Firefox.FirefoxOptions firefoxOptions = new OpenQA.Selenium.Firefox.FirefoxOptions();

                    //Set location to store files after downloading.
                    firefoxOptions.SetPreference("browser.download.folderList", 2);
                    firefoxOptions.SetPreference("browser.helperApps.alwaysAsk.force", false);
                    firefoxOptions.SetPreference("browser.download.manager.focusWhenStarting", false);
                    firefoxOptions.SetPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false);
                    firefoxOptions.SetPreference("pdfjs.disabled", true);
                    firefoxOptions.SetPreference("browser.download.dir", directoryInfo.FullName);

                    //Set Preference to not show file download confirmation dialogue using MIME types Of different file extension types.
                    firefoxOptions.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");

                    // Use this to disable Acrobat plugin for previewing PDFs in Firefox (if you have Adobe reader installed on your computer)
                    firefoxOptions.SetPreference("plugin.scan.Acrobat", "99.0");
                    firefoxOptions.SetPreference("plugin.scan.plid.all", false);

                    //Pass profile parameter In webdriver to use preferences to download file.
                    driver = new OpenQA.Selenium.Firefox.FirefoxDriver(firefoxService, firefoxOptions);
                }

                #endregion Firefox - Options

                if (driver == null)
                {
                    throw new Exception("WebDriver do Selenium não definido nas configurações");
                }

                driver.Navigate().GoToUrl("https://www.itau.com.br/servicos/boletos/atualizar/");

                //Aguarda processamento da página
                WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60));

                //Textbox
                var elem = wait.Until(d =>
                {
                    try
                    {
                        var ele = d.FindElement(By.Id("representacaoNumerica"));
                        return(ele.Displayed ? ele : null);
                    }
                    catch (UnhandledAlertException)
                    {
                        return(null);
                    }
                    catch (StaleElementReferenceException)
                    {
                        return(null);
                    }
                    catch (NoSuchElementException)
                    {
                        return(null);
                    }
                });


                //Preenche os dados da pesquisa
                driver.FindElement(By.Id("representacaoNumerica")).SendKeys(linhaDigitavel);
                driver.FindElement(By.Id("txtDocumentoSacado")).SendKeys(cpfCnpjPagador);
                driver.FindElement(By.Id("btnProximo")).Click();

                //Aguarda
                System.Threading.Thread.Sleep(2500);

                //Acessa aba aerta
                driver.SwitchTo().Window(driver.WindowHandles.Last());

                //Botão de cownload
                elem = wait.Until(d =>
                {
                    try
                    {
                        var ele = d.FindElement(By.Name("frmPDF"));
                        return(ele.Displayed ? ele : null);
                    }
                    catch (UnhandledAlertException)
                    {
                        return(null);
                    }
                    catch (StaleElementReferenceException)
                    {
                        return(null);
                    }
                    catch (NoSuchElementException)
                    {
                        return(null);
                    }
                });

                //Download
                ((IJavaScriptExecutor)driver).ExecuteScript("javascript:document.frmPDF.submit();");

                //Aguarda
                System.Threading.Thread.Sleep(3000);

                //Renomear
                fileInfo.Refresh();
                if (fileInfo.Exists)
                {
                    fileInfo.MoveTo(Path.Combine(directoryInfo.FullName, string.Format("{0}.pdf", id)));
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (driver != null)
                {
                    driver.Dispose();
                }
            }
        }
Example #14
0
        public void DebugBSMobile(string strMobileDevice)
        {
            Config            = true;
            configurationbool = true;

            if (strMobileDevice == browsertype.android.ToString())
            {
                // ********************** sauce lab capabilities start **********************

                //Thread.Sleep(4000);
                //devicenameBS = ConfigurationManager.AppSettings.Get("androiddeviceNameBS");
                //this.deviceNameAndroid = ConfigurationManager.AppSettings.Get("androiddevice");
                //this.environment = ConfigurationManager.AppSettings.Get("environment");
                //DesiredCapabilities capability = DesiredCapabilities.Android();
                //capability.SetCapability("browserName", "Chrome");
                //capability.SetCapability("platformVersion", "6.1");
                //capability.SetCapability(MobileCapabilityType.BrowserName, MobileBrowserType.Chrome);
                //capability.SetCapability("username", "Sunil21318"); // supply sauce labs username
                //capability.SetCapability("accessKey", "d056215a-a397-414c-923f-e42e0be236b6");  // supply sauce labs account key
                //capability.SetCapability("deviceName", "Android Emulator");
                //capability.SetCapability("tunnel-identifier", Environment.GetEnvironmentVariable("TRAVIS_JOB_NUMBER"));
                //capability.SetCapability("build", Environment.GetEnvironmentVariable("TRAVIS_BUILD_NUMBER"));
                //capability.SetCapability("deviceReadyTimeout", TimeSpan.FromSeconds(120));
                //capability.SetCapability("androidDeviceReadyTimeout", TimeSpan.FromSeconds(120));
                //capability.SetCapability("avdLaunchTimeout", TimeSpan.FromSeconds(120));
                //capability.SetCapability("appWaitDuration", TimeSpan.FromSeconds(120));
                //capability.SetCapability("avdReadyTimeout", TimeSpan.FromSeconds(120));
                //capability.SetCapability("idleTimeout", 120);
                //driver = new RemoteWebDriver(new Uri("http://*****:*****@ondemand.saucelabs.com/wd/hub"), capability, TimeSpan.FromSeconds(120));
                //driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(200));
                //driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(200));

                // ********************** sauce lab capabilities end **********************



                //  ********************** browser stack capabilities start **********************

                Browser = "Chrome";
                Env     = "Android";

                devicenameBS           = ConfigurationManager.AppSettings.Get("androiddeviceNameBS");
                this.deviceNameAndroid = ConfigurationManager.AppSettings.Get("androiddevice");
                this.environment       = ConfigurationManager.AppSettings.Get("environment");
                DesiredCapabilities capability = DesiredCapabilities.Android();
                ChromeOptions       chrOpts    = new ChromeOptions();
                chrOpts.AddArguments("test-type");
                chrOpts.AddArguments("--disable-extensions");
                chrOpts.AddArgument("incognito");
                chrOpts.AddArgument("no-sandbox");
                capability = (DesiredCapabilities)chrOpts.ToCapabilities();
                capability.SetCapability("browserName", "android");
                capability.SetCapability("browserstack.user", browserstack_user); // browser stack username
                capability.SetCapability("browserstack.key", browserstack_key);   // browser stack account key
                capability.SetCapability("deviceName", devicenameBS);
                capability.SetCapability("browserName", "chrome");
                capability.SetCapability("platform", MobilePlatform.Android);
                capability.SetCapability("browserstack.debug", true);
                capability.SetCapability("project", Environment.GetEnvironmentVariable("BS_AUTOMATE_PROJECT"));
                capability.SetCapability("build", Environment.GetEnvironmentVariable("BS_AUTOMATE_BUILD"));
                capability.SetCapability("browserstack.localIdentifier", Environment.GetEnvironmentVariable("BROWSERSTACK_LOCAL_IDENTIFIER"));
                capability.SetCapability("deviceReadyTimeout", TimeSpan.FromSeconds(200));
                capability.SetCapability("androidDeviceReadyTimeout", TimeSpan.FromSeconds(200));
                capability.SetCapability("avdLaunchTimeout", TimeSpan.FromSeconds(200));
                capability.SetCapability("appWaitDuration", TimeSpan.FromSeconds(200));
                capability.SetCapability("avdReadyTimeout", TimeSpan.FromSeconds(200));
                capability.SetCapability("idleTimeout", 300);
                driver = new RemoteWebDriver(new Uri(ConfigurationManager.AppSettings.Get("server")), capability, TimeSpan.FromSeconds(200));
                driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(200));

                // ********************** browser stack capabilities end **********************
            }
            else if (strMobileDevice == browsertype.ios.ToString())
            {
                Browser = "Safari";
                Env     = "IOS";
                Thread.Sleep(4000);
                devicenameBS           = ConfigurationManager.AppSettings.Get("iosdeviceNameBS");
                this.deviceNameAndroid = ConfigurationManager.AppSettings.Get("iosdevice");
                this.environment       = ConfigurationManager.AppSettings.Get("environment");
                DesiredCapabilities desiredCap = DesiredCapabilities.IPhone();
                desiredCap.SetCapability("browserstack.user", browserstack_user);
                desiredCap.SetCapability("browserstack.key", browserstack_key);
                desiredCap.SetCapability("platform", "MAC");
                desiredCap.SetCapability("browserName", "iPhone");
                desiredCap.SetCapability("browserstack.debug", true);
                desiredCap.SetCapability("device", devicenameiphone);
                desiredCap.SetCapability("project", Environment.GetEnvironmentVariable("BS_AUTOMATE_PROJECT"));
                desiredCap.SetCapability("build", Environment.GetEnvironmentVariable("BS_AUTOMATE_BUILD"));
                desiredCap.SetCapability("browserstack.localIdentifier", Environment.GetEnvironmentVariable("BROWSERSTACK_LOCAL_IDENTIFIER"));
                desiredCap.SetCapability("newCommandTimeout", TimeSpan.FromSeconds(120));
                desiredCap.SetCapability("idleTimeout", TimeSpan.FromSeconds(120));
                driver = new RemoteWebDriver(new Uri(ConfigurationManager.AppSettings.Get("server")), desiredCap, TimeSpan.FromSeconds(120));
                // driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(200));
            }
        }
Example #15
0
        public void DebugLocalMobile(string strMobileDevice)
        {
            if (strMobileDevice == browsertype.android.ToString())
            {
                Browser = "Android";
                Env     = "Android";
                Config  = true;
                try
                {
                    //devicenamelocal = ConfigurationManager.AppSettings.Get("androiddeviceNameLocal");
                    //configurationbool = true;
                    //DesiredCapabilities capabilities = new DesiredCapabilities();
                    //capabilities.SetCapability(MobileCapabilityType.BrowserName, MobileBrowserType.Chrome);
                    //// capabilities.SetCapability(MobileCapabilityType.DeviceName, devicenamelocal);
                    //capabilities.SetCapability(MobileCapabilityType.DeviceName, "192.168.99.101:5555");
                    //capabilities.SetCapability(MobileCapabilityType.PlatformName, MobilePlatform.Android);
                    //capabilities.SetCapability("newCommandTimeout", TimeSpan.FromSeconds(200));
                    //driver = new RemoteWebDriver(new Uri("http://127.0.0.1:4723/wd/hub"), capabilities);
                    //// driver = new RemoteWebDriver(capabilities);
                    //driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad"))));
                    //driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(200));


                    //-------------- local chrome DEVICE Mode for chrome ------------------------

                    string path = TestUtility.GetAssemblyDirectory() + "//chromedriver.exe";
                    Environment.SetEnvironmentVariable("webdriver.chrome.driver", path);

                    DesiredCapabilities capabilities = new DesiredCapabilities();
                    capabilities.SetCapability(MobileCapabilityType.Orientation, MobileSelector.AndroidUIAutomator);
                    capabilities.SetCapability(MobileCapabilityType.BrowserName, "Android");
                    capabilities.SetCapability(MobileCapabilityType.DeviceName, "Galaxy S5");
                    capabilities.SetCapability(MobileCapabilityType.PlatformName, "Android");
                    capabilities.SetCapability(MobileCapabilityType.PlatformVersion, "5.0.2");
                    capabilities.SetCapability(MobileBrowserType.Browser, "Android");


                    //Dictionary<String, String> mobileEmulation = new Dictionary<String, String>();
                    //mobileEmulation.Add("deviceName", "Galaxy S5");
                    //mobileEmulation.Add("height", "640");
                    //mobileEmulation.Add("width", "360");
                    //mobileEmulation.Add("pixelRatio", "3");
                    //mobileEmulation.Add("browserName", "Android");
                    //mobileEmulation.Add("platformName", MobilePlatform.Android);
                    ChromeOptions chrOpts = new ChromeOptions();
                    // chrOpts.AddAdditionalCapability("capabilityName", mobileEmulation);
                    chrOpts.EnableMobileEmulation("Galaxy S5");
                    // chrOpts.AddArguments("test-type");
                    // chrOpts.AddArguments("--disable-extensions");
                    chrOpts.AddArgument("incognito");
                    //chrOpts.AddUserProfilePreference("download.prompt_for_download", ConfigurationManager.AppSettings["ShowBrowserDownloadPrompt"]);
                    driver = new ChromeDriver(chrOpts);
                    //driver.Manage().Window.Maximize();
                    driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad"))));

                    // Map<String, String> mobileEmulation = new HashMap<>();
                    // mobileEmulation.put("deviceName", "Nexus 5");
                    // ChromeOptions chromeOptions = new ChromeOptions();
                    // chromeOptions.setExperimentalOption("mobileEmulation", mobileEmulation);
                    //WebDriver driver = new ChromeDriver(chromeOptions);



                    //------------- Genymotion Local---------------------

                    //DesiredCapabilities capabilities = new DesiredCapabilities();
                    //capabilities.SetCapability("device", "Android");
                    //capabilities.SetCapability("browserName", "chrome");
                    //capabilities.SetCapability("deviceName", "192.168.99.101:5555");
                    //capabilities.SetCapability("platformName", "Android");
                    //capabilities.SetCapability("platformVersion", "5.0.2");

                    //driver = new RemoteWebDriver(new Uri("http://127.0.0.1:4723/wd/hub"), capabilities, TimeSpan.FromSeconds(180));
                    //driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad"))));
                    //driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(200));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            else if (strMobileDevice == browsertype.ios.ToString())
            {
                DesiredCapabilities capabilities = new DesiredCapabilities();
                capabilities.SetCapability(MobileCapabilityType.Orientation, MobileSelector.AndroidUIAutomator);
                capabilities.SetCapability(MobileCapabilityType.BrowserName, "chrome");
                capabilities.SetCapability(MobileCapabilityType.DeviceName, "iPhone X");
                capabilities.SetCapability(MobileCapabilityType.PlatformName, "ios");
                capabilities.SetCapability(MobileCapabilityType.PlatformVersion, "5.0.2");
                capabilities.SetCapability(MobileBrowserType.Browser, "chrome");

                //DesiredCapabilities capabilities = new DesiredCapabilities();
                //capabilities.SetCapability("platformName", "ios");
                //capabilities.SetCapability("platformVersion", "11.0");
                //capabilities.SetCapability("", "Mac");
                //capabilities.SetCapability("deviceName", "iPhone X");
                //capabilities.SetCapability("automaplatformtionName", "XCUITest");
                //capabilities.SetCapability("browserName", "Safari");
                //Connecting to Appium Server
                //Uri serverUri = new Uri("http://192.168.10.53:4723/wd/hub"); //192.168.10.41  192.168.1.6 192.168.10.46
                // driver = new IOSDriver<IWebElement>(serverUri, capabilities, TimeSpan.FromSeconds(500));
                //driver = new RemoteWebDriver(serverUri, capabilities, TimeSpan.FromSeconds(500));
                //driver = new RemoteWebDriver(new Uri("http://127.0.0.1:4723/wd/hub"), capabilities);
                // driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(120));

                //devicenamelocal = ConfigurationManager.AppSettings.Get("androiddeviceNameLocal");
                //configurationbool = true;
                //string udid = "F710DB58-6336-4DA5-AB83-34801285A2AD";//iphone 8
                //string bundleID = "au.com.nimble.nimbleit";
                //DesiredCapabilities capabilities = new DesiredCapabilities();
                //capabilities.SetCapability(MobileCapabilityType.DeviceName, devicenamelocal);
                //capabilities.SetCapability("platformName", "iOS");
                //capabilities.SetCapability("platformVersion", "10.3");
                //capabilities.SetCapability("device", "iPhone 6");
                //capabilities.SetCapability("newCommandTimeout", "200000");
                //capabilities.SetCapability("takesScreenshot", true);
                //capabilities.SetCapability("udid", udid);
                //capabilities.SetCapability("bundleId", bundleID);
                //capabilities.SetCapability("autoWebviewTimeout", "10000");
                //capabilities.SetCapability("locationServicesAuthorized", true);
                //capabilities.SetCapability("waitForAppScript", "target.elements().length > 0; $.delay(30000); $.,.,y();");

                //driver = new RemoteWebDriver(new Uri("http://192.168.1.6:4723/wd/hub"), capabilities, TimeSpan.FromSeconds(1000)); // home
                ////driver = new RemoteWebDriver(new Uri("http://192.168.10.51:4723/wd/hub"), capabilities); // office
                //driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad"))));
                //driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(200));

                ChromeOptions chrOpts = new ChromeOptions();
                chrOpts.EnableMobileEmulation("iPhone X");
                driver = new ChromeDriver(chrOpts);
            }
            else
            {
                driver = null;
            }
        }
Example #16
0
        public Form1()
        {
            InitializeComponent();
            int    kolichestvotovarovvpost = 0;
            int    countrazn = 0;
            string hashtag   = null;
            string src       = null;

            string[]     artvar      = null;
            string[]     namevariant = null;
            string       desk        = null;
            const string campaign    = "08";

            OpenQA.Selenium.Chrome.ChromeOptions co = new OpenQA.Selenium.Chrome.ChromeOptions();
            co.AddArgument(@"user-data-dir=C:\Users\homepc\AppData\Local\Google\Chrome\User Data");
            Browser = new OpenQA.Selenium.Chrome.ChromeDriver(co); //
            IWait <IWebDriver> wait = new WebDriverWait(Browser, TimeSpan.FromSeconds(10));

            Browser.Manage().Window.Maximize();
            Browser.Manage().Timeouts().ImplicitWait = TimeSpan.FromHours(1);
            Browser.Navigate().GoToUrl("http://www.avon.ru/REPSuite/jsbrochure.page#page=0&campaign=" + campaign + "&year=18&index=01&zoom=0&type=core");
            IWebElement login = GetElement(By.Id("submitBtn")); if (login != null)

            {
                login.Click();
            }

            wait.Until(ExpectedConditions.ElementIsVisible(By.Id("jsbr_backnavbtn")));
            IWebElement back = Browser.FindElement(By.Id("jsbr_backnavbtn")); back.Click();

            System.Threading.Thread.Sleep(1500);
            string url       = Browser.Url;
            int    indexlast = url.IndexOf('&');
            int    leng      = indexlast - 49;
            string countpage = url.Substring(49, leng);
            int    pagelast  = int.Parse(countpage);

            for (int k = 0; k <= pagelast; k += 2)
            {
                Browser.Navigate().GoToUrl("http://www.avon.ru/REPSuite/jsbrochure.page#page=" + k + "&campaign=" + campaign + "&year=18&index=01&zoom=0&type=core");
                System.Threading.Thread.Sleep(2000);
                Browser.Navigate().Refresh();
Start:
                try
                {
                    System.Threading.Thread.Sleep(2000);
                    IWebElement zakazatprodsostr = Browser.FindElement(By.Id("jsbr_ver2_add")); zakazatprodsostr.Click();
                    IWebElement order            = Browser.FindElement(By.CssSelector("#jsbr_ver2_to_order [target='_top']")); //order.Click();
                }
                catch (UnhandledAlertException)
                {
                    IAlert alert = Browser.SwitchTo().Alert();
                    alert.Accept();
                    IWebElement next = Browser.FindElement(By.Id("jsbr_fwdnav_container"));
                    next.Click();
                    goto Start;
                }
                IWebElement imagepost = Browser.FindElement(By.Id("jsbr_pageimage")); string srcpost = imagepost.GetAttribute("src");
                wait.Until(ExpectedConditions.FrameToBeAvailableAndSwitchToIt("jsBroDialogFrame"));
                wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector(".js_bbo_lineno_val.cell .js_cell")));
                List <IWebElement> listart2 = Browser.FindElements(By.CssSelector(".js_bbo_lineno_val.cell .js_cell")).ToList();
                string[]           articul  = new string[listart2.Count];
                for (int j = 0; j < listart2.Count; j++)
                {
                    articul[j] = listart2[j].Text;
                }
                kolichestvotovarovvpost = listart2.Count;
                for (int i = 0; i < listart2.Count; i++)
                {
                    Browser.SwitchTo().DefaultContent();
                    Browser.Navigate().GoToUrl("https://my.avon.ru/poisk/rezultaty/?q=" + articul[i]);
                    IWebElement otsytarticul = Browser.FindElement(By.CssSelector("strong.ng-binding"));
                    int         errornumber  = int.Parse(otsytarticul.Text);
                    if (errornumber != 0)
                    {
                        IWebElement parsename = Browser.FindElement(By.CssSelector("a.ProductName.ng-binding"));
                        Name = parsename.Text;
                        parsename.Click();
                        IWebElement raznovinost = GetElement(By.CssSelector(".select2-chosen.ng-binding"));
                        if (raznovinost != null)
                        {
                            List <IWebElement> imageraznovid = Browser.FindElements(By.CssSelector(".VariantImageOverlay")).ToList();
                            countrazn = imageraznovid.Count;
                            for (int j = 0; j < imageraznovid.Count; j++)
                            {
                                src = imageraznovid[j].GetAttribute("scr");
                                webclient.DownloadFile(src, @"C:\avon\variants\" + articul[i] + ".jpg");
                                string pathToImage = @"C:\avon\variants\" + articul[i] + ".jpg";
                                Bitmap source      = new Bitmap(pathToImage);
                                Bitmap result      = new Bitmap(source, 400, 300);
                                namevariant[j] = imageraznovid[j].GetAttribute("alt");
                                List <IWebElement> articulvarianta = Browser.FindElements(By.ClassName("VariantLineNumber ng-binding ng-scope")).ToList();
                                artvar[j] = articulvarianta[j].Text;
                            }
                        }

                        IWebElement        priceproduct = Browser.FindElement(By.CssSelector("#ProductDetails div div.Price.ng-binding"));
                        List <IWebElement> deskproduct  = Browser.FindElements(By.CssSelector("#ProductDescription div div div div.ng-binding.ng-scope p")).ToList();
                        for (int j = 0; j < deskproduct.Count; j++)
                        {
                            desk += deskproduct[j].Text + "\r\n";
                        }
                        List <IWebElement> ht  = Browser.FindElements(By.CssSelector("#Breadcrumbs .ng-binding")).ToList();
                        string             kat = null;
                        int numcat             = ht.Count - 1;
                        for (int j = 1; j < ht.Count; j++)
                        {
                            hashtag += "#" + ht[j].Text.Replace(" ", "") + " ";
                            if (j == numcat)
                            {
                                kat = ht[j].Text;
                            }
                        }

                        string      pr     = priceproduct.Text.Replace(" руб.", "");
                        string      price  = pr.Replace(" ", "");
                        IWebElement yveliz = Browser.FindElement(By.CssSelector("span.EnlargeImageText")); yveliz.Click();
                        IWebElement image  = Browser.FindElement(By.CssSelector("#ProductLightboxCarousel div div div div a div img"));
                        src = image.GetAttribute("src");
                        webclient.DownloadFile(src, @"c:\avon\" + articul + ".jpg");
                        //заполнение
CreateCatalog:
                        Browser.Navigate().GoToUrl("https://m.ok.ru/dk?st.cmd=createProduct&st.rtu=%2Fdk%3Fst.cmd%3DaltGroupMain%26st.groupId%3D55240665399526%26_prevCmd%3DaltGroupMain%26tkn%3D4595&st.groupId=55240665399526&_prevCmd=altGroupMain&tkn=2316");
                        System.Threading.Thread.Sleep(1000);
                        Browser.Navigate().Refresh();
                        IWebElement nameok  = Browser.FindElement(By.CssSelector("#boxPage #content .input-text #field_name")); nameok.SendKeys(Name);
                        IWebElement priceok = Browser.FindElement(By.CssSelector("#idFormContentBeforePhoto div div input#field_price.input-text_element")); priceok.SendKeys(price.ToString());
                        IWebElement deskok  = Browser.FindElement(By.CssSelector("#idFormContentBeforePhoto div div textarea#field_descr.textarea_element")); deskok.SendKeys(hashtag + "\r\n" + "\r\n" + desk);
                        IWebElement photo   = Browser.FindElement(By.Id("upload-photo-files_field-id")); photo.SendKeys(@"C:\avon\" + articul + ".jpg");
                        System.Threading.Thread.Sleep(2000);
                        IWebElement katalog = Browser.FindElement(By.Id("field_selId")); SelectElement drop = new SelectElement(katalog);

                        try
                        {
                            Browser.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2);
                            drop.SelectByText(kat);
                        }
                        catch (NoSuchElementException)
                        {
                            CreateCatalog(kat);
                            goto CreateCatalog;
                        }
                        Browser.Manage().Timeouts().ImplicitWait = TimeSpan.FromHours(1);

                        IWebElement dlit = Browser.FindElement(By.Id("field_lifeTm")); SelectElement drop2 = new SelectElement(dlit); drop2.SelectByValue("30");
                        IWebElement saveok = Browser.FindElement(By.CssSelector("input.base-button_target")); saveok.Click();
                        System.Threading.Thread.Sleep(2500);
                        Browser.Navigate().GoToUrl("https://vk.com/market-147979295");
                        IWebElement addvk   = Browser.FindElement(By.Id("market_add_item_btn")); addvk.Click();
                        IWebElement namevk  = Browser.FindElement(By.Id("item_name")); namevk.SendKeys(Name);
                        IWebElement imagevk = Browser.FindElement(By.Name("photo"));
                        IWebElement deskvk  = Browser.FindElement(By.Id("item_description"));
                        if (raznovinost == null)
                        {
                            deskvk.SendKeys(hashtag + "\r\n\r\n" + desk);
                            imagevk.SendKeys(@"C:\avon\" + articul + ".jpg");
                            IWebElement acceptvkphoto = Browser.FindElement(By.Id("market_photo_crop_done"));
                            System.Threading.Thread.Sleep(2000);
                            acceptvkphoto.Click();
                        }
                        else
                        {
                            int n = 0;
                            do
                            {
                                deskvk.SendKeys(hashtag + "\r\n" + "Внимание! У данного товара есть разновидности:" + "\r\n" +
                                                "(" + (n + 2) + " фотография) - " + namevariant[i] + "(" + artvar[i] + ")\r\n" + desk);
                                imagevk.SendKeys(@"C:\avon\variants" + artvar[i] + ".jpg");
                                IWebElement acceptvkphoto = Browser.FindElement(By.Id("market_photo_crop_done"));
                                acceptvkphoto.Click();
                                n++;
                            } while (n < countrazn);
                        }
                        System.Threading.Thread.Sleep(2500);
                        IWebElement pricevk   = Browser.FindElement(By.Id("item_price")); pricevk.SendKeys(price.ToString());
                        IWebElement katalogvk = Browser.FindElement(By.CssSelector("#container4 input.selector_input")); katalogvk.SendKeys(kat + OpenQA.Selenium.Keys.Enter);
                        IWebElement savevk    = Browser.FindElement(By.XPath("/html/body[@class='layers_shown']/div[@id='box_layer_wrap']/div[@id='box_layer']/div[@class='popup_box_container']/div[@class='box_layout']/div[@class='box_controls_wrap']/div[@class='box_controls']/table[@class='fl_r']/tbody/tr/td[2]/button[@class='flat_button']")); savevk.Click();
                        System.Threading.Thread.Sleep(2500);
                    }
                }
                int m = 0;
                Browser.Navigate().GoToUrl("https://vk.com/rosuinka");
                IWebElement postvk = Browser.FindElement(By.Id("post_field")); postvk.SendKeys(hashtag);
                webclient.DownloadFile(srcpost, @"C:\avon\katalog\" + m + ".jpg");
                IWebElement addphotoiconvk = Browser.FindElement(By.CssSelector(".ms_item_photo")); addphotoiconvk.Click();
                IWebElement uploadkatalog  = Browser.FindElement(By.Id("choose_photo_upload")); uploadkatalog.SendKeys(@"C:\avon\katalog\" + m + ".jpg");
                System.Threading.Thread.Sleep(3000);
                for (int i = 0; i < kolichestvotovarovvpost; i++)
                {
                    ((IJavaScriptExecutor)Browser).ExecuteScript("arguments[0].click();", Browser.FindElement(By.CssSelector("ms_item ms_item_market _type_market")));
                    IWebElement findtovar   = Browser.FindElement(By.CssSelector("input#market_search_input")); findtovar.SendKeys(Name);
                    IWebElement accepttovar = Browser.FindElement(By.CssSelector("#market_subtab_pane_search .market_row_img")); accepttovar.Click();
                }
                Browser.Navigate().GoToUrl("https://ok.ru/group/55240665399526/market/search");
                string      hrefok   = null;
                IWebElement searchok = Browser.FindElement(By.CssSelector("label input"));
                for (int i = 0; i < kolichestvotovarovvpost; i++)
                {
                    searchok.SendKeys(Name);
                    IWebElement selecttovarok = Browser.FindElement(By.CssSelector(".market-list_lk"));
                    hrefok += selecttovarok.GetAttribute("href") + "\r\n";
                    searchok.Clear();
                }
                Browser.Navigate().GoToUrl("https://ok.ru/group/55240665399526");
                IWebElement lenta       = Browser.FindElement(By.CssSelector(".mctc_navMenuSec[href='/group/55240665399526']")); lenta.Click();
                IWebElement postokclick = Browser.FindElement(By.ClassName("input_placeholder")); postokclick.Click();
                IWebElement postok      = Browser.FindElement(By.CssSelector("[data-initial-text-to-modify='null']")); postok.SendKeys(hrefok + OpenQA.Selenium.Keys.Enter); System.Threading.Thread.Sleep(1000); postok.Clear(); postok.SendKeys(hashtag);
                IWebElement addcatok    = Browser.FindElement(By.CssSelector(".posting_ac_i.h-mod[title='Добавить фото']")); addcatok.Click();
                IWebElement upldkatok   = Browser.FindElement(By.CssSelector(".dblock input[type='file'][name='photo']")); upldkatok.SendKeys(@"C:\avon\katalog\" + m + ".jpg");
                IWebElement poskokacc   = Browser.FindElement(By.CssSelector(".posting_submit")); poskokacc.Click();
            }
            Browser.Quit();
        }
        public async void FBLogin(String user, String pass)
        {
            Program.mainForm.btnLogin.Enabled = false;

            if (user == "" || pass == "")
            {
                MessageBox.Show("Điền thông tin đăng nhập!");
                Program.mainForm.btnLogin.Enabled = true;
                return;
            }

            //Program.loadingForm = new LoadingForm();
            //Program.loadingForm.setText("KHỞI TẠO HỆ THỐNG...");
            //Program.loadingForm.Show();
            //Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(() => Program.loadingForm.ShowDialog()));

            //t = new System.Threading.Thread(() => Program.loadingForm.ShowDialog());
            //t.Start(); // LoadingForm.Show()
            // Bật trình duyệt khi Login
            if (driver == null)
            {
                setReady(false, "Đang khởi tạo hệ thống");
                //var profile = new OpenQA.Selenium.Firefox.FirefoxProfile();
                //profile.SetPreference("general.useragent.override", "NokiaC5-00/061.005 (SymbianOS/9.3; U; Series60/3.2 Mozilla/5.0; Profile/MIDP-2.1 Configuration/CLDC-1.1) AppleWebKit/525 (KHTML, like Gecko) Version/3.0 Safari/525 3gpp-gba");
                //profile.SetPreference("webdriver.load.strategy", "unstable");
                //profile.SetPreference("permissions.default.stylesheet", 2);
                //profile.SetPreference("permissions.default.image", 2);
                //profile.AddExtension("App/Firefox/firebug.xpi");
                //profile.SetPreference("dom.ipc.plugins.enabled.libflashplayer.so", "false");
                IEnumerable<int> pidsBefore = Process.GetProcessesByName("chrome").Select(p => p.Id);
                try
                {
                    //this.driver = await Task.Factory.StartNew(() => new OpenQA.Selenium.Firefox.FirefoxDriver(profile));
                    /*
                    OpenQA.Selenium.Firefox.FirefoxBinary firefox = new OpenQA.Selenium.Firefox.FirefoxBinary("App/Firefox/firefox.exe");
                    this.driver = new OpenQA.Selenium.Firefox.FirefoxDriver(firefox, profile);*/
                    var chromeDriverService = OpenQA.Selenium.Chrome.ChromeDriverService.CreateDefaultService(Path.GetDirectoryName(Application.ExecutablePath) + @"\App");
                    chromeDriverService.HideCommandPromptWindow = true;
                    OpenQA.Selenium.Chrome.ChromeOptions chromeDriverOptions = new OpenQA.Selenium.Chrome.ChromeOptions();
                    chromeDriverOptions.AddArgument("--user-agent=NokiaC5-00/061.005 (SymbianOS/9.3; U; Series60/3.2 Mozilla/5.0; Profile/MIDP-2.1 Configuration/CLDC-1.1) AppleWebKit/525 (KHTML, like Gecko) Version/3.0 Safari/525 3gpp-gba"); //Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0
                    chromeDriverOptions.AddArgument("ignore-certificate-errors");
                    chromeDriverOptions.AddArgument("no-sandbox");
                    chromeDriverOptions.AddExtension(Path.GetDirectoryName(Application.ExecutablePath) + @"\App\block.crx");
                    driver = await Task.Factory.StartNew(() => new OpenQA.Selenium.Chrome.ChromeDriver(chromeDriverService, chromeDriverOptions));
                    //Thread.Sleep(1000);
                }
                catch
                {
                    //Program.loadingForm.RequestStop();
                    MessageBox.Show("Thiếu File!?");
                    /*
                    if (MessageBox.Show("Để chạy chương trình, bạn cần cài đặt trình duyệt Mozilla Firefox tích hợp. Cài đặt ngay?", "Cài đặt trình duyệt", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.Yes)
                    {
                        MessageBox.Show("Chương trình có thể bị treo trong vài giây tới. Nhấn OK để bắt đầu cài đặt!");
                        // install firefox 34
                        ProcessStartInfo startInfo = new ProcessStartInfo();
                        startInfo.CreateNoWindow = false;
                        startInfo.UseShellExecute = false;
                        startInfo.FileName = "firefox34.exe";
                        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                        startInfo.Arguments = "-ms";
                        try
                        {
                            using (Process exeProcess = Process.Start(startInfo))
                            {
                                exeProcess.WaitForExit();
                            }
                        }
                        catch { }

                        string[] folders = Directory.GetDirectories(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Mozilla\\Firefox\\Profiles\\", "*.default");
                        string prefs_js = folders[0] + "\\prefs.js";

                        StreamWriter sw;
                        sw = File.AppendText(prefs_js);
                        sw.WriteLine("user_pref('app.update.auto', false);");
                        sw.WriteLine("user_pref('app.update.enabled', false);");
                        sw.Close();

                        MessageBox.Show("Hoàn thành cài đặt! Hãy khởi động lại chương trình!");
                    }*/

                    Exceptions_Handler();
                }
                IEnumerable<int> pidsAfter = Process.GetProcessesByName("chrome").Select(p => p.Id);

                newFirefoxPids = pidsAfter.Except(pidsBefore);

                try
                {
                    foreach (int pid in newFirefoxPids)
                    {
                        int hWnd = Process.GetProcessById(pid).MainWindowHandle.ToInt32();
                        ShowWindow(hWnd, SW_HIDE);
                    }
                }
                catch
                {
                    // newFirefoxPids.Count == 0
                    //Program.loadingForm.RequestStop();
                    MessageBox.Show("Không tìm thấy cửa sổ Trình duyệt!");
                    Exceptions_Handler();
                }

                driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(1));
                driver.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromSeconds(10));
                driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(30));
                setReady(true);
            }

            //Program.loadingForm.setText("ĐĂNG NHẬP TÀI KHOẢN FACEBOOK...");
            setReady(false, "Đang đăng nhập");
            await Task.Factory.StartNew(() => Navigate(links["fb_url"]));

            if (await Task.Factory.StartNew(() => driver.FindElementsByName("email").Count) == 0)
            {
                //Program.loadingForm.RequestStop();
                //t.Abort();
                //t.Join();
                MessageBox.Show("Có lỗi với đường truyền mạng hoặc tài khoản facebook của bạn!\nHãy kiểm tra lại");
                Program.mainForm.btnLogin.Enabled = true;
                Program.mainForm.txtUser.Enabled = true;
                Program.mainForm.txtPass.Enabled = true;
                foreach (Control item in Program.mainForm.dgGroups.Controls.OfType<Control>())
                {
                    if (item.Name == "group_loading_gif")
                        Program.mainForm.dgGroups.Controls.Remove(item);
                }
                setReady(true);
                return;
            }
            
            await Task.Factory.StartNew(() => InputValueAdd("email", user));
            await Task.Factory.StartNew(() => InputValueAdd("pass", pass));
            await Task.Factory.StartNew(() => Click("login"));
            /*
            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
            await Task.Factory.StartNew(() => wait.Until<IWebElement>((d) =>
            {
                return d.FindElement(By.Name("xc_message"));
            }));*/
            //await Task.Factory.StartNew(() => ((IJavaScriptExecutor)driver).ExecuteScript("alert(123)"));
            driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(300));
            string after_login_url = await Task.Factory.StartNew(() => driver.Url);
            driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(30));

            check_after_login:
            if (after_login_url.Contains("home.php") || after_login_url.Contains("phoneacquire"))
            {
                Program.mainForm.btnLogin.Text = "Đăng nhập thành công!";
                Program.mainForm.AcceptButton = null;
                Program.mainForm.btnPost.Enabled = true;
                Program.mainForm.btnInvite.Enabled = true;
                Program.mainForm.btnGroupSearch.Enabled = true;
                Program.mainForm.btnGroupJoin.Enabled = true;
                Program.mainForm.btnPMImportFriends.Enabled = true;
                Program.mainForm.btnPM.Enabled = true;
                Program.mainForm.btnPMSendFrRequests.Enabled = true;
                Program.mainForm.btnInteractionsFollow.Enabled = true;
                Program.mainForm.btnInteractionsPoke.Enabled = true;
                Program.mainForm.btnInteractionsLike.Enabled = true;
                Program.mainForm.btnPMImportProfile.Enabled = true;
                Program.mainForm.btnPMImportGroup.Enabled = true;
                Program.mainForm.btnCommentImportComment.Enabled = true;
                Program.mainForm.btnPostImportGroups.Enabled = true;
                Program.mainForm.btnGroupImportFriends.Enabled = true;
                Program.mainForm.btnCommentScan.Enabled = true;
                Program.mainForm.btnFanpageComment.Enabled = true;
                Program.mainForm.btnFanpageGroupPost.Enabled = true;
                Program.mainForm.btnEventInviteFriends.Enabled = true;
                Program.mainForm.btnFanpageSeeder.Enabled = true;
                Program.mainForm.btnFanpageInviteFriends.Enabled = true;
                Program.mainForm.btnFanpageLike.Enabled = true;
                Program.mainForm.btnGraphSearch.Enabled = true;
                
                var photos = await Task.Factory.StartNew(() => driver.FindElementsByXPath("//a[contains(@href, '?v=photos')]"));
                if (photos.Count > 0)
                {
                    String href = photos[0].GetAttribute("href");
                    Match match = Regex.Match(href, @".com\/([A-Za-z0-9\-\.]+)\?v\=photos", RegexOptions.None);
                    if (match.Success)
                    {
                        user_id = match.Groups[1].Value;
                    }
                }

                var nodes = await Task.Factory.StartNew(() => driver.FindElementsByXPath("//img[contains(@src, 'fbcdn-profile-a.akamaihd.net')]"));
                if (nodes.Count > 0)
                {
                    Program.mainForm.lblUsername.Text = nodes[0].GetAttribute("alt");
                }

                try
                {
                    user_id_img = user_id;
                    await Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            user_id_img = driver.FindElementByName("target").GetAttribute("value");
                        }
                        catch { }
                    });

                    Program.mainForm.pbAvatar.WaitOnLoad = false;
                    Program.mainForm.pbAvatar.LoadAsync(links["facebook_graph"] + "/" + user_id_img + "/picture");
                    Program.mainForm.lblViewProfile.Text = "https://facebook.com/" + user_id_img;
                }
                catch { }
                
                //Program.mainForm.Focus();
                //Program.loadingForm.setText("ĐĂNG NHẬP THÀNH CÔNG! ĐANG TẢI DANH SÁCH NHÓM...");
                Program.mainForm.lblStatus.Text = "Tải danh sách nhóm...";
                Program.mainForm.dgGroups.Rows.Clear();
                if (Program.mainForm.cbGroupReload.Checked)
                {
                    try
                    {
                        DataSet DS = new DataSet();
                        DS.ReadXml(RemoveSpecialCharacters(user_id_img) + "_groups.xml");

                        bool empty = true;

                        foreach (DataRow dr in DS.Tables[0].Rows)
                        {
                            Program.mainForm.dgGroups.Rows.Add(dr[0], dr[1], dr[2], dr[3]);
                            await TaskEx.Delay(1);
                            if (dr[3].ToString() == "1") empty = false;
                        }

                        if (empty)
                        {
                            foreach (DataGridViewRow row in Program.mainForm.dgGroups.Rows)
                            {
                                DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[3];
                                chk.Value = 1;
                            }
                        }
                    }
                    catch { }
                }

                if (Program.mainForm.dgGroups.RowCount == 0) await getGroups();
                else
                {
                    //Program.loadingForm.RequestStop();
                    //t.Abort();
                    //t.Join();
                    Program.mainForm.lblProgress.Text = "0/" + Program.mainForm.dgGroups.Rows.Count;
                    setReady(true, "Số lượng nhóm: " + Program.mainForm.dgGroups.Rows.Count);
                }

                Program.mainForm.btnLogin.Text = "Đăng xuất";
                Program.mainForm.btnLogin.Enabled = true;

                foreach (Control item in Program.mainForm.dgGroups.Controls.OfType<Control>())
                {
                    if (item.Name == "group_loading_gif")
                        Program.mainForm.dgGroups.Controls.Remove(item);
                }
            }
            else
            {
                if (getUrl().Contains("home.php"))
                {
                    goto check_after_login; // check again, just in case 100ms is not enough
                }

                Program.mainForm.txtUser.Enabled = true;
                Program.mainForm.txtPass.Enabled = true;
                foreach (Control item in Program.mainForm.dgGroups.Controls.OfType<Control>())
                {
                    if (item.Name == "group_loading_gif")
                        Program.mainForm.dgGroups.Controls.Remove(item);
                }
                //Program.loadingForm.RequestStop();
                //t.Abort();
                //t.Join();
                if (getUrl().Contains("checkpoint"))
                    MessageBox.Show("Hãy vô hiệu hóa bảo mật tài khoản trước khi sử dụng AUTO!");
                
                MessageBox.Show("Kiểm tra lại thông tin đăng nhập!\nNếu bạn chắc chắn thông tin đăng nhập là đúng,\nhãy đăng nhập lại tài khoản trên trình duyệt trước khi tiếp tục!");
                Program.mainForm.btnLogin.Enabled = true;
                setReady(true);
                return;
            }
            // await Task.Factory.StartNew(() => new WebDriverWait(driver, TimeSpan.FromSeconds(10))); // Chờ tải xong trang
        }
Example #18
0
        public void DebugLocalMobile(string strMobileDevice)
        {
            if (strMobileDevice == browsertype.android.ToString())
            {
                Browser = "Android";
                Env     = "Android";
                Config  = true;
                try
                {
                    //devicenamelocal = ConfigurationManager.AppSettings.Get("androiddeviceNameLocal");
                    //configurationbool = true;
                    //DesiredCapabilities capabilities = new DesiredCapabilities();
                    //capabilities.SetCapability(MobileCapabilityType.BrowserName, MobileBrowserType.Chrome);
                    //// capabilities.SetCapability(MobileCapabilityType.DeviceName, devicenamelocal);
                    //capabilities.SetCapability(MobileCapabilityType.DeviceName, "192.168.99.101:5555");
                    //capabilities.SetCapability(MobileCapabilityType.PlatformName, MobilePlatform.Android);
                    //capabilities.SetCapability("newCommandTimeout", TimeSpan.FromSeconds(200));
                    //driver = new RemoteWebDriver(new Uri("http://127.0.0.1:4723/wd/hub"), capabilities);
                    //// driver = new RemoteWebDriver(capabilities);
                    //driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad"))));
                    //driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(200));


                    //-------------- local chrome DEVICE Mode for chrome ------------------------

                    string path = TestUtility.GetAssemblyDirectory() + "\\chromedriver.exe";
                    Environment.SetEnvironmentVariable("webdriver.chrome.driver", path);

                    DesiredCapabilities capabilities = new DesiredCapabilities();
                    capabilities.SetCapability(MobileCapabilityType.Orientation, MobileSelector.AndroidUIAutomator);
                    capabilities.SetCapability(MobileCapabilityType.BrowserName, "Android");
                    capabilities.SetCapability(MobileCapabilityType.DeviceName, "Galaxy S5");
                    capabilities.SetCapability(MobileCapabilityType.PlatformName, "Android");
                    capabilities.SetCapability(MobileCapabilityType.PlatformVersion, "5.0.2");
                    capabilities.SetCapability(MobileBrowserType.Browser, "Android");


                    //Dictionary<String, String> mobileEmulation = new Dictionary<String, String>();
                    //mobileEmulation.Add("deviceName", "Galaxy S5");
                    //mobileEmulation.Add("height", "640");
                    //mobileEmulation.Add("width", "360");
                    //mobileEmulation.Add("pixelRatio", "3");
                    //mobileEmulation.Add("browserName", "Android");
                    //mobileEmulation.Add("platformName", MobilePlatform.Android);
                    ChromeOptions chrOpts = new ChromeOptions();
                    // chrOpts.AddAdditionalCapability("capabilityName", mobileEmulation);
                    chrOpts.EnableMobileEmulation("Galaxy S5");
                    // chrOpts.AddArguments("test-type");
                    // chrOpts.AddArguments("--disable-extensions");
                    chrOpts.AddArgument("incognito");
                    //chrOpts.AddUserProfilePreference("download.prompt_for_download", ConfigurationManager.AppSettings["ShowBrowserDownloadPrompt"]);
                    driver = new ChromeDriver(chrOpts);
                    driver.Manage().Window.Maximize();
                    driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad"))));

                    // Map<String, String> mobileEmulation = new HashMap<>();
                    // mobileEmulation.put("deviceName", "Nexus 5");
                    // ChromeOptions chromeOptions = new ChromeOptions();
                    // chromeOptions.setExperimentalOption("mobileEmulation", mobileEmulation);
                    //WebDriver driver = new ChromeDriver(chromeOptions);



                    //------------- Genymotion Local---------------------

                    //DesiredCapabilities capabilities = new DesiredCapabilities();
                    //capabilities.SetCapability("device", "Android");
                    //capabilities.SetCapability("browserName", "chrome");
                    //capabilities.SetCapability("deviceName", "192.168.99.101:5555");
                    //capabilities.SetCapability("platformName", "Android");
                    //capabilities.SetCapability("platformVersion", "5.0.2");

                    //driver = new RemoteWebDriver(new Uri("http://127.0.0.1:4723/wd/hub"), capabilities, TimeSpan.FromSeconds(180));
                    //driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad"))));
                    //driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(200));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            else if (strMobileDevice == browsertype.ios.ToString())
            {
                DesiredCapabilities capabilities = new DesiredCapabilities();
                capabilities.SetCapability("platformName", "ios");
                capabilities.SetCapability("platformVersion", "11.0");
                capabilities.SetCapability("", "Mac");
                capabilities.SetCapability("deviceName", "iPhone SE");
                capabilities.SetCapability("automationplatformName", "XCUITest");
                capabilities.SetCapability("browserName", "Safari");

                Uri serverUri = new Uri("http://192.168.10.59:4723/wd/hub"); //192.168.10.41  192.168.1.6 192.168.10.46 10.37.110.228 192.168.10.60
                                                                             // driver = new IOSDriver<IWebElement>(serverUri, capabilities, TimeSpan.FromSeconds(500));
                driver = new RemoteWebDriver(serverUri, capabilities, TimeSpan.FromSeconds(1000));
            }
            else
            {
                driver = null;
            }
        }