/// <summary>
        /// Logins the user.
        /// </summary>
        /// <param name="browser">The <paramref name="browser"/> instance.</param>
        /// <param name="userName">Name of the user.</param>
        /// <param name="userPassword">The user password.</param>
        /// <returns>If User login was successfully or not</returns>
        public static bool LoginUser(IE browser, string userName, string userPassword)
        {
            // Login User
            browser.GoTo("{0}yaf_login.aspx".FormatWith(TestConfig.TestForumUrl));

            // Check If User is already Logged In
            if (browser.Link(Find.ById(new Regex("_LogOutButton"))).Exists)
            {
                browser.Link(Find.ById("forum_ctl01_LogOutButton")).Click();

                browser.Button(Find.ById("forum_ctl02_OkButton")).Click();
            }

            browser.GoTo("{0}yaf_login.aspx".FormatWith(TestConfig.TestForumUrl));

            browser.ShowWindow(NativeMethods.WindowShowStyle.Maximize);

            browser.TextField(Find.ById(new Regex("Login1_UserName"))).TypeText(userName);
            browser.TextField(Find.ById(new Regex("Login1_Password"))).TypeText(userPassword);

            browser.Button(Find.ById(new Regex("LoginButton"))).ClickNoWait();

            browser.GoTo(TestConfig.TestForumUrl);

            return browser.Link(Find.ById(new Regex("LogOutButton"))).Exists;
        }
Esempio n. 2
0
        public void TestAlterDescription()
        {
            WatiN.Core.IE window = ie;
            ie.GoTo("http://localhost:13164/Photo/PhotoAlbumManager.aspx");
            base.Login(ie);
            Button btn_ctl00ContentPlac = window.Button(Find.ByName("ctl00$ContentPlaceHolder1$PhotoAlbumManager1$grdPhotoAlbum$ctl04$Button1"));

            Assert.That(btn_ctl00ContentPlac.Exists);
            Span spn_ctl00_ContentPla = window.Span(Find.ById("ctl00_ContentPlaceHolder1_PhotoAlbumManager1_frmEdit_rptPhoto_ctl00_SinglePhotoThumbnail1_lblDescription"));

            Assert.That(spn_ctl00_ContentPla.Exists);
            //Added after the registration
            TextField txt_editCurrent = window.TextField(Find.ById("editCurrent"));

            Assert.That(txt_editCurrent.Exists);
            txt_editCurrent.WaitUntilExists(3000);

            window.GoTo("http://localhost:13164/Photo/PhotoAlbumManager.aspx");

            btn_ctl00ContentPlac.Click();

            spn_ctl00_ContentPla.Click();

            txt_editCurrent.Click();


            txt_editCurrent.AppendText("!!");
            txt_editCurrent.KeyDown('\n');
        }
Esempio n. 3
0
 public void SetUp()
 {
     Settings.WaitForCompleteTimeOut = 10;
     Settings.WaitUntilExistsTimeOut = 10;
     ie = new IE();
     ie.GoTo(url + "ProspectorPlus/VendorLogin.aspx");
     ie.ShowWindow(NativeMethods.WindowShowStyle.Maximize);
 }
Esempio n. 4
0
        public void NavigateTo(string url)
        {
            if (_browser == null)
            {
                _browser = new IE();
            }

            _browser.GoTo(url);
        }
        /// <summary>
        /// Registers the standard test user.
        /// </summary>
        /// <param name="browser">The <paramref name="browser"/> instance.</param>
        /// <param name="userName">Name of the user.</param>
        /// <param name="password">The password.</param>
        /// <returns>
        /// If User was Registered or not
        /// </returns>
        public static bool RegisterStandardTestUser(IE browser, string userName, string password)
        {
            browser.GoTo("{0}yaf_register.aspx".FormatWith(TestConfig.TestForumUrl));

            var email = "{0}@test.com".FormatWith(userName.ToLower());

            browser.ShowWindow(NativeMethods.WindowShowStyle.Maximize);

            // Check if Registrations are Disabled
            if (browser.ContainsText("You tried to enter an area where you didn't have access"))
            {
                return false;
            }

            // Accept the Rules
            if (browser.ContainsText("Forum Rules"))
            {
                browser.Button(Find.ById("forum_ctl04_Login1_LoginButton")).Click();
                browser.Refresh();
            }

            if (browser.ContainsText("Security Image"))
            {
                return false;
            }

            // Fill the Register Page
            browser.TextField(Find.ById(new Regex("CreateUserWizard1_CreateUserStepContainer_UserName"))).TypeText(
                userName);

            if (browser.ContainsText("Display Name"))
            {
                browser.TextField(Find.ById(new Regex("CreateUserWizard1_CreateUserStepContainer_DisplayName"))).TypeText(userName);
            }

            browser.TextField(Find.ById(new Regex("CreateUserWizard1_CreateUserStepContainer_Password"))).TypeText(password);
            browser.TextField(Find.ById(new Regex("CreateUserWizard1_CreateUserStepContainer_ConfirmPassword"))).TypeText(password);
            browser.TextField(Find.ById(new Regex("CreateUserWizard1_CreateUserStepContainer_Email"))).TypeText(email);
            browser.TextField(Find.ById(new Regex("CreateUserWizard1_CreateUserStepContainer_Question"))).TypeText(password);
            browser.TextField(Find.ById(new Regex("CreateUserWizard1_CreateUserStepContainer_Answer"))).TypeText(password);

            ////browser.TextField(Find.ById(new Regex("CreateUserWizard1_CreateUserStepContainer_tbCaptcha"))).TypeText(captcha);

            // Create User
            browser.Button(Find.ById(new Regex("CreateUserWizard1_CreateUserStepContainer_StepNextButton"))).Click();

            if (!browser.ContainsText("Forum Preferences"))
            {
                return false;
            }

            browser.Button(Find.ById(new Regex("ProfileNextButton"))).Click();

            return browser.Link(Find.ById(new Regex("_LogOutButton"))).Exists;
        }
Esempio n. 6
0
        public void NavigateTo(string url)
        {
            Debug.WriteLine("Navigating browser to " + url);

            if (_browser == null)
            {
                _browser = new IE();
            }

            _browser.GoTo(url);
        }
Esempio n. 7
0
        public void MyTestInitialize()
        {
            IISManager.KillW3WP();
             DatabaseManager.DropDatabase(TestEnvironment.DatabaseName);
             DatabaseManager.CopyAndAttachDatabase(TestContext, TestEnvironment.DatabaseName);

             // Open a new Internet Explorer window and navigate to the website
             ie = new IE();
             ie.GoTo(TestEnvironment.PortalUrl);

             Login(TestUsers.Admin.UserName, TestUsers.Admin.Password, TestUsers.Admin.DisplayName);
        }
Esempio n. 8
0
 public Browser Authorize(string login, string password)
 {
     Browser browser = new IE("https://www.codeplex.com/site/login");
     
     browser.GoTo("https://www.codeplex.com/site/login");
     browser.Link("CodePlexLogin").Click();
     browser.TextField("UserName").TypeText(login);
     browser.TextField("Password").TypeText(password);
     browser.Button("loginButton").Click();
     
     return browser;
 }
Esempio n. 9
0
        /// <summary>
        /// Opens a new IE instance with the given settings in front of other windows that are currently open.
        /// </summary>
        /// <param name="targetURL">The URL that the IE instance should browse to.</param>
        /// <param name="silentMode">If true the test will be run without displaying any IE instance or steps.</param>
        /// <param name="timeOut">The default time out to use when calling IE.AttachToIE(findby).</param>
        /// <param name="autoCloseIE">If true when a reference to the IE instance is destroyed the actual window will close.</param>
        /// <param name="movePointer">It true the mouse pointer will move to the top left corner of the screen when a new IE instance is created.</param>
        /// <returns>The new IE instance.</returns>
        public static IE OpenIEInstance(string targetURL, bool silentMode, int timeOut, bool autoCloseIE, bool movePointer)
        {
            Settings.MakeNewIeInstanceVisible = !silentMode;
            Settings.WaitForCompleteTimeOut = timeOut;
            Settings.WaitUntilExistsTimeOut = timeOut;
            Settings.AttachToBrowserTimeOut = timeOut;
            Settings.AutoMoveMousePointerToTopLeft = movePointer;

            IE ieInstance = new IE { AutoClose = autoCloseIE };
            if(!silentMode) ieInstance.ShowWindow(NativeMethods.WindowShowStyle.ShowMaximized);
            ieInstance.BringToFront();
            ieInstance.GoTo(targetURL);

            return ieInstance;
        }
        public bool Login(string username, string password)
        {
            ie = new IE();

            ie.GoTo("http://www.cruisecontrolnet.org/login");
            if (!AtChiliCCNet()) return false;

            ie.TextField(WatiN.Core.Find.ByName("username")).SetAttributeValue("value", username);

            ie.TextField(WatiN.Core.Find.ByName("password")).SetAttributeValue("value", password);
            ie.Button(WatiN.Core.Find.ByName("login")).Click();

            if (ie.Elements.Exists("password")) return false; // still on logon page, so login failed

            return true;
        }
        public void Adding_Items_ToCart()
        {
            using (var browser = new IE())
            {
                browser.GoTo("http://localhost:1100/");

                browser.BringToFront();

                browser.Link(Find.ByText("Pop")).Click();

                browser.Link(Find.ByText("Frank")).Click();

                browser.Link(Find.ByText("Add to cart")).Click();

                Assert.IsTrue(browser.ContainsText("8.99"));
            }
        }
        private void Login(ref IE ie)
        {
            Utilities.NavigateToHomePage(ref ie);

            if (ie.Url.Contains("Login"))
            {
                ie.GoTo(Utilities.GetUrl("Index.aspx"));

                string UserName = ConfigurationReader.getWebUserName();
                string Password = ConfigurationReader.getWebPassword();

                ie.TextField(Find.ById("txtUsername")).TypeText(UserName);
                ie.TextField(Find.ById("txtPassword")).TypeText(Password);

                ie.Image(Find.ById("IbLogin")).ClickNoWait();
            }
        }
        public void Demonstrate_speed()
        {
            new DatabaseTester().Clean();

            var url = "http://localhost:1234/";
            using (var ie = new IE(url))
            {
                for (int i = 0; i < 50; i++)
                {
                    ie.GoTo("http://localhost:1234/");
                    ie.TextField("PathAndQuerystring").Value = "/MyUrl";
                    ie.TextField("LoginName").Value = "SomeComputer\\ThisUser";
                    ie.Button("submit").Click();

                    ie.ContainsText("/MyUrl");
                    ie.ContainsText("SomeComputer\\ThisUser").ShouldBeTrue();
                }
                
            }
        }
Esempio n. 14
0
        public void WatinOverview()
        {
            using (var ie = new IE())
            {
                ie.BringToFrontForDemo();
                ie.AutoClose = false;

                // Navigate
                ie.GoTo("http://localhost:62988/Register.aspx");

                // Finding a HTML element by id
                var passwordTextBox = ie.TextField(Find.ById("Password"));

                // Typing text
                passwordTextBox.TypeText("Hello World");

                // Clicking a button
                ie.Button(Find.ById("DoRegister")).Click();
            }
        }
        public void RemoveItemsFromCart()
        {
            using (var browser = new IE())
            {
                browser.GoTo("http://localhost:1100/");

                browser.BringToFront();

                browser.Link(Find.ByText("Pop")).Click();

                browser.Link(Find.ByText("Frank")).Click();

                browser.Link(Find.ByText("Add to cart")).Click();

                browser.Link(Find.BySelector("a.RemoveLink")).Click();

                Assert.IsTrue(browser.ContainsText("0"));

            }
        }
Esempio n. 16
0
        public bool DeletePostByTitle(string title, IE ie)
        {
            ie.GoTo(Url);
            ie.WaitForComplete();

            var tblPosts = ie.Table("Posts");

            if (tblPosts != null)
            {
                foreach (var row in tblPosts.TableRows)
                {
                    if (!string.IsNullOrEmpty(row.Id) && row.InnerHtml.Contains(title))
                    {
                        ie.Link("a-" + row.Id).Click();
                        return true;
                    }
                }
            }
            return false;
        }
Esempio n. 17
0
        public void Register()
        {
            try
            {
                Ie = new IE("about:blank");
                Ie.GoTo("http://localhost/GuestBook/GuestBook.aspx");
                Ie.TextField(Find.ByName("name")).TypeText("Jay");
                Ie.TextField(Find.ByName("comments")).TypeText("Hello");
                Ie.Button(Find.ByName("save")).Click();

                Assert.AreEqual("Jay", Ie.TableCell(Find.By("innerText", "Jay")).Text, @"innerText does not match");
                Assert.AreEqual("Hello", Ie.TableCell(Find.By("innerText", "Hello")).Text, @"innerText does not match");
            }
            finally
            {
                if (Ie != null)
                {
                    InternetExplorer internetExplorer = (InternetExplorer)Ie.InternetExplorer;
                    internetExplorer.Quit();
                }
            }
        }
Esempio n. 18
0
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                IE ie = new IE();

                ie.GoTo("www.terra.com.br");

                ie.WaitForComplete();

                ie.TextField("autocomplete").Value = "esporte";
                ie.TextField("autocomplete").Focus();

                SendKeys.SendWait("{ENTER}");
                //ie.TextField("autocomplete").KeyPress((char)Keys.Enter);

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }
        }
        public void SetUp()
        {
            bool IsWebStarted;
            rootUrl = string.Format("http://*****:*****@".UnitTest")) ;
                    
                    //Environment.CurrentDirectory.Substring(0,Environment.CurrentDirectory.LastIndexOf('\\'));
                string commandArgs = string.Format(" /path:\"{0}\" /port:{1} /vapth:\"/{2}\"", rootPhyPath, devServerPort, rootpath);

                cmdProcess = new Process();
                cmdProcess.StartInfo.Arguments = commandArgs;
                cmdProcess.StartInfo.CreateNoWindow = true;
                cmdProcess.StartInfo.FileName = command;
                cmdProcess.StartInfo.UseShellExecute = false;
                cmdProcess.StartInfo.WorkingDirectory = command.Substring(0, command.LastIndexOf('\\'));
               if( !cmdProcess.Start())
                   throw new Exception("Cannot start webserver");
                
                // .. and try one more time to see if the server is up
                ie.GoTo(rootUrl);
            }
            Assert.IsTrue(ie.ContainsText("Directory Listing -- /"));

            // Give some time to crank up
            Thread.Sleep(1000);
        }
        public void Login_Successful_Should_Have_LogOut_Link()
        {
            using (var browser = new IE())
            {
                browser.GoTo("http://localhost:1100/");

                browser.BringToFront();

                browser.Link(Find.ByText("Admin")).Click();

                //browser.Element(x => x.)

                browser.TextField(Find.ById("UserName")).TypeText("administrator");

                browser.TextField(Find.ById("Password")).TypeText("password123!");

                browser.Element(Find.BySelector("input.LogOn")).Click();

                Assert.IsTrue(browser.Link(Find.ByText("Log Out")).Exists);

                browser.Link(Find.ByText("Log Out")).Click();

            }
        }
 public void GivenIAmOnTheGoogleHomePage()
 {
     WebBrowser = new IE();
     WebBrowser.GoTo(@"http://yandex.ru");
 }
        private void Go_Click(object sender, EventArgs e)
        {
            _IsProduct = false;
            _percent.Visible = false;
            _Bar1.Value = 0;
            _lblerror.Visible = false;
            _Pages = 0;
            _TotalRecords = 0;
            gridindex = 0;
            _IsCategory = true;
            _Stop = false;
            time = 0;

            _Worker1 = new IE();
            _Worker2 = new IE();

            #region Factory.ca
            _ScrapeUrl = "http://www.factorydirect.ca/SearchResults.aspx";
            try
            {

                _lblerror.Visible = true;
                _lblerror.Text = "We are going to read category Link for factorydirect.ca Website";
                int counterReload = 0;
                bool isError = false;

                _Worker1.GoTo(_ScrapeUrl);
                _Worker1.WaitForComplete();
                System.Threading.Thread.Sleep(10000);
                _Work1doc.LoadHtml(_Worker1.Html);

                HtmlNodeCollection _CollectionCatLink = _Work1doc.DocumentNode.SelectNodes("//b[@class=\"nxt-result-total\"]");
                if (_CollectionCatLink != null)
                {
                    try
                    {
                        _TotalRecords = Convert.ToInt32(_CollectionCatLink[0].InnerText.Trim());
                        if ((_TotalRecords % 36) == 0)
                        {
                            _Pages = Convert.ToInt32(_TotalRecords / 36);
                        }
                        else
                        {
                            _Pages = Convert.ToInt32(_TotalRecords / 36) + 1;
                        }
                    }
                    catch
                    { }

                    while (_Work.IsBusy || _Work1.IsBusy)
                    {
                        Application.DoEvents();

                    }
                    if (_TotalRecords > 0)
                    {
                        gridindex = 0;
                        _Bar1.Value = 0;
                        _percent.Visible = false;
                        _lblerror.Visible = true;
                        _lblerror.Text = "We are going to read products from search page.";
                        _Stop = false;
                        time = 0;
                        _IsCategory = true;
                        tim(3);
                        totalrecord.Visible = true;

                        for (int Page = 1; Page <= _Pages; Page++)
                        {
                            CategoryUrl.Add("http://www.factorydirect.ca/SearchResults.aspx#/?search_return=all&res_per_page=36&page=" + Page);
                        }
                        totalrecord.Text = "Total No Pages :" + CategoryUrl.Count.ToString();

                        foreach (string url in CategoryUrl)
                        {
                            while (_Work.IsBusy && _Work1.IsBusy)
                            {
                                Application.DoEvents();
                            }

                            if (!_Work.IsBusy)
                            {
                                Url1 = url;
                                _Work.RunWorkerAsync();
                            }
                            else
                            {
                                Url2 = url;
                                _Work1.RunWorkerAsync();
                            }

                        }
                        while (_Work.IsBusy || _Work1.IsBusy)
                        {
                            Application.DoEvents();

                        }
                        _lblerror.Visible = true;
                        _lblerror.Text = "We are going to read product info.";
                        _IsCategory = false;
                        _IsProduct = true;
                        gridindex = 0;
                        totalrecord.Text = "Total No Products :" + Producturl.Count.ToString();
                        foreach (var url in Producturl)
                        {
                            while (_Work.IsBusy && _Work1.IsBusy)
                            {
                                Application.DoEvents();
                            }

                            if (!_Work.IsBusy)
                            {
                                Url1 = url.Key;
                                _Work.RunWorkerAsync();
                            }
                            else
                            {
                                Url2 = url.Key;
                                _Work1.RunWorkerAsync();
                            }
                        }
                        while (_Work.IsBusy || _Work1.IsBusy)
                        {
                            Application.DoEvents();

                        }

                        #region InsertScrappedProductInDatabase

                        if (Products.Count() > 0)
                        {
                            _Prd.ProductDatabaseIntegration(Products, "factorydirect.ca", 1);

                        }
                        else
                        {
                            BusinessLayer.DB _Db = new BusinessLayer.DB();
                            _Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='factorydirect.ca'");
                            _Prd.ProductDatabaseIntegration(Products, "factorydirect.ca", 1);
                            _Mail.SendMail("OOPS there is no any product scrapped by app for factorydirect.ca Website." + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
                        }
                        #endregion InsertScrappedProductInDatabase
                    }
                    else
                    {
                        BusinessLayer.DB _Db = new BusinessLayer.DB();
                        _Prd.ProductDatabaseIntegration(Products, "factorydirect.ca", 1);
                        _Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='factorydirect.ca'");
                        _lblerror.Text = "Oops there is change in html code  on client side. You need to contact with developer in order to check this issue for factorydirect.ca Website";
                        /****************Email****************/
                        _Mail.SendMail("Oops there is change in html code  on client side. You need to contact with developer in order to check this issue for factorydirect.ca Website as soon as possible because noscrapping of given store is stopped working." + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
                        /*******************End********/
                    }

                }

                else
                {
                    BusinessLayer.DB _Db = new BusinessLayer.DB();
                    _Prd.ProductDatabaseIntegration(Products, "factorydirect.ca", 1);
                    _Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='factorydirect.ca'");
                    _lblerror.Text = "Oops there is change in html code  on client side. You need to contact with developer in order to check this issue for factorydirect.ca Website";
                    /****************Email****************/
                    _Mail.SendMail("Oops there is change in html code  on client side. You need to contact with developer in order to check this issue for factorydirect.ca Website as soon as possible because noscrapping of given store is stopped working." + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);
                    /*******************End********/
                }
            }
            catch
            {
                BusinessLayer.DB _Db = new BusinessLayer.DB();
                _Db.ExecuteCommand("update Schduler set LastProcessedStatus=0 where StoreName='factorydirect.ca'");
                _lblerror.Visible = true;
                _Mail.SendMail("Oops Some issue Occured in scrapping data factorydirect.ca Website" + DateTime.Now.ToString(), "Urgent issue in Scrapper.", false, false, 1);

            }
            while (_Work.IsBusy || _Work1.IsBusy)
            {
                Application.DoEvents();

            }
            # endregion Factory.CA
            writer.Close();

            try { _Worker1.Close(); _Worker2.Close(); }
            catch
            {

            }
            this.Close();
        }
Esempio n. 23
0
        public void FetchLeetCode()
        {
            using (var browser = new IE("https://leetcode.com"))
            {

                using (StreamReader sr = new StreamReader(Directory + @"template\solution.html"))
                {
                    string solutionTemplate = sr.ReadToEnd();

                    using (StreamReader questionReader = new StreamReader(Directory + @"template\question.html"))
                    {
                        string questionTemplate = questionReader.ReadToEnd();

                        var toHtml = new IE("http://hilite.me/");

                        browser.Link(Find.ByClass("btn btn-default")).Click();
                        browser.TextField(Find.ById("id_login")).SetAttributeValue("value", "*****@*****.**"); //TypeText("*****@*****.**");
                        browser.TextField(Find.ById("id_password")).SetAttributeValue("value", "Test123"); //.TypeText("Test123");
                        browser.Button(Find.ByText("Sign In")).Click();

                        for (int i = 115; i < 300; ++i)
                        {
                            var table = browser.Table(Find.ById("problemList"));
                            var body = table.TableBodies[0];
                            foreach (var row in body.OwnTableRows)
                            {
                                if (row.Elements != null && row.Elements.Count > 0 && "ac" == row.Elements[1].ClassName)
                                {
                                    var cell2 = row.Elements[2] as TableCell;
                                    string questionIndex = cell2.Text;

                                    if (Int32.Parse(questionIndex) == i)
                                    {
                                        var cell = row.Elements[3] as TableCell;
                                        string questionName = cell.Text;
                                        cell.Links[0].Click();

                                        var questionDiv = browser.Div(Find.ByClass("question-content"));

                                        string questionContent = "";

                                        for (int j = 0; j < questionDiv.Paras.Count; ++j)
                                        {
                                            if (!string.IsNullOrEmpty(questionDiv.Paras[j].Text) &&
                                                questionDiv.Paras[j].Text.StartsWith("<b>Notes:</b>"))
                                            {
                                                break;
                                            }
                                            questionContent += "<p>" + questionDiv.Paras[j].Text + "</p>";
                                        }

                                        //browser.Links.SelectMany(l => l.Text == "My Submissions");
                                        browser.Links.Filter(l => l.Text == "My Submissions").Where(l => l.Url != "https://leetcode.com/submissions/").First().Click();
                                        //browser.Link(Find.ByText("My Submissions") ).  .Click();
                                        browser.WaitForComplete();

                                        var tableResult = browser.Table(Find.ById("result_testcases"));
                                        var resultBody = tableResult.TableBodies[0];

                                        string solutionCode = "";

                                        foreach (var resultRow in resultBody.OwnTableRows)
                                        {
                                            if (resultRow.Elements[3].Text.Contains("Accepted"))
                                            {
                                                var acceptedCell = resultRow.Elements[3] as TableCell;
                                                acceptedCell.Links[0].Click();

                                                var div = browser.Div(Find.ByClass("ace_content"));
                                                solutionCode = div.Text;
                                                solutionCode = solutionCode.Replace("\r\n\r\n", "\r\n");
                                                break;
                                            }
                                        }

                                        toHtml.TextField(Find.ById("divstyles")).SetAttributeValue("value", "padding:.1em .3em;");

                                        toHtml.TextField(Find.ByName("code")).SetAttributeValue("value", solutionCode);

                                        toHtml.SelectList(Find.ByName("lexer")).SelectByValue("cpp");

                                        toHtml.Button(Find.ByValue("Highlight!")).Click();

                                        toHtml.WaitForComplete(3);

                                        string questionhtml = questionTemplate.Replace("<%QuestionName%>", questionName).Replace("<%QuestionContent%>", questionContent);
                                        string solutonhtml = solutionTemplate.Replace("<%QuestionName%>", questionName).Replace("<%SolutionTemplate%>", toHtml.TextField(Find.ById("html")).Text);
                                        solutonhtml = solutonhtml.Replace("margin: 0; line-height: 125%", "margin: 0; line-height: 125%; white-space: pre-wrap;");

                                        string solutionFilename = Directory + "output\\" + questionIndex + ".solution.html";
                                        string questionFileName = Directory + "output\\" + questionIndex + ".question.html";

                                        System.IO.File.WriteAllText(solutionFilename, solutonhtml);
                                        System.IO.File.WriteAllText(questionFileName, questionhtml);

                                        browser.GoTo("https://leetcode.com/problemset/algorithms/");
                                    }
                                }
                            }

                        }

                    }
                }
            }
        }
Esempio n. 24
0
        public void SignupPage()
        {
            clsDBQueryManager SetDb = new clsDBQueryManager();
            DataSet ds = new DataSet();
            //bool UsePublicProxy = false;
            int counter_Username = 0;
            foreach (string EmailPassword in LstAccountcreationEmailPassword)
            {
            StartAgain:
                try
                {
                    GlobusHttpHelper httpHelper = new GlobusHttpHelper();
                    string[] array = Regex.Split(EmailPassword, ":");
                    string email = array[0];
                    string password = array[1];
                    string username = string.Empty;
                    string ProxyAdress = string.Empty;
                    string ProxyPort = string.Empty;
                    string Proxy = string.Empty;
                    AddToProxyAccountCreationLog("Clearing Cookies");
                    ClearCookies();
                    if (chkboxUsePublicProxies.Checked)
                    {
                        try
                        {
                            ds = SetDb.SelectPublicProxyData();
                            if (ds.Tables[0].Rows.Count != 0)
                            {
                                int index = RandomNumberGenerator.GenerateRandom(0, ds.Tables[0].Rows.Count);
                                DataRow dr = ds.Tables[0].Rows[countForInstance];
                                Proxy = dr.ItemArray[0].ToString() + ":" + dr.ItemArray[1].ToString() + ":" + dr.ItemArray[2].ToString() + ":" + dr.ItemArray[3].ToString();
                                string[] ProxyList = Regex.Split(Proxy, ":");
                                ProxyAdress = ProxyList[0];
                                ProxyPort = ProxyList[1];
                                
                                AddToProxyAccountCreationLog("Using Proxy Address : - " + ProxyAdress + ":" + ProxyPort);
                            }
                            else
                            {
                                AddToProxyAccountCreationLog("Please Uplaod Public Proxies");
                                break;
                            }
                        }
                        catch (Exception ex)
                        {

                        }
                    }

                    AddToProxyAccountCreationLog("Setting Proxy");

                    Thread.Sleep(2000);

                    SetProxy(ProxyAdress, ProxyPort);

                    Thread.Sleep(2000);

                    IE explorer = new IE();

                    Thread.Sleep(1000);

                    if (LstAccountcreationUsername.Count > 0)
                    {
                        if (counter_Username < LstAccountcreationUsername.Count)
                        {
                            username = LstAccountcreationUsername[counter_Username];
                            counter_Username++;
                        }
                        else
                        {
                            AddToProxyAccountCreationLog("*********** /n All Usernames have been taken /n ***********");
                            break;
                        }
                    }
                    else
                    {
                        AddToProxyAccountCreationLog("Please Upload Usernames To Create Twitter Accounts");
                        break;
                    }

                    string name = LstAccountCreationName[countForInstance];
                    string capcthaUrl = string.Empty;

                    try
                    {
                        explorer.GoTo("https://twitter.com/signup");

                        string PageSource = explorer.Html.ToString();
                        if (PageSource.Contains("Sign out"))
                        {
                            explorer.Link(Find.ById("signout-button")).Click();
                            Thread.Sleep(2000);
                            explorer.GoTo("https://twitter.com/signup");
                            Thread.Sleep(2000);
                        }
                    }
                    catch (Exception ex)
                    {
                        AddToProxyAccountCreationLog("Taking too Long To respond.Page Not Loaded Fully");
                        break;
                    }

                    try
                    {

                        foreach (TextField item in explorer.TextFields)
                        {
                            string Html = item.OuterHtml.ToString();
                            if (item.Name == "user[name]")
                            {
                                AddToProxyAccountCreationLog("Name :" + name);
                                item.TypeText(name);
                                Thread.Sleep(1000);
                                break;
                            }
                        }

                        foreach (TextField item in explorer.TextFields)
                        {
                            if (item.Name == "user[email]")
                            {
                                AddToProxyAccountCreationLog("Email :" + email);
                                item.TypeText(email);
                                Thread.Sleep(1000);
                                break;
                            }
                        }

                        string EmailCheck = explorer.Html.ToString();
                        Thread.Sleep(8000);
                        if (EmailCheck.Contains("taken error active") || EmailCheck.Contains("invalid error active") || EmailCheck.Contains("blank error active"))
                        {
                            AddToProxyAccountCreationLog("Error In Email - " + email);
                            GlobusFileHelper.AppendStringToTextfileNewLine(email + ":" + password + ":" + ProxyAdress + ":" + ProxyPort, Globals.path_DesktopFolder + "\\TwtDominator\\BrowserAccountUnsuccessfull.txt");
                        }
                        else
                        {
                            foreach (TextField item in explorer.TextFields)
                            {
                                string Html = item.OuterHtml.ToString();
                                if (item.Name == "user[user_password]")
                                {
                                    AddToProxyAccountCreationLog("Password :"******"invalid error active") || !CheckPassword.Contains("blank error active") || !CheckPassword.Contains("blank error active") || CheckPassword.Contains("weak error active"))
                            {
                                AddToProxyAccountCreationLog("Password Not Secure creating Other");
                                password = password + RandomStringGenerator.RandomString(5);
                                if (password.Count() > 15)
                                {
                                    password = password.Remove(13); //Removes the extra characters
                                }

                                foreach (TextField item in explorer.TextFields)
                                {
                                    string Html = item.OuterHtml.ToString();
                                    if (item.Name == "user[user_password]")
                                    {
                                        AddToProxyAccountCreationLog("Password :"******"Username : "******""))
                                //{
                                if (item.Name == "user[screen_name]")
                                {
                                    item.TypeText(username);
                                    Thread.Sleep(1000);
                                    break;
                                }
                                //}
                            }

                            string Usernamecheck = explorer.Html.ToString();
                            if (!Usernamecheck.Contains("taken error active") || !Usernamecheck.Contains("invalid error active") || !Usernamecheck.Contains("blank error active"))
                            {
                                if (username.Count() > 12)
                                {
                                    username = username.Remove(8); //Removes the extra characters
                                }
                                username = username + RandomStringGenerator.RandomString(5);
                                if (username.Count() > 15)
                                {
                                    username = username.Remove(13); //Removes the extra characters
                                }
                                foreach (TextField item in explorer.TextFields)
                                {
                                    if (item.Name == "user[screen_name]")
                                    {
                                        item.TypeText(username);
                                        Thread.Sleep(1000);
                                        break;
                                    }
                                }
                            }


                            Thread.Sleep(2000);

                            string PageSource = explorer.Html.ToString();

                            if (PageSource.Contains("sign-up-box"))
                            {
                                AddToProxyAccountCreationLog("Creating Twitter Account With Email : " + email);
                                explorer.Button(Find.ByValue("Create my account")).Click();
                                Thread.Sleep(2000);
                            }
                           
                                string PageSourceSignup = explorer.Html.ToString();


                                if (PageSource.Contains("signout-button") && PageSource.Contains("js-signout-button"))
                                {
                                    AddToProxyAccountCreationLog("Creating Twitter Account With Email : " + email);
                                    GlobusFileHelper.AppendStringToTextfileNewLine(email + ":" + password, Globals.Path_BrowserCreatedAccounts);
                                    string GetSignout = explorer.Html.ToString();
                                    if (GetSignout.Contains("Sign out"))
                                    {
                                        explorer.Link(Find.ById("signout-button")).Click();
                                        Thread.Sleep(2000);
                                        countForInstance++;
                                    }
                                }
                                else if (PageSource.Contains("Are you human?"))
                                {
                               
                                    AddToProxyAccountCreationLog("Checking For Human??");
                                
                                    Thread.Sleep(3000);
                                    try
                                    {
                                        foreach (Div Item in explorer.Divs)
                                        {
                                            string Url = Item.OuterHtml.ToString();
                                            if (Item.Id == "recaptcha_image")
                                            {
                                                int startIndex = Url.IndexOf("src=\"");
                                                string start = Url.Substring(startIndex).Replace("src=\"", "");
                                                int endIndex = start.IndexOf("\"");
                                                string end = start.Substring(0, endIndex);
                                                capcthaUrl = end;
                                                break;
                                            }
                                        }
                                        int i = 0;
                                       WebClient webclient = new WebClient();
                                   StartWebClient:
                                        Thread.Sleep(2000);
                                        try
                                        {
                                            byte[] args = webclient.DownloadData(capcthaUrl);
                                            string[] arr1 = new string[] { BaseLib.Globals.DBCUsername, BaseLib.Globals.DBCPassword, "" };
                                            string CapcthaString = DecodeDBC(arr1, args);
                                            foreach (TextField item in explorer.TextFields)
                                            {

                                                string Html = item.OuterHtml.ToString();
                                                if (item.Id == "recaptcha_response_field")
                                                {
                                                    AddToProxyAccountCreationLog("Adding Capctha Response");
                                                    item.TypeText(CapcthaString);
                                                    break;
                                                }
                                            }
                                            explorer.Button(Find.ByValue("Create my account")).Click();
                                        }
                                        catch (Exception ex)
                                        {
                                            i++;
                                            if (ex.Message.Contains("An exception occurred during a WebClient request."))
                                            {
                                                AddToProxyAccountCreationLog("Error In Capctha Download Trying Again - " + i);
                                                if (i <= 3)
                                                {
                                                    goto StartWebClient;
                                                }
                                                else
                                                {
                                                    GlobusFileHelper.AppendStringToTextfileNewLine(email + ":" + password + ":" + ProxyAdress + ":" + ProxyPort, Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\TwtDominator\\UnsuccessfullBrowserAcounts.txt");
                                                }
                                            }
                                        }
                                    }

                                    catch (Exception ex)
                                    {
                                       
                                    }

                                    string ConfirmId = explorer.Html.ToString();

                                    AddToProxyAccountCreationLog("Confirming created Account");
                                    if (!ConfirmId.Contains("Sign out"))
                                    {
                                        AddToProxyAccountCreationLog("Account Not Created : " + email + ":" + password);
                                        GlobusFileHelper.AppendStringToTextfileNewLine(email + ":" + password + ":" + ProxyAdress + ":" + ProxyPort, Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\TwtDominator\\UnsuccessfullBrowserAcounts.txt");
                                    }
                                    else if (ConfirmId.Contains("Sign out"))
                                    {
                                        GlobusFileHelper.AppendStringToTextfileNewLine(email + ":" + password + ":" + ProxyAdress + ":" + ProxyPort, Globals.Path_BrowserCreatedAccounts);
                                        explorer.GoTo("https://twitter.com/");
                                        explorer.Link(Find.ById("signout-button")).Click();
                                        Thread.Sleep(1000);
                                    }
                                }
                            }
                        
                    }
                    catch (Exception ex)
                    {
                        if (ex.Message == "The remote server returned an error: (504) Gateway Timeout.")
                        {
                            AddToProxyAccountCreationLog("Remote Server Returned Error - Time out");
                        }
                        explorer.Close();
                        AddToProxyAccountCreationLog("Closing Explorer Due To Error");
                        goto StartAgain;
                    }
                         
                    explorer.Close();
                    countForInstance++;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error :: - " + DateTime.Now.ToString() + " || Error - " + ex.Message);
                        if (ex.Message.Contains("Creating an instance of the COM component with"))
                        {
                            goto StartAgain;
                        }
                    }
            }
        
        }
        private static void LoginAsAdmin(IE netWindow)
        {
            //go to login page
            netWindow.GoTo("http://*****:*****@hotmail.com");
            netWindow.TextField(Find.ById("ctl00_ContentPlaceHolder1_ucLogin_txtPassword")).TypeText("");
            netWindow.Button(Find.ById("ctl00_ContentPlaceHolder1_ucLogin_btnLogin")).Click();
            netWindow.WaitForComplete(100);
        }
Esempio n. 26
0
        public void WebApplicationScraping()
        {
            try
            {
                // Reads the path of the web application
                string webSitePath = Convert.ToString(ConfigurationManager.AppSettings["WebApplicationPath"]);
                string filePhysicalPath = Convert.ToString(ConfigurationManager.AppSettings["ScraperEnginePhysicalLocation"]);

                StreamWriter file = new StreamWriter(filePhysicalPath + "Output.txt");

                if (webSitePath != null && webSitePath != string.Empty)
                {
                    // Create an instance of IE browser
                    IE ieInstance = new IE(webSitePath);

                    // This will opens IE browser in maximized mode
                    ieInstance.ShowWindow(WatiN.Core.Native.Windows.NativeMethods.WindowShowStyle.ShowMaximized);

                    // Watin window will not visible to the end user when web scraping is done
                    //ieInstance.Visible = false;

                    // This will wait for the browser to complete loading of the page
                    ieInstance.WaitForComplete();

                    // This will store page source in categoryPageSource variable
                    string categoryPageSource = ieInstance.Html;

                    // Regular expression pattern to fetch list of categories categories

                    Regex categoryMatches = new Regex(_categoryRegEx, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.CultureInvariant);

                    // Fetches all the categories based upon category regex from category listing page
                    MatchCollection categoryMatchCollection = categoryMatches.Matches(categoryPageSource);

                    // Navigate to each categories and fetch page URL and navigate to the item listing page for each categories
                    foreach (Match categoryMatch in categoryMatchCollection)
                    {
                        GroupCollection categoryGroup = categoryMatch.Groups;

                        // URL of the item listing page
                        string itemListingURL = Convert.ToString(categoryGroup["href"].Value);

                        // Partial web path where demonstration web site is deployed.
                        // Note: This path needs to be modified in App.Config file accordingly.
                        string webSiteHostedLocation = webSitePath.Remove(webSitePath.LastIndexOf("/"));

                        // Creates path of the category listing page.
                        string itemListingpath = webSiteHostedLocation + "/" + itemListingURL;

                        // Navigate to the item listing page
                        ieInstance.GoTo(itemListingpath);

                        ieInstance.WaitForComplete();

                        // HTML source of given generated web page
                        string itemListingPageSource = ieInstance.Html;

                        // Match for the paging Event
                        Regex pagingMatches = new Regex(_pagingRegEx, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.CultureInvariant | RegexOptions.Multiline);

                        // Find Matches.
                        MatchCollection pagingMatchCollection = pagingMatches.Matches(itemListingPageSource);

                        foreach (Match pageMatch in pagingMatchCollection)
                        {
                            GroupCollection pagingGroup = pageMatch.Groups;

                            if (pagingGroup[_pageNumber].Value != "1")
                            {
                                // Fetches the page number of the current page.
                                string linkText = Convert.ToString(pagingGroup[_pageNumber].Value);

                                // Performs click event on the given link. For e.g if linkText contains "2" as a value then 
                                //Watin will perform click event on this second link.
                                ieInstance.Link(Find.ByText(linkText)).Click();

                                // Wait for the operation to complete
                                ieInstance.WaitForComplete();

                                // Store the result of the page in itemListingPageSource variable
                                itemListingPageSource = ieInstance.Html;
                            }

                            Regex itemMatches = new Regex(_itemRegEx, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.CultureInvariant);

                            // Fetches all the items based upon item regex from the item listing page
                            MatchCollection itemMatchCollection = itemMatches.Matches(itemListingPageSource);

                            // Navigate to each item and fetch ProductID, ProductName and ProductPrice and store the result in text file
                            foreach (Match itemMatch in itemMatchCollection)
                            {
                                GroupCollection itemGroups = itemMatch.Groups;

                                // Fetch productId from the given item group
                                string productID = Convert.ToString(itemGroups[_productID].Value);

                                // Fetch productName from the given item Group
                                string productName = Convert.ToString(itemGroups[_productName].Value);

                                // Fetch product price from the given product price
                                string productPrice = Convert.ToString(itemGroups[_productPrice].Value);

                                file.WriteLine("ProductID: " + productID);

                                file.WriteLine("Product Name: " + productName);

                                file.WriteLine("Product Price: " + productPrice);

                                file.WriteLine("-----------------------------------------------------------------------------------------------");

                                file.WriteLine("\n");
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Mention category listing website application path");
                }

                file.Close();
            }
            catch (Exception ex)
            {

            }
            finally
            {

            }
        }
Esempio n. 27
0
        private static void StartIE()
        {
            int globalTimeout = 0;
            if (Int32.TryParse(ConfigurationManager.AppSettings["GlobalIETimeout"], out globalTimeout))
            {
                WatiN.Core.Settings.WaitForCompleteTimeOut = globalTimeout;
                defaultTimeout = globalTimeout;
            }

            _ie = new IE();
            //string baseUrl = String.Empty;
            if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["BaseURL"]))
            {
                _ie.GoTo(ConfigurationManager.AppSettings["BaseURL"]);
            }
            if (Convert.ToBoolean(ConfigurationManager.AppSettings["MaximizeBrowser"]))
            {
                _ie.ShowWindow(NativeMethods.WindowShowStyle.ShowMaximized);
            }

            InjectJQueryAjaxMonitor();
            // _ie.AddDialogHandler(new LogonDialogCloser());
            // _ie.AddDialogHandler(new MessageFromPageDialogHandler());
            //_ie.AddDialogHandler(new CloseIEDialogHandler(true));
        }
Esempio n. 28
0
        static void GetSpecificContentWithWatin()
        {
            //Kill all ie
            Process[] processes = Process.GetProcessesByName("iexplore");

            foreach (Process process in processes)
            {
                process.Kill();
            }

            HadithDBEntities ctx = new HadithDBEntities();
            var hadist = (from c in ctx.Hadiths
                          where c.HadithID == 1 || c.HadithID == 3 || c.HadithID == 4
                          select c).ToList();
            using (IE ieInstance = new IE())
            {
                // This will open Internet Explorer browser in maximized mode 
                ieInstance.ShowWindow(WatiN.Core.Native.Windows.NativeMethods.WindowShowStyle.ShowMaximized);
                ieInstance.Visible = false;

                ieInstance.WaitForComplete();
                // This will store page source in categoryPageSource variable 

                

                for (int i = 0; i < hadist.Count; i++)
                {
                    var selHadith = hadist[i];
                    var hadistIndex = (from c in ctx.HadithIndexes
                                       where c.HadithID == selHadith.HadithID
                                       && c.No != null
                                       orderby c.No
                                       select c).ToList();
                    for (int j = 0; j < hadistIndex.Count; j++)
                    {
                        var selIndex = hadistIndex[j];
                        var selURL = string.Format("http://sunnah.com/{0}/{1}", selHadith.Name, selIndex.No);

                        try
                        {
                            int HadithOrder = 0;
                            bool isIndonesian = false;
                            bool isUrdu = false;
                            ieInstance.GoTo(selURL);
                            var RdBtn = ieInstance.RadioButton(Find.ById("ch_indonesian"));
                            var RdBtn2 = ieInstance.RadioButton(Find.ById("ch_urdu"));

                            if (ieInstance.Elements.Exists("ch_indonesian") && RdBtn != null)
                            {
                                try
                                {
                                    RdBtn.Click();
                                    ieInstance.WaitForComplete();
                                    Thread.Sleep(500);
                                    // This will wait for the browser to complete loading of the page 
                                    isIndonesian = true;
                                }
                                catch { }
                            }
                            if (ieInstance.Elements.Exists("ch_urdu") && RdBtn2 != null)
                            {
                                try
                                {
                                    RdBtn2.Click();
                                    ieInstance.WaitForComplete();
                                    Thread.Sleep(500);

                                    // This will wait for the browser to complete loading of the page 
                                    isUrdu = true;
                                }
                                catch { }
                            }
                            string HtmlPage = ieInstance.Html;
                            HtmlDocument doc = new HtmlDocument();
                            doc.LoadHtml(HtmlPage);
                            HadithChapter selChapter = null;
                            int ContentCounter = 0;

                            HadithPage selPage = new HadithPage();
                            selPage.PageNo = selIndex.No;
                            selPage.HadithID = selHadith.HadithID;
                            //get title
                            foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//div"))
                            {
                                if (node.Attributes["class"] != null && !string.IsNullOrEmpty(node.Attributes["class"].Value))
                                {
                                    switch (node.Attributes["class"].Value)
                                    {
                                        case "book_page_english_name":
                                            selPage.Title = node.InnerText.Trim();
                                            break;
                                        case "book_page_arabic_name arabic":
                                            selPage.TitleArabic = node.InnerText.Trim();
                                            //ctx.HadithPages.Add(selPage);
                                            break;
                                        case "chapter":
                                            selChapter = new HadithChapter();
                                            selChapter.HadithID = selHadith.HadithID;
                                            selChapter.PageNo = selPage.PageNo;
                                            //iterate every chapter
                                            var chapterNode = node;
                                            {
                                                var subnode = chapterNode.SelectSingleNode(".//div[@class='echapno']");
                                                if (subnode != null)
                                                {
                                                    try
                                                    {
                                                        selChapter.ChapterNo = Convert.ToInt32(subnode.InnerText.Trim().Replace("(", "").Replace(")", ""));
                                                    }
                                                    catch
                                                    {
                                                        var Parsed = subnode.InnerText.Trim().Replace("(", "").Replace(")", "");
                                                        if (Parsed.Contains(','))
                                                        {
                                                            selChapter.ChapterNo = Convert.ToInt32(Parsed.Split(',')[0]);
                                                        }
                                                        else
                                                        {
                                                            for (int z = 0; z < Parsed.Length; z++)
                                                            {
                                                                if (!(Parsed[z] >= '0' && Parsed[z] <= '9'))
                                                                {
                                                                    Parsed = Parsed.Replace(Parsed[z].ToString(), " ");
                                                                }
                                                            }
                                                            selChapter.ChapterNo = Convert.ToInt32(Parsed.Trim());
                                                        }
                                                    }
                                                }
                                            }
                                            {
                                                var subnode = chapterNode.SelectSingleNode(".//div[@class='englishchapter']");
                                                if (subnode != null)
                                                {
                                                    selChapter.Title = subnode.InnerText.Trim();
                                                }
                                            }
                                            {
                                                var subnode = chapterNode.SelectSingleNode(".//div[@class='arabicchapter arabic']");
                                                if (subnode != null)
                                                {
                                                    selChapter.TitleArabic = subnode.InnerText.Trim();
                                                }
                                            }
                                            //ctx.HadithChapters.Add(selChapter);
                                            break;
                                        case "arabic achapintro":
                                            {
                                                if (selChapter != null)
                                                {
                                                    selChapter.Intro = node.InnerText.Trim();
                                                }
                                            }
                                            break;
                                        case "actualHadithContainer":
                                            HadithContent selContent = new HadithContent();
                                            selContent.HadithID = selHadith.HadithID;
                                            selContent.PageNo = selPage.PageNo;
                                            selContent.HadithOrder = ++HadithOrder;
                                            if (selChapter != null)
                                            {
                                                selContent.ChapterNo = selChapter.ChapterNo;
                                            }
                                            {
                                                var subnode = node.SelectSingleNode(".//div[@class='hadith_narrated']");
                                                if (subnode != null)
                                                {
                                                    selContent.Narated = subnode.InnerText.Trim();
                                                }
                                            }
                                            {
                                                var subnode = node.SelectSingleNode(".//div[@class='text_details']");
                                                if (subnode != null)
                                                {
                                                    selContent.ContentEnglish = subnode.InnerText.Trim();
                                                }
                                            }
                                            if(isIndonesian)
                                            {
                                                var subnode = node.SelectSingleNode(".//div[@class='indonesian_hadith_full']");
                                                if (subnode != null)
                                                {
                                                    selContent.ContentIndonesia = subnode.InnerText.Trim();
                                                }
                                            }
                                            if (isUrdu)
                                            {
                                                var subnode = node.SelectSingleNode(".//div[@class='urdu_hadith_full']");
                                                if (subnode != null)
                                                {
                                                    selContent.ContentUrdu = subnode.InnerText.Trim();
                                                }
                                            }
                                            {
                                                var subnode = node.SelectSingleNode(".//table[@class='gradetable']");
                                                if (subnode != null)
                                                {
                                                    selContent.Grade = subnode.InnerText.Trim();
                                                }
                                            }
                                            {
                                                var subnode = node.SelectSingleNode(".//table[@class='hadith_reference']");
                                                if (subnode != null)
                                                {
                                                    selContent.Reference = subnode.InnerText.Trim();
                                                }
                                            }
                                            {
                                                var subnode = node.SelectNodes(".//span[@class='arabic_sanad arabic']");
                                                if (subnode != null)
                                                {
                                                    selContent.SanadTop = subnode[0].InnerText.Trim();
                                                    selContent.SanadBottom = subnode[1].InnerText.Trim();
                                                }

                                            }
                                            {
                                                var subnode = node.SelectSingleNode(".//span[@class='arabic_text_details arabic']");
                                                if (subnode != null)
                                                {
                                                    selContent.ContentArabic = subnode.InnerText.Trim();
                                                }
                                            }
                                            ctx.HadithContents.Add(selContent);
                                            ContentCounter++;
                                            if (ContentCounter > 100)
                                            {
                                                ctx.SaveChanges();
                                                ContentCounter = 0;
                                            }
                                            break;
                                        default: break;
                                    }
                                }


                            }

                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(selURL + ":" + ex.Message + "-" + ex.StackTrace);
                        }

                        ctx.SaveChanges();
                    }
                }
            }
            Console.WriteLine("selesai");
            Console.ReadLine();
        }
 public void Check_That_When_Not_Logged_In_As_Admin_Then_Trying_Admin_Link_Goes_To_Site_Home_Page()
 {
     var url = string.Empty;
     //Act
     using (IE netWindow = new IE("http://localhost:49573/default.aspx"))
     {
         netWindow.GoTo("http://localhost:49573//administration/default.aspx");
         url = netWindow.Url;
     }
     Assert.AreEqual("http://localhost:49573/default.aspx", url);
 }
		public static void Descargar(string rfc, string contrasena, string carpeta, DateTime fechaDesde, DateTime fechaHasta, TipoBusqueda busqueda)
		{
			using (IE browser = new IE())
			{
				//limpiar sesion y login 
				browser.ClearCookies();
				Thread.Sleep(1000);

				//java login
				browser.GoTo("https://portalcfdi.facturaelectronica.sat.gob.mx");
				browser.WaitForComplete();

				//entrar por contraseña
				browser.GoTo("https://cfdiau.sat.gob.mx/nidp/app/login?id=SATUPCFDiCon&sid=0&option=credential&sid=0");
				browser.TextField(Find.ByName("Ecom_User_ID")).AppendText(rfc);
				browser.TextField(Find.ByName("Ecom_Password")).AppendText(contrasena);
				browser.Button("submit").Click();

				browser.WaitForComplete();

				//ver si nos pudimos loggear
				if (browser.ContainsText("Login failed, please try again") || browser.ContainsText("La entrada no se ha completado"))
				{
					browser.Close();
					throw new Exception("Los datos de acceso son incorrectos para: " + rfc);
				}

				//seleccionar emitidas o recibidas
				if (busqueda == TipoBusqueda.Emitidas)
				{
					browser.RadioButton("ctl00_MainContent_RdoTipoBusquedaEmisor").Click();
				}
				else
				{
					browser.RadioButton("ctl00_MainContent_RdoTipoBusquedaReceptor").Click();
				}

				browser.Button("ctl00_MainContent_BtnBusqueda").Click();

				Log.Write("Tipo busqueda", Log.Information);

				//Creating the directory if it doesn't exists
				if (!System.IO.Directory.Exists(carpeta))
				{
					System.IO.Directory.CreateDirectory(carpeta);
				}

				//facturas emitidas
				if (busqueda == TipoBusqueda.Emitidas)
				{
					browser.WaitUntilContainsText("Fecha Inicial de Emisión");
					browser.RadioButton("ctl00_MainContent_RdoFechas").Click();
					Thread.Sleep(1000);

					//fecha desde
					browser.TextField("ctl00_MainContent_CldFechaInicial2_Calendario_text").Value = fechaDesde.ToString("dd/MM/yyyy");
					//hasta
					browser.TextField("ctl00_MainContent_CldFechaFinal2_Calendario_text").Value = fechaHasta.ToString("dd/MM/yyyy");
					Thread.Sleep(1000);

					//buscar muchas veces por si marca error de lentitud la pagina del sat >(
					while (true)
					{
						browser.Button("ctl00_MainContent_BtnBusqueda").Click();
						Thread.Sleep(3000);

						if (browser.ContainsText("lentitud"))
						{
							browser.Link("closeBtn").Click();
						}
						else
						{
							break;
						}
					}

					DescargarFacturasListadas(browser, carpeta);
				}
				else
				{
					DateTime mesActual = fechaDesde;
					bool primeraVez = true;

					while (mesActual < fechaHasta)
					{
						browser.WaitUntilContainsText("Fecha de Emisión");
						browser.RadioButton("ctl00_MainContent_RdoFechas").Click();
						Thread.Sleep(1000);

						//seleccionar año adecuado
						browser.SelectList("DdlAnio").SelectByValue(mesActual.Year.ToString());
						//seleccionar mes adecuado
						browser.SelectList("ctl00_MainContent_CldFecha_DdlMes").SelectByValue(mesActual.Month.ToString());

						if (mesActual.Day < 10 && primeraVez)
						{
							//seleccionar dia adecuado
							//click en buscar por que si no no jala
							
							//buscar muchas veces por si marca error de lentitud la pagina del sat >(
							while (true)
							{
								browser.Button("ctl00_MainContent_BtnBusqueda").Click();
								Thread.Sleep(3000);

								if (browser.ContainsText("lentitud"))
								{
									browser.Link("closeBtn").Click();
								}
								else
								{
									break;
								}
							}

							Thread.Sleep(1000);
							primeraVez = false;
						}

						browser.SelectList("ctl00_MainContent_CldFecha_DdlDia").SelectByValue(mesActual.Day.ToString("00"));
						Thread.Sleep(1000);

						//buscar muchas veces por si marca error de lentitud la pagina del sat >(
						while (true)
						{
							browser.Button("ctl00_MainContent_BtnBusqueda").Click();
							Thread.Sleep(3000);

							if (browser.ContainsText("lentitud"))
							{
								browser.Link("closeBtn").Click();
							}
							else
							{
								break;
							}
						}

						DescargarFacturasListadas(browser, carpeta);

						//pasar al siguiente mes
						mesActual = mesActual.AddDays(1);
					}
				}

				browser.Link("ctl00_LnkBtnCierraSesion").Click();
				Thread.Sleep(2000);
				browser.Close();
			}
		}
Esempio n. 31
0
 static void Main(string[] args)
 {
     //Делаем компилятор счастливым
     string username = "";
     System.Console.WriteLine("OZWar Bot v1.0");
     System.Console.WriteLine("Инициализация IE...");
     //Инициализация ватина
     WatiN.Core.IE ieb = new IE("http://ozwar.ru/forum/index.php?app=core&module=global&section=login");
     ieb.Visible = false;
     int ii = 0;
     while (ii == 0)
     {
         System.Console.WriteLine("Авторизация...");
         ieb.WaitForComplete();
         //Вводим данные
         System.Console.WriteLine("Введите имя пользователя:");
         username = System.Console.ReadLine();
         System.Console.WriteLine("Введите пароль:");
         string password = System.Console.ReadLine();
         ieb.TextField(WatiN.Core.Find.ByName("ips_username")).TypeText(username);
         ieb.TextField(WatiN.Core.Find.ByName("ips_password")).TypeText(password);
         ieb.Button(WatiN.Core.Find.ByClass("input_submit")).Click();
         ieb.WaitForComplete();
         if (ieb.Link(WatiN.Core.Find.ByTitle(username)).Exists)
         {
             ii = 1;
         }
     }
     //Смотрим баланс
     ieb.GoTo(ieb.Link(WatiN.Core.Find.ByTitle(username)).Url);
     ieb.WaitForComplete();
     System.Console.WriteLine("Баланс: " + ieb.Span(WatiN.Core.Find.ByClass("fc")).Text.ToString());
     System.Console.WriteLine("Грузим ссылки...");
     //Грузим ссылки
     var ar1 = new List<string>();
     System.IO.StreamReader file = new System.IO.StreamReader(@"c:\list.txt");
     string line;
     while ((line = file.ReadLine()) != null)
     {
         ar1.Add(line);
     }
     //Грузим фразы
     System.Console.WriteLine("Грузим фразы...");
     var ar2 = new List<string>();
     System.IO.StreamReader file2 = new System.IO.StreamReader(@"c:\phrases.txt");
     string line2 = "";
     while ((line2 = file2.ReadLine()) != null)
     {
         ar2.Add(line2);
     }
     int co = 0;
     while (co < ar1.Count)
     {
         ieb.GoTo(ar1[co]);
         ieb.WaitForComplete();
         if (!ieb.Link(WatiN.Core.Find.ByTitle("Изменить")).Exists)
         {
             System.Console.WriteLine("Текущая ссылка: " + ar1[co]);
             int rnd = RandomInt(0, ar2.Count);
             System.Console.WriteLine("Пишем");
             ieb.TextField(WatiN.Core.Find.ByName("Post")).TypeTextQuickly(ar2[rnd] + "[color=#222222]Эта информация тут только для дебага, цыц, вы этого не видели. Не, ну серьёзно. Ну, а раз видели, значит её сейчас, к сожалению, сейчас не станет. Это сообщение отправлено ботом OreNew, пожалуйста, не читайте его.[/color]");
             ieb.Form(WatiN.Core.Find.ById("ips_fastReplyForm")).Submit();
             ieb.WaitForComplete();
             ieb.GoTo(ieb.Link(WatiN.Core.Find.ByTitle("Изменить")).Url);
             ieb.WaitForComplete();
             ieb.TextField(WatiN.Core.Find.ByName("Post")).TypeText(ar2[rnd]);
             ieb.Form(WatiN.Core.Find.ById("postingform")).Submit();
             System.Console.WriteLine("Выполнено");
             ieb.GoTo("http://ozwar.ru/forum/index.php?/user/609-benderfromfuture/");
             ieb.WaitForComplete();
             System.Console.WriteLine("Баланс: " + ieb.Span(WatiN.Core.Find.ByClass("fc")).Text.ToString());
             co++;
         }
         else
         {
             System.Console.WriteLine("Найдены следы нас!");
             co++;
         }
         System.Console.WriteLine("Ссылки кончились, бот завершил свою работу");
         ieb.Link(WatiN.Core.Find.ByTitle("Выход")).Click();
         System.Console.WriteLine("Выход из профиля...");
         System.Console.ReadLine();
     }
 }
Esempio n. 32
-1
        public string PassportCheck()
        {
            string strreturn = "";
            using (var browser = new IE("https://www.world-check.com/portal/mod_perl/Login/"))
            {
                if (Find.ByName("username"))
                {
                    browser.TextField(Find.ByName("username")).TypeText("nzrbrt0002");
                    browser.TextField(Find.ByName("password")).TypeText("Go8ahE5s");
                    browser.Image(Find.ByName("submitted")).Click();
                }

                browser.GoTo("https://www.world-check.com/portal/mod_perl/PassportCheck");

                browser.TextField(Find.ByName("givenName")).TypeText("Jim");
                browser.TextField(Find.ByName("lastName")).TypeText("Smith");
                browser.RadioButton(Find.ByName("sexg") && Find.ByValue("M")).Click();
                browser.Span(Find.ById("issuingState-CAN")).Click();
                browser.TextField(Find.ByName("dateOfBirthDay")).TypeText("29");
                browser.TextField(Find.ByName("dateOfBirthMonth")).TypeText("05");
                browser.TextField(Find.ByName("dateOfBirthYear")).TypeText("1978");
                browser.TextField(Find.ByName("passportNumber")).TypeText("WL745488");
                browser.TextField(Find.ByName("expireDateDay")).TypeText("10");
                browser.TextField(Find.ByName("expireDateMonth")).TypeText("07");
                browser.TextField(Find.ByName("expireDateYear")).TypeText("2014");
                browser.Button(Find.ByValue("VERIFY")).Click();

                var element = browser.Element(Find.ByClass("tablelinespacer"));
                var firsttd = element.NextSibling.NextSibling;
                strreturn = firsttd.Text.Replace("Lower Line:","");
                //Assert.IsTrue(browser.ContainsText("WatiN"));
            }
            return strreturn;
        }
Esempio n. 33
-2
 public void Purge(IE ie)
 {
     var trash = ie.Page<Trash>();
     ie.GoTo(trash.Url);
     ie.WaitForComplete();
     trash.PurgeAll.Click();
 }