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 DebugLocalChrome()
        {
            try
            {
                //set configuration to be picked up and set Locator
                Config  = false;
                Browser = "Chrome";
                Env     = "Desktop";

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

                ChromeOptions chrOpts = new ChromeOptions();
                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"))));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Example #3
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}");
        }
Example #4
0
        public void DebugBSChrome()
        {
            Browser           = "Chrome";
            Env               = "BS Desktop";
            Config            = false;
            configurationbool = false;
            DesiredCapabilities desiredCap = DesiredCapabilities.Chrome();
            ChromeOptions       chrOpts    = new ChromeOptions();

            chrOpts.AddArguments("test-type");
            chrOpts.AddArguments("--disable-extensions");
            //chrOpts.AddArgument("incognito");
            //desiredCap.SetCapability(ChromeOptions.Capability, chrOpts);    // updated
            desiredCap = (DesiredCapabilities)chrOpts.ToCapabilities();

            desiredCap.SetCapability("browserstack.user", browserstack_user);
            desiredCap.SetCapability("browserstack.key", browserstack_key);
            desiredCap.SetCapability("platform", "WINDOWS");
            desiredCap.SetCapability("os", "WINDOWS");
            desiredCap.SetCapability("os_version", "8");
            // desiredCap.SetCapability("build", Environment.GetEnvironmentVariable("BS_AUTOMATE_BUILD"));
            desiredCap.SetCapability("browserstack.debug", true);
            // string strTestName = TestContext.CurrentContext.Test.Name.ToString();
            desiredCap.SetCapability("project", Environment.GetEnvironmentVariable("BS_AUTOMATE_PROJECT"));
            desiredCap.SetCapability("build", Environment.GetEnvironmentVariable("BS_AUTOMATE_BUILD"));

            driver = new RemoteWebDriver(
                new Uri("http://hub-cloud.browserstack.com/wd/hub/"), desiredCap);

            SessionId = ((RemoteWebDriver)driver).SessionId.ToString();

            driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(Convert.ToInt32(ConfigurationManager.AppSettings.Get("ElementPageLoad"))));
            driver.Manage().Window.Maximize();
        }
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
        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 #7
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 #8
0
 public FacebookAutomationTest()
 {
     OpenQA.Selenium.Chrome.ChromeOptions options = new OpenQA.Selenium.Chrome.ChromeOptions();
     options.AddArguments(new string[] { "--start-maximized", "--disable-notifications", "--incognito" });
     driver = new OpenQA.Selenium.Chrome.ChromeDriver(options);
     groups = new List <string>();
 }
        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 #10
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 #11
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");
 }
        public void Patch_WithUnhandledPromptBehaviorDefault_ShouldReturnWithUnhandledPromptBehaviorDismissAndNotify()
        {
            OpenQA.Selenium.Chrome.ChromeOptions originalOptions = new OpenQA.Selenium.Chrome.ChromeOptions();
            originalOptions.PageLoadStrategy = OpenQA.Selenium.PageLoadStrategy.Normal;

            OpenQA.Selenium.DriverOptions patchedOptions = DriverOptionsHelper.Patch(originalOptions, BrowserType.Chrome);

            Assert.AreEqual(OpenQA.Selenium.UnhandledPromptBehavior.DismissAndNotify, patchedOptions.UnhandledPromptBehavior);
        }
Example #13
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);
        }
        public void Patch_WithExistingOptions_ShouldReturnUnchangedOptions()
        {
            OpenQA.Selenium.Chrome.ChromeOptions originalOptions = new OpenQA.Selenium.Chrome.ChromeOptions();
            originalOptions.PageLoadStrategy        = OpenQA.Selenium.PageLoadStrategy.Eager;
            originalOptions.UnhandledPromptBehavior = OpenQA.Selenium.UnhandledPromptBehavior.AcceptAndNotify;

            OpenQA.Selenium.DriverOptions patchedOptions = DriverOptionsHelper.Patch(originalOptions, BrowserType.Chrome);

            Assert.AreEqual(originalOptions, patchedOptions);
        }
Example #15
0
        private ApplicationManager()
        {
            OpenQA.Selenium.Chrome.ChromeOptions options = new OpenQA.Selenium.Chrome.ChromeOptions();
            driver  = new OpenQA.Selenium.Chrome.ChromeDriver(options);
            baseURL = "http://localhost:81/";

            loginHelper      = new LoginHelper(this);
            navigationHelper = new NavigationHelper(this, baseURL);
            groupHelper      = new GroupHelper(this);
            addressHelper    = new AddressHelper(this);
        }
Example #16
0
        public void StartBrowser()
        {
            ChromeOptions chromeOptions = new ChromeOptions();

            chromeOptions.AddAdditionalCapability(CapabilityType.Version, "latest", true);
            chromeOptions.AddAdditionalCapability(CapabilityType.Platform, "Windows 10", true);
            chromeOptions.AddAdditionalCapability("username", this.sauceUsername, true);
            chromeOptions.AddAdditionalCapability("accessKey", this.sauceAccessKey, true);
            chromeOptions.AddAdditionalCapability(TestProjectCapabilityType.CLOUD_URL, "https://ondemand.saucelabs.com/wd/hub", true);
            this.driver = new ChromeDriver(chromeOptions: chromeOptions);
        }
        public override void RunCommand(object sender)
        {
            var engine         = (Core.Automation.Engine.AutomationEngineInstance)sender;
            var driverPath     = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath), "Resources");
            var seleniumEngine = v_EngineType.ConvertToUserVariable(sender);
            var instanceName   = v_InstanceName.ConvertToUserVariable(sender);

            OpenQA.Selenium.DriverService driverService;
            OpenQA.Selenium.IWebDriver    webDriver;

            if (seleniumEngine == "Chrome")
            {
                OpenQA.Selenium.Chrome.ChromeOptions options = new OpenQA.Selenium.Chrome.ChromeOptions();

                if (!string.IsNullOrEmpty(v_SeleniumOptions))
                {
                    var convertedOptions = v_SeleniumOptions.ConvertToUserVariable(sender);
                    options.AddArguments(convertedOptions);
                }

                driverService = OpenQA.Selenium.Chrome.ChromeDriverService.CreateDefaultService(driverPath);
                webDriver     = new OpenQA.Selenium.Chrome.ChromeDriver((OpenQA.Selenium.Chrome.ChromeDriverService)driverService, options);
            }
            else
            {
                driverService = OpenQA.Selenium.IE.InternetExplorerDriverService.CreateDefaultService(driverPath);
                webDriver     = new OpenQA.Selenium.IE.InternetExplorerDriver((OpenQA.Selenium.IE.InternetExplorerDriverService)driverService, new OpenQA.Selenium.IE.InternetExplorerOptions());
            }


            //add app instance
            engine.AddAppInstance(instanceName, webDriver);


            //handle app instance tracking
            if (v_InstanceTracking == "Keep Instance Alive")
            {
                GlobalAppInstances.AddInstance(instanceName, webDriver);
            }

            //handle window type on startup - https://github.com/saucepleez/taskt/issues/22
            switch (v_BrowserWindowOption)
            {
            case "Maximize":
                webDriver.Manage().Window.Maximize();
                break;

            case "Normal":
            case "":
            default:
                break;
            }
        }
        public void ExampleTestUsingRemoteWebDriverWithChromeOptions()
        {
            OpenQA.Selenium.Chrome.ChromeOptions chromeOptions = new OpenQA.Selenium.Chrome.ChromeOptions();

            this.driver = new RemoteWebDriver(driverOptions: chromeOptions);

            this.driver.Navigate().GoToUrl("https://example.testproject.io");
            this.driver.FindElement(By.CssSelector("#name")).SendKeys("John Smith");
            this.driver.FindElement(By.CssSelector("#password")).SendKeys("12345");
            this.driver.FindElement(By.CssSelector("#login")).Click();

            Assert.IsTrue(this.driver.FindElement(By.CssSelector("#greetings")).Displayed);
        }
Example #19
0
        public void Setup()
        {
            var options = new OpenQA.Selenium.Chrome.ChromeOptions();

            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://passport.yandex.ua/auth?origin=home_desktop_ua&retpath=https%3A%2F%2Fmail.yandex.ua%2F&backpath=https%3A%2F%2Fyandex.ua");
            driver.Manage().Window.Maximize();
        }
Example #20
0
        protected override async ValueTask <IActivityExecutionResult> OnExecuteAsync(ActivityExecutionContext context)
        {
            var options = new OpenQA.Selenium.Chrome.ChromeOptions();

            if (UseHeadless)
            {
                options.AddArguments("headless");
            }
            var driverId = await _factory.OpenAsync(BrowserType, options, context.CancellationToken);

            Data[RpaWebConventions.DriverIdKey] = driverId;
            //this.SaveWorkflowContext = true;
            return(Done(driverId));
        }
Example #21
0
 public SingleSteps()
 {
     OpenQA.Selenium.Chrome.ChromeOptions capability = new OpenQA.Selenium.Chrome.ChromeOptions();
     capability.AddAdditionalCapability("os_version", "10", true);
     capability.AddAdditionalCapability("browser", "Chrome", true);
     capability.AddAdditionalCapability("browser_version", "latest", true);
     capability.AddAdditionalCapability("os", "Windows", true);
     capability.AddAdditionalCapability("name", "Google Search Test", true);            // test name
     capability.AddAdditionalCapability("build", "browserstack-specflow-sample", true); // CI/CD job or build name
     capability.AddAdditionalCapability("browserstack.user", username, true);
     capability.AddAdditionalCapability("browserstack.key", accessKey, true);
     driver = new RemoteWebDriver(
         new Uri("https://hub-cloud.browserstack.com/wd/hub/"), capability);
     driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);
 }
Example #22
0
        public bool RecycleDriver(int recycleNavigateCount = 100)
        {
            if (this.Driver != null && this.NavigateCount < recycleNavigateCount)
            {
                return(false);
            }
            if (this.Driver != null)
            {
                this.Driver.Quit();
            }
            var options = new OpenQA.Selenium.Chrome.ChromeOptions();

            options.AddUserProfilePreference("profile.default_content_setting_values.images", 2);
            options.AddArguments("--start-maximized");
            this.Driver = new OpenQA.Selenium.Chrome.ChromeDriver(options);
            //this.RemoteWebDriver = new OpenQA.Selenium.Firefox.FirefoxDriver();
            NavigateCount = 0;
            return(true);
        }
        public ICapabilities GetCapabilitiesFromBrowserName(string browserName, string browserVersion, string platformName, Dictionary <string, object> optionalCapabilities = null)
        {
            optionalCapabilities = optionalCapabilities ?? new Dictionary <string, object>();
            DriverOptions browserOptions;

            switch (browserName)
            {
            case "firefox":
                browserOptions = new OpenQA.Selenium.Firefox.FirefoxOptions();
                break;

            case "safari":
                browserOptions = new OpenQA.Selenium.Safari.SafariOptions();
                break;

            case "internet explorer":
                browserOptions = new OpenQA.Selenium.IE.InternetExplorerOptions();
                break;

            case "microsoft edge":
                browserOptions = new OpenQA.Selenium.Edge.EdgeOptions();
                break;

            default:
                browserOptions = new OpenQA.Selenium.Chrome.ChromeOptions();
                break;
            }

            browserOptions.BrowserVersion = browserVersion;
            browserOptions.PlatformName   = platformName;
            var cloudOptions = new Dictionary <string, object>();

            foreach (var optionalCapability in optionalCapabilities)
            {
                cloudOptions.Add(optionalCapability.Key, optionalCapability.Value);
            }

            cloudOptions.Add("username", this.username);
            cloudOptions.Add("password", this.authkey);
            browserOptions.AddAdditionalOption("cbt:options", cloudOptions);
            return(browserOptions.ToCapabilities());
        }
Example #24
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 #25
0
        private void button1_Click(object sender, EventArgs e)
        {
            OpenQA.Selenium.Chrome.ChromeOptions options = new OpenQA.Selenium.Chrome.ChromeOptions();
            options.AddArguments(@"user-data-dir=C:\Users\DAle\AppData\Local\Google\Chrome\User Data\Default");
            Browser = new OpenQA.Selenium.Chrome.ChromeDriver(options);
            Browser.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(300);
            Browser.Navigate().GoToUrl("https://evoplay.games/portfolio/high-striker/");
            System.Threading.Thread.Sleep(1000);
            Cursor.Position = new Point(925, 861);
            mouse_event((int)(MouseEventFlags.LEFTDOWN), 0, 0, 0, 0);
            System.Threading.Thread.Sleep(100);
            mouse_event((int)(MouseEventFlags.LEFTUP), 0, 0, 0, 0);
            System.Threading.Thread.Sleep(300);
            Cursor.Position = new Point(800, 620);
            mouse_event((int)(MouseEventFlags.LEFTDOWN), 0, 0, 0, 0);
            System.Threading.Thread.Sleep(100);
            mouse_event((int)(MouseEventFlags.LEFTUP), 0, 0, 0, 0);
            System.Threading.Thread.Sleep(2000);
            Browser.SwitchTo().Frame(0);
            Temp = Browser.FindElements(By.CssSelector("#app table tbody b")).ToList();
            //List<IWebElement> Results = Browser.FindElements(By.XPath("//*[@id='app']/div/div/div[5]/div/div[2]/table/tbody/tr[1]/td[1]/b")).ToList();
            //var i = 0;
            //double[] array = new double[19];
            int i = 0;

            foreach (var element in Temp)
            {
                dataGridView1[1, i].Value = GetValue(element);
                array[i] = Convert.ToDouble(dataGridView1[1, i].Value);
                GlobalTurns(Convert.ToDouble(dataGridView1[1, i].Value));
                //dataGridView1[0, i].Style.BackColor = Color.Red;
                i++;
            }
            Post();
            timer.Interval = 4900; // 5000 (5 сек)
            timer.Start();
            timer.Tick += button2_Click;
        }
Example #26
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 #27
0
        public IWebDriver GetWebDriver(WebDriverParameters parameters)
        {
            IWebDriver driver = null;
            var desiredCaps = new DesiredCapabilities();

            foreach (var cap in parameters.capabilities)
            {
                desiredCaps.SetCapability(cap.Key, cap.GetValue());
            }
            //desiredCaps.SetCapability(CapabilityType.Platform, new Platform(GetPlatformTypeFromString(parameters.platform)));
            //desiredCaps.SetCapability(CapabilityType.BrowserName, parameters.browserName);
            //if (parameters.version != string.Empty)
            //{
            //    desiredCaps.SetCapability(CapabilityType.Version, parameters.version);
            //}
            var ieOptions = new OpenQA.Selenium.IE.InternetExplorerOptions();
            ieOptions.IgnoreZoomLevel = true;
            ieOptions.UnexpectedAlertBehavior = OpenQA.Selenium.IE.InternetExplorerUnexpectedAlertBehavior.Accept;

            var chromeOptions = new OpenQA.Selenium.Chrome.ChromeOptions();
            chromeOptions.AddAdditionalCapability("unexpectedAlertBehaviour", "Accept");

            switch (parameters.browserName.ToUpperInvariant())
            {
                case "CHROME":
                    driver = new OpenQA.Selenium.Chrome.ChromeDriver(chromeOptions);
                    break;
                case "ANDROIDCHROME":
                    driver = new OpenQA.Selenium.Chrome.ChromeDriver(chromeOptions);
                    break;
                case "IE":
                    driver = new OpenQA.Selenium.IE.InternetExplorerDriver(ieOptions);
                    break;
                case "FIREFOX":
                    driver = new OpenQA.Selenium.Firefox.FirefoxDriver(desiredCaps);
                    break;
            }

            //driver.S(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.ACCEPT);

            return driver;
        }
        private async Task ChromeAgent()
        {
            if (driver2 != null)
            {
                return;
            }
            ready2 = false;
            Program.mainForm.lblStatus.Text = "Khởi tạo kết nối nâng cao";

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

            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();
            driver2 = await Task.Factory.StartNew(() => new OpenQA.Selenium.Chrome.ChromeDriver(chromeDriverService, chromeDriverOptions));


            IEnumerable<int> pidsAfter = Process.GetProcessesByName("chrome").Select(p => p.Id);
            var newChromePids = pidsAfter.Except(pidsBefore);

            try
            {
                foreach (int pid in newChromePids)
                {
                    int hWnd = Process.GetProcessById(pid).MainWindowHandle.ToInt32();
                    ShowWindow(hWnd, SW_HIDE);
                }
            }
            catch
            {
                MessageBox.Show("Có lỗi xảy ra! Hãy khởi động lại chương trình");
                Exceptions_Handler();
            }

            Program.mainForm.lblStatus.Text = "Thiết lập kết nối nâng cao";

            driver2.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));

            await Task.Factory.StartNew(() => driver2.Url = "https://www.facebook.com/");


            WebDriverWait wait = new WebDriverWait(driver2, TimeSpan.FromSeconds(60));

            await Task.Factory.StartNew(() =>
            {
                try
                {
                    driver2.Url = "https://www.facebook.com/";
                }
                catch
                {
                    ((IJavaScriptExecutor)driver2).ExecuteScript("return window.stop()");
                }
            });

            await Task.Factory.StartNew(() =>
            {
                wait.Until<Boolean>((d) =>
                {
                    return ((IJavaScriptExecutor)driver2).ExecuteScript("return document.readyState").Equals("complete");
                });
            });

            try
            {
                driver2.ExecuteScript(@"document.getElementsByName('email')[0].value = '" + System.Web.HttpUtility.JavaScriptStringEncode(Program.mainForm.txtUser.Text) + "';");
            }
            catch
            {
                MessageBox.Show("Đường truyền mạng quá chậm, vui lòng thử lại sau!");
                Exceptions_Handler();
            }

            await Task.Factory.StartNew(() =>
            {
                driver2.ExecuteScript(@"document.getElementsByName('pass')[0].value = '" + System.Web.HttpUtility.JavaScriptStringEncode(Program.mainForm.txtPass.Text) + "';");
                driver2.ExecuteScript(@"document.getElementById('loginbutton').click();");
            });

            await Task.Factory.StartNew(() =>
            {
                wait.Until<Boolean>((d) =>
                {
                    return ((IJavaScriptExecutor)driver2).ExecuteScript("return document.readyState").Equals("complete");
                });
            });

            await TaskEx.Delay(1000);
            ready2 = true;
        }
Example #29
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();
        }
Example #30
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#");
 }
        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 #32
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 #33
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));
            }
        }