/// <summary>
        /// Finds an element using the element name.
        /// </summary>
        /// <param name="driver">The <see cref="IWebDriver"/> to use in finding the element.</param>
        /// <param name="use">The locator string to use.</param>
        /// <returns>An <see cref="IWebElement"/> that matches the locator string.</returns>
        public IWebElement Find(OpenQA.Selenium.IWebDriver driver, string use)
        {
            string[] parts = use.Split(new char[] { ' ' });

            ReadOnlyCollection<IWebElement> allElements = driver.FindElements(By.Name(parts[0]));
            IList<IWebElement> filteredElements = new List<IWebElement>(allElements);

            for (int i = 1; i < parts.Length; i++)
            {
                IFilterFunction filterBy = this.GetFilterFunction(parts[i]);

                if (filterBy == null)
                {
                    throw new SeleniumException(use + " not found. Cannot find filter for: " + parts[i]);
                }

                string filterValue = this.GetFilterValue(parts[i]);
                filteredElements = filterBy.FilterElements(allElements, filterValue);
            }

            if (filteredElements != null && filteredElements.Count > 0)
            {
                return filteredElements[0];
            }

            throw new SeleniumException(use + " not found");
        }
Beispiel #2
0
        private static DataSet BillInfo(ref List<string> q, ref List<string> d, ref List<string> e, ref List<string> sd, ref List<string> st, ref List<string> name, ref List<string> kw)
        {
            //creates a dataset
            DataSet ds = new DataSet();

            //create a excel sheet called Bill Info
            DataTable dt1 = new DataTable("Bill Info");

            //create a columns with names listed below
            dt1.Columns.Add("Record", Type.GetType("System.Decimal"));
            dt1.Columns.Add("Quotation Number", Type.GetType("System.String"));
            dt1.Columns.Add("Description", Type.GetType("System.String"));
            dt1.Columns.Add("Entity Name", Type.GetType("System.String"));
            dt1.Columns.Add("Submission Date", Type.GetType("System.String"));
            dt1.Columns.Add("Submission Time", Type.GetType("System.String"));
            dt1.Columns.Add("Username", Type.GetType("System.String"));
            dt1.Columns.Add("Keyword", Type.GetType("System.String"));

            //adding rows of record that is extracted
            for (int i = 0; i < q.Count; i++)
            {
                dt1.Rows.Add(new object[] { i + 1, q[i], d[i], e[i], sd[i], st[i], name[i], kw[i] });
            }

            //adds every rows and columns to the excel sheet
            ds.Tables.Add(dt1);

            //return dataset
            return ds;
        }
Beispiel #3
0
 internal WebElements(RemoteSession session, List rawElements)
     : base(rawElements.Count) {
     _count = _items.Length;
     for (int i = 0; i < _count; i++) {
         _items[i] = new WebElement(session, (Dictionary)rawElements[i]);
     }
 }
Beispiel #4
0
 internal Cookies(RemoteSession session, List rawCookies) :
     base(rawCookies.Count) {
     _count = _items.Length;
     for (int i = 0; i < _count; i++) {
         _items[i] = new Cookie(session, (Dictionary)rawCookies[i]);
     }
 }
Beispiel #5
0
 public WindowContext(RemoteSession session)
     : base() {
     _session = session;
     _currentWindow = new Window(session, this, null);
     _previousWindow = _currentWindow;
     _cachedWindows = new List(10);
     _cachedWindows.Add(_currentWindow);
 }
Beispiel #6
0
 internal void Add(RemoteSession session, List rawElements) {
     int count = rawElements.Count;
     int size = _count + count;
     if (size > _items.Length)
         IncreaseSize(size);
     for (int i = 0; i < count; i++) {
         _items[_count++] = new WebElement(session, (Dictionary)rawElements[i]);
     }
 }
Beispiel #7
0
 public Village(string VillageID, string VillageName, string X, string Y)
 {
     this.Buildings = new List<Building>();
     this.resources = new List<Building>();
     this.villageID = VillageID;
     this.villageName = VillageName;
     this.url = Account.url;
     this.driver = Account.driver;
     this.x = X;
     this.y = Y;
 }
Beispiel #8
0
        public static void ExportData(string targetFilename, ref List<string> q, ref List<string> d, ref List<string> e, ref List<string> sd, ref List<string> st, ref List<string> name, ref List<string> kw)
        {
            //  Step 1: Create a DataSet, and put some sample data in it
            DataSet ds = BillInfo(ref q, ref d, ref e, ref sd, ref st, ref name, ref kw);

            //  Step 2: Create the Excel file
            try
            {
                CreateExcelFile.CreateExcelDocument(ds, targetFilename);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Couldn't create Excel file.\r\nException: " + ex.Message);
                return;
            }
        }
Beispiel #9
0
        public void Manipulate()
        {
            ChromeDriver driver = new ChromeDriver();
            HelpFunctions H = new HelpFunctions();

             H.Navigate("http://us14.chatzy.com/37785015405504", driver);
            H.Navigate("http://us14.chatzy.com", driver);
            driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 100));
            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
            IWebElement element = null;
               //= wait.Until(ExpectedConditions.ElementIsVisible(By.ClassName("X967")));

            H.Button("//*[@id='X313']", driver);//Login/SignUp
            driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30));
            element = wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//*[@id='X603']")));

            H.InputInfo("//*[@id='X603']", "*****@*****.**", driver);//add email
            driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30));

            H.Button("//*[@id='X6001']", driver); // choose the "I am regitered user"
            driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30));

            H.InputInfo("//*[@id='X604']", "Amber001", driver); //Enter in the password
            driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30));

            H.Button("//*[@id='X593']", driver); //click the ok button

            element = wait.Until(ExpectedConditions.ElementIsVisible(By.ClassName("X967")));
            H.Navigate("http://us14.chatzy.com/37785015405504", driver);

            H.Button("//*[@id='X593']", driver); //click the enter room button
            H.Button("//*[@id='X1049']", driver);

            var chat = driver.FindElementById("X184");
               // System.Collections.ObjectModel.ReadOnlyCollection<IWebElement> chat = driver.FindElementsByClassName("a");
               // chat.ToString();

            List<string> Temp = new List<string>();
            Temp.Add(chat.Text);
            System.IO.File.AppendAllLines(@"OUTPUT3.txt", Temp);
            string[] t = System.IO.File.ReadAllLines(@"OUTPUT3.txt");
            t.ToList();

             //   string s = chat.Text;
            //    string[] words = Regex.Split(s, "\r\n");
            driver.Close();
        }
Beispiel #10
0
 public void ListWindows(out List windows, out List handles) {
     handles = WindowContext.GetWindowsHandles(_session);
     windows = new List(handles.Count);
     foreach (string handle in handles) {
         int hash = handle.GetHashCode();
         foreach (Window win in _cachedWindows) {
             if (win.GetHashCode() == hash && handle == win.Handle) {
                 windows.Add(win);
                 goto nextHandle;
             }
         }
         windows.Add(new Window(_session, this, handle));
     nextHandle:
         continue;
     }
     _cachedWindows = windows;
 }
Beispiel #11
0
 static void LoadFile(ref List<string> l, ref Dictionary<string,string> dict)
 {
     try
     {
         //declare variable
         string line;
         List<string> listStrLineElements = new List<string>();
         //calling steamreader and reading the numbers from Numbers.txt
         using (StreamReader sr = new StreamReader("Keywords.txt"))
         {
             while ((line = sr.ReadLine()) != null)
             {
                 if (line == null)
                 {
                     break;
                 }
                 #region Split into name and keywords from the input file
                 listStrLineElements = line.Split(',').ToList();
                 for (int i = 0; i < listStrLineElements.Count; i++)
                 {
                     switch (i)
                     {
                         case 0:
                             l.Add(listStrLineElements[i]);
                             break;
                         case 1:
                             dict.Add(listStrLineElements[(i-1)], listStrLineElements[i]);
                             break;
                         default:
                             break;
                     }
                 }
                 #endregion
             }
         }
     }
     catch (Exception LoadFile)
     {
         MessageBox.Show("Load File Error: " + LoadFile.Message);
     }
 }
Beispiel #12
0
        static void Main(string[] args)
        {
            //Declaration
                //l = phone numbers, quotation number, desc of the records, entity, submission date , submission time, name of user
                List<string> l = new List<string>();
                List<string> quotation = new List<string>();
                List<string> desc = new List<string>();
                List<string> entity = new List<string>();
                List<string> subDate = new List<string>();
                List<string> subTime = new List<string>();
                List<string> name = new List<string>();
                List<string> kw = new List<string>();
                Dictionary<string, string> dict = new Dictionary<string, string>();
                int numbrecords = 0;
                string filename = "";

                #region Load google chrome
                // Initialize the Chrome Driver
                using (var driver = new ChromeDriver())
                {
                    LoadFile(ref l, ref dict);

                    // Go to the home page
                    driver.Navigate().GoToUrl("http://www.gebiz.gov.sg/scripts/main.do?sourceLocation=openarea&select=tenderId");

                    #region autofill and extract data from GeBiz webpage
                    foreach (var val in l)
                    {
                        //Get the page elements

                        var fromdate = driver.FindElementByXPath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/form/table[2]/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr[5]/td[4]/input");
                        var todate = driver.FindElementByXPath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/form/table[2]/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr[5]/td[6]/input");
                        var keyword = driver.FindElementByName("searchByDesc");
                        new SelectElement(driver.FindElement(By.Name("dateType"))).SelectByIndex(1);
                        var submitbutton = driver.FindElementByName("submitAction");

                        fromdate.SendKeys(DateTime.Now.AddDays(-1).ToString("dd/MM/yyyy"));
                        todate.SendKeys(DateTime.Now.AddDays(-1).ToString("dd/MM/yyyy"));

                        keyword.SendKeys(val);

                        //click the submit button
                        submitbutton.Click();

                        if (driver.FindElements(By.XPath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/form/table[3]/tbody/tr/td/table[1]/tbody/tr[2]/td")).Count == 1)
                        {
                            driver.Navigate().GoToUrl("http://www.gebiz.gov.sg/scripts/main.do?sourceLocation=openarea&select=tenderId");
                        }
                        else
                        {

                            if (driver.FindElementByXPath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/form/table[3]/tbody/tr/td/table[1]/tbody/tr[2]/td").Text.Equals("No data found"))
                            {
                                Console.WriteLine("No Data Found");
                                driver.Navigate().GoToUrl("http://www.gebiz.gov.sg/scripts/main.do?sourceLocation=openarea&select=tenderId");
                            }
                            else
                            {
                                #region Checking the number of records
                                for (int j = 11; j > 1; j--)
                                {
                                    //select the records by row
                                    if (driver.FindElements(By.XPath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/form/table[3]/tbody/tr/td/table[1]/tbody/tr[" + j + "]")).Count == 1)
                                    {
                                        Console.WriteLine(driver.FindElementByXPath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/form/table[3]/tbody/tr/td/table[1]/tbody/tr[2]/td").Text);
                                        numbrecords = j + 1;
                                        #region Storing quotation and desc to list
                                        for (int i = 2; i < numbrecords; i++)
                                        {
                                            //get the record from the current row on the quotation col
                                            quotation.Add(driver.FindElementByXPath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/form/table[3]/tbody/tr/td/table[1]/tbody/tr[" + i + "]/td[2]/table/tbody/tr[1]/td/a/b").Text);
                                            //get the record from the current row on the description col
                                            desc.Add(driver.FindElementByXPath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/form/table[3]/tbody/tr/td/table[1]/tbody/tr[" + i + "]/td[3]/table/tbody/tr[1]/td").Text);
                                            //get the record from the current row on entity from description col
                                            entity.Add(RemoveWord(driver.FindElementByXPath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/form/table[3]/tbody/tr/td/table[1]/tbody/tr[" + i + "]/td[3]/table/tbody/tr[2]/td").Text));
                                            //get the record from the current row on submission date from closing date/time col
                                            subDate.Add(driver.FindElementByXPath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/form/table[3]/tbody/tr/td/table[1]/tbody/tr[" + i + "]/td[5]/table/tbody/tr[1]/td").Text);
                                            //get the record from the current row on submission time from closing date/time col
                                            subTime.Add(driver.FindElementByXPath("/html/body/table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td/form/table[3]/tbody/tr/td/table[1]/tbody/tr[" + i + "]/td[5]/table/tbody/tr[2]/td").Text);
                                            //add the name of the organisation that the keyword belong to
                                            name.Add(dict[val]);
                                            //add the keyword
                                            kw.Add(val);
                                        }
                                        driver.Navigate().GoToUrl("http://www.gebiz.gov.sg/scripts/main.do?sourceLocation=openarea&select=tenderId");
                                        break;
                                        #endregion
                                    }
                                }
                                #endregion
                            }
                        }
                    }
                    #endregion
                }
                #endregion
                //saving to excel file
                filename = SaveExcel();

                ExportData(filename, ref quotation, ref desc, ref entity, ref subDate, ref subTime, ref name, ref kw);
        }
Beispiel #13
0
 internal Actions(RemoteSession session) {
     _session = session;
     _mouse = session.mouse;
     _keyboard = session.keyboard;
     _actions = new List<Action>();
 }
Beispiel #14
0
 internal WebElements(List webElements)
     : base(webElements.Values()) {
 }
Beispiel #15
0
        static void Main(string[] args)
        {
            HtmlDocument doc = new HtmlDocument();
            List<string> list = new List<string>();
            HashSet<string> listposters = new HashSet<string>();
            int forumNumber = 0;
            string forumAddress = "";
            //List<string> list = new List<string>();
            ISelenium sel = new DefaultSelenium("localhost", 4444, "*chrome", forumAddress);
            sel.Start();
            sel.WindowMaximize();
            sel.Open("/");
            sel.Click("id=loginlink");
            sel.WaitForPageToLoad("30000");
            sel.Type("id=username", "");
            sel.Type("id=password", "");
            sel.Click("id=submit");
            sel.WaitForPageToLoad("30000");


            for (int y = 1; y < 14; y++)
            {
                sel.Open(string.Format("/vbulletin/forumdisplay.php?f=" + forumNumber + "&order=desc&page={0}", y));
                sel.WaitForPageToLoad("30000");

                var src = sel.GetHtmlSource();

                doc.LoadHtml(src);

                var links = doc.DocumentNode.SelectNodes("//a[@href]");

                var posters = from i in links
                              where i.OuterHtml.Contains("whoposted")
                              select i;

                var ln = from o in posters
                         select o.OuterHtml.ToString();

                foreach (var item in ln)
                {
                    LinkItem i = new LinkItem();


                    Match m2 = Regex.Match(item, @"href=\""(.*?)\""",
                    RegexOptions.Singleline);
                    if (m2.Success)
                    {
                        i.Href = m2.Groups[1].Value;
                    }

                    list.Add(i.Href.Replace("&amp;", "&"));
                }

            }

            foreach (var it in list)
            {
                sel.Open(string.Format("vbulletin/{0}", it));
                sel.WaitForPageToLoad("30000");

                var src = sel.GetHtmlSource();

                doc.LoadHtml(src);

                var links = doc.DocumentNode.SelectNodes("//a[@href]");

                var posters = from i in links
                              where i.OuterHtml.Contains("member")
                              select i;

                var ln = from o in posters
                         select o.InnerHtml.ToString();

                foreach (var item in ln)
                {
                    listposters.Add(item);
                }
            }


            sel.Close();



            //var links = doc.DocumentNode.SelectNodes("//a[@href]");
            //var links2 = doc.DocumentNode.G
            //var posters = from i in links
            //              where i.OuterHtml.Contains("lastposter")
            //              select i;

            //var link = from o in posters
            //           select o.OuterHtml;

            System.IO.File.WriteAllLines(@"C:\Users\William\Documents\CsharpRandom\SeleniumTest\AllPosters.txt", listposters);

            Console.Read();
        }
Beispiel #16
0
        public static void Start()
        {
            Account.driver = new FirefoxDriver();

            Account.Login(Account.username, Account.password);
            // Start village creation
            Account.villages = new List<Village>();

            Account.driver.Navigate().GoToUrl(Account.url + "dorf1.php");

            try
            {
                TimeSpan timespan = TimeSpan.FromSeconds(2);
                WebDriverWait wait = new WebDriverWait(Account.driver, timespan);
                wait.Until(ExpectedConditions.ElementIsVisible(By.Id("sidebarBoxVillagelist")));
                Account.driver.FindElement(By.Id("sidebarBoxVillagelist")).FindElement(By.ClassName("addHoverClick")).Click();
                ReadOnlyCollection<IWebElement> villageElements = Account.driver.FindElement(By.Id("sidebarBoxVillagelist")).FindElement(By.ClassName("sidebarBoxInnerBox")).FindElements(By.TagName("li"));

                string name;
                string id;
                string x;
                string y;
                int count = 0;
                foreach (IWebElement village in villageElements)
                {

                    // Parse name and id
                    name = Account.driver.FindElement(By.Id("sidebarBoxVillagelist")).FindElement(By.ClassName("sidebarBoxInnerBox")).FindElements(By.TagName("li"))[count].FindElement(By.ClassName("name")).Text;
                    id = Account.driver.FindElement(By.Id("sidebarBoxVillagelist")).FindElement(By.ClassName("sidebarBoxInnerBox")).FindElements(By.TagName("li"))[count].FindElement(By.TagName("a")).GetAttribute("href");
                    id = id.Replace("&", "").Split('=')[1];

                    //Parse X

                    x = Account.driver.FindElement(By.Id("sidebarBoxVillagelist")).FindElement(By.ClassName("sidebarBoxInnerBox")).FindElements(By.TagName("li"))[count].FindElement(By.ClassName("coordinateX")).Text;

                    x = x.Replace("(", "");
                    bool negative = x.Contains('-');

                    x = new string(x.Where(c => char.IsDigit(c)).ToArray());
                    if (negative) {
                        x = "-" + x;
                    }

                    //Parse Y
                    y = Account.driver.FindElement(By.Id("sidebarBoxVillagelist")).FindElement(By.ClassName("sidebarBoxInnerBox")).FindElements(By.TagName("li"))[count].FindElement(By.ClassName("coordinateY")).Text;

                    y = y.Replace(")", "");
                    negative = y.Contains('-');
                    y = new string(y.Where(c => char.IsDigit(c)).ToArray());
                    if (negative) {
                        y = "-" + y;
                    }

                    Village vil = new Village(id, name, x, y);
                    vil.setNoOfResources();
                    vil.setBuildingsData();
                    vil.setProductionPH();
                    vil.setResourcesData();
                    vil.setWareGranCapacity();
                    villages.Add(vil);
                    count++;
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBoxResult result = System.Windows.MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// Wait for 'idleTimeMS' seconds of HTTP idle time (no request being processed
        /// for 3 seconds) or a 'timeout second timeout.
        /// Returns 'true' if no items were downloaded for 'idleTimeMS' seconds. 
        /// Returns 'false' if the timeout occurs.
        /// </summary>
        /// <param name="session">The list of sessions to test (passed by reference).</param>
        /// <param name="idleTimeMS">The HTTP traffic idle time in milliseconds to wait.</param>
        /// <param name="timeoutMS">The fallback timeout in milliseconds.</param>
        private static bool WaitHttpIdle(List<Fiddler.Session> sessions, int idleTimeMS, int timeoutMS)
        {
            DateTime beginWait = DateTime.Now;
            DateTime lastTrafficTime = beginWait;
            while ((DateTime.Now - beginWait).TotalMilliseconds < timeoutMS)
            {
                Monitor.Enter(sessions);
                for (int i = sessions.Count - 1; i > -1; i--)
                {
                    Session s = sessions[i];

                    if (s.state == SessionStates.Done ||
                        s.state == SessionStates.Aborted) {
                        sessions.RemoveAt(i);
                        lastTrafficTime = DateTime.Now;
                    }

                    // You also may want to ignore certain URLs
                }
                Monitor.Exit(sessions);
                if ((DateTime.Now - lastTrafficTime).TotalMilliseconds > idleTimeMS)
                {
                    return true;
                }
                Thread.Sleep(100);
            }
            return false;
        }
 /// <summary>
 /// Private constructor to remove ability for class to be instantiated
 /// </summary>
 SeleniumSupport(SeleniumServer seleniumServer)
 {
     this.Server = seleniumServer;
     _disposed = false;
     Instances = new List<ISelenium>();
 }
Beispiel #19
0
 internal TouchActions(RemoteSession session, TouchScreen screen) {
     _session = session;
     _screen = screen;
     _actions = new List<Action>();
 }
        static void Main(string[] args)
        {
            try
            {
                string baseUrl = "http://www.webmetrics.com";
                if (args.Length >= 1)
                {
                    baseUrl = args[0];
                }

                string filename;
                if (args.Length >= 2)
                {
                    filename = args[1];
                }
                else
                {
                    Uri uri = new Uri(baseUrl);
                    filename = uri.Host.Replace(".", "-") + @".har";
                }

                // Uncomment to enable SSL support
                // Fiddler.CONFIG.IgnoreServerCertErrors = true;
                // FiddlerApplication.Prefs.SetBoolPref("fiddler.network.streaming.abortifclientaborts", true);

                // Varibale to store the list of items downloaded
                var sessions = new List<Fiddler.Session>();

                // As each HTTP item is downloaded add it to our list.
                // We will export this list later.
                Fiddler.FiddlerApplication.AfterSessionComplete += delegate(Fiddler.Session oS)
                {
                    Monitor.Enter(sessions);
                    sessions.Add(oS);
                    Monitor.Exit(sessions);
                };

                // As each HTTP item is downloaded add it to our list.
                // We will export this list later.
                Fiddler.FiddlerApplication.BeforeRequest += delegate(Fiddler.Session oS)
                {
                    if (!new Regex(baseUrl).IsMatch(oS.fullUrl))
                    {
                        oS.utilCreateResponseAndBypassServer();
                        oS.responseCode = 200;
                    }
                };

                // Start Fiddler on port 8877.
                // Register as the system wide proxy.
                Fiddler.FiddlerApplication.Startup(8877, FiddlerCoreStartupFlags.Default);

                /////////////////////////////////////////////////
                // Begin selenium test
                /////////////////////////////////////////////////

                var webDriver = new OpenQA.Selenium.Firefox.FirefoxDriver();
                var selenium = new Selenium.WebDriverBackedSelenium(webDriver, baseUrl);

                selenium.Start();
                selenium.Open(baseUrl);
                selenium.WaitForPageToLoad("30000");
                selenium.Stop();

                /////////////////////////////////////////////////
                // End selenium test
                /////////////////////////////////////////////////

                // Load the HAR file exporter (this only has to be done once per process).
                // The following DLL was downloaded from:
                // https://www.fiddler2.com/dl/FiddlerCore-BasicFormats.zip
                // It is currently only loadable with FiddlerCode 2.2.9.9.
                String path = Path.Combine(Path.GetDirectoryName
                    (Assembly.GetExecutingAssembly().Location), @"FiddlerCore-BasicFormats.dll");
                FiddlerApplication.oTranscoders.ImportTranscoders(path);

                // Export fiddler sessions to HAR file
                Monitor.Enter(sessions);
                var oExportOptions = new Dictionary<string, object>();
                oExportOptions.Add("Filename", filename);
                bool fiddler = Fiddler.FiddlerApplication.DoExport("HTTPArchive v1.2", sessions.ToArray(), oExportOptions, null);
                sessions.Clear();
                Monitor.Exit(sessions);
            }
            finally
            {
                // Shutdown fiddler, this removes Fiddler as the system proxy.
                Fiddler.FiddlerApplication.Shutdown();
                Thread.Sleep(500);
            }
        }
Beispiel #21
0
 /// <summary>
 /// Returns a list containing the text for each element
 /// </summary>
 /// <param name="offsetStart"></param>
 /// <param name="offsetEnd"></param>
 /// <param name="trim"></param>
 /// <returns></returns>
 public List Text(int offsetStart = 0, int offsetEnd = 0, bool trim = true) {
     int size = base.Count;
     int imax = size + offsetEnd - 1;
     int imin = offsetStart;
     List lst = new List(size - offsetStart + offsetEnd);
     int i = -1;
     foreach (WebElement ele in this) {
         if (++i < imin || i > imax)
             continue;
         var text = ele.Text();
         if (trim) {
             lst.Add(text.Trim());
         } else {
             lst.Add(text);
         }
     }
     return lst;
 }
        static void Main(string[] args)
        {
            try
            {
                string baseUrl = "http://www.amazon.com/";
                if (args.Length >= 1)
                {
                    baseUrl = args[0];
                }

                string filename;
                if (args.Length >= 2)
                {
                    filename = args[1];
                }
                else
                {
                    Uri uri = new Uri(baseUrl);
                    filename = uri.Host.Replace(".", "-") + @".har";
                }

                // Uncomment to enable SSL support
                // Fiddler.CONFIG.IgnoreServerCertErrors = true;
                // FiddlerApplication.Prefs.SetBoolPref("fiddler.network.streaming.abortifclientaborts", true);

                // Varibale to store the list of items downloaded
                var sessions = new List<Fiddler.Session>();
                var newSessions = new List<Fiddler.Session>();
                int browserProcessId = -1;

                // As each HTTP item is downloaded add it to our list.
                // We will export this list later.
                Fiddler.FiddlerApplication.AfterSessionComplete += delegate(Fiddler.Session oS)
                {
                    Monitor.Enter(sessions);
                    // Only record HTTP traffic by our browser process
                    if (browserProcessId == oS.LocalProcessID)
                    {
                        sessions.Add(oS);
                    }
                    Monitor.Exit(sessions);
                };

                Fiddler.FiddlerApplication.BeforeRequest += delegate(Fiddler.Session oS)
                {
                    // Record the process id for the first URL we go to,
                    // this is the browser that we lanched with Selenium
                    // Could also do extra verification here, for example
                    // check that it is a child process, of this process.
                    // That requires some heavy Win32 API usage, so I've
                    // skipped it here.
                    if (browserProcessId == -1 && oS.fullUrl == baseUrl)
                    {
                        browserProcessId = oS.LocalProcessID;
                    }

                    // Only record HTTP traffic by our browser process
                    if (browserProcessId == oS.LocalProcessID)
                    {
                        Monitor.Enter(newSessions);
                        newSessions.Add(oS);
                        Monitor.Exit(newSessions);
                    }
                };

                // Start Fiddler on port 8877.
                // Register as the system wide proxy.
                Fiddler.FiddlerApplication.Startup(8877, FiddlerCoreStartupFlags.Default);

                /////////////////////////////////////////////////
                // Begin selenium test
                /////////////////////////////////////////////////

                var webDriver = new OpenQA.Selenium.Firefox.FirefoxDriver();
                var selenium = new Selenium.WebDriverBackedSelenium(webDriver, baseUrl);

                selenium.Start();
                selenium.Open(baseUrl);

                // Wait until 3 seconds of HTTP idle (no request being processed for 3 seconds)
                // or a 30 second timeout.
                // 'result' will be false if items are still being downloaded when the timeout
                // occurs.
                bool result = WaitHttpIdle(sessions, 3000, 30000);
                selenium.Stop();

                /////////////////////////////////////////////////
                // End selenium test
                /////////////////////////////////////////////////

                // Load the HAR file exporter (this only has to be done once per process).
                // The following DLL was downloaded from:
                // https://www.fiddler2.com/dl/FiddlerCore-BasicFormats.zip
                // It is currently only loadable with FiddlerCode 2.2.9.9.
                String path = Path.Combine(Path.GetDirectoryName
                    (Assembly.GetExecutingAssembly().Location), @"FiddlerCore-BasicFormats.dll");
                FiddlerApplication.oTranscoders.ImportTranscoders(path);

                // Export fiddler sessions to HAR file
                Monitor.Enter(sessions);
                var oExportOptions = new Dictionary<string, object>();
                oExportOptions.Add("Filename", filename);
                bool fiddler = Fiddler.FiddlerApplication.DoExport("HTTPArchive v1.2", sessions.ToArray(), oExportOptions, null);
                sessions.Clear();
                Monitor.Exit(sessions);
            }
            finally
            {
                // Shutdown fiddler, this removes Fiddler as the system proxy.
                Fiddler.FiddlerApplication.Shutdown();
                Thread.Sleep(500);
            }
        }
Beispiel #23
0
 /// <summary>
 /// Returns a list containing the text parsed to a number for each element
 /// </summary>
 /// <param name="defaultValue">Default value in case the text can't be parsed.</param>
 /// <param name="offsetStart"></param>
 /// <param name="offsetEnd"></param>
 /// <returns></returns>
 public List Values(object defaultValue = null, int offsetStart = 0, int offsetEnd = 0) {
     int size = base.Count;
     int imin = offsetStart;
     int imax = size - 1 + offsetEnd;
     List lst = new List(size - offsetStart + offsetEnd);
     int i = -1;
     foreach (WebElement ele in this) {
         if (++i < imin || i > imax)
             continue;
         string text = ele.Text().Trim();
         double num;
         if (double.TryParse(text, out num)) {
             lst.Add(num);
         } else {
             lst.Add(defaultValue);
         }
     }
     return lst;
 }