コード例 #1
0
        /// <summary>
        /// Function Name :- FnDeSelectByIndex
        /// Created By :- Pankaj Kumar
        /// Date of Creation :- 11-Apr-2020
        /// </summary>
        public Boolean FnDeSelectByIndex(By elem, int index, string strDescription)
        {
            Boolean blnStatus = true;

            try
            {
                if (FnElementPresent(elem))
                {
                    try
                    {
                        SelectElement objSelect = new SelectElement(driver.FindElement(elem));
                        if (objSelect.Options.Count > 0)
                        {
                            try
                            {
                                objSelect.DeselectByIndex(index);
                                Reporter.Pass(strDescription + " : Element is De-Selected By Index : " + index);
                            }
                            catch (Exception e) { blnStatus = false; Reporter.Fail(strDescription + " : Element is not De-Selected By Index : " + index); }
                        }
                    }
                    catch (Exception e) { blnStatus = false; Reporter.Fail(strDescription + " : Element is not De-Selected By Index : " + index); }
                }
                else
                {
                    Reporter.Fail(strDescription + " : Element not displayed.");
                }
            }
            catch (Exception e) { blnStatus = false; Reporter.Fail(strDescription + " : Element is not De-Selected By Index : " + index); }
            return(blnStatus);
        }
コード例 #2
0
        public void TestMultipleSelection()
        {
            IWebDriver driver = new FirefoxDriver();

            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMinutes(3);

            driver.Url = "http://toolsqa.wpengine.com/automation-practice-form";

            SelectElement oSelection = new SelectElement(driver.FindElement(By.Name("selenium_commands")));

            oSelection.SelectByIndex(0);
            Thread.Sleep(2000);
            oSelection.DeselectByIndex(0);

            oSelection.SelectByText("Navigation Commands");
            Thread.Sleep(2000);
            oSelection.DeselectByText("Navigation Commands");

            IList <IWebElement> oSize = oSelection.Options;
            int iListSize             = oSize.Count;

            for (int i = 0; i < iListSize; i++)
            {
                String sValue = oSelection.Options.ElementAt(i).Text;
                Console.WriteLine("Value of the Item is : " + sValue);
                oSelection.SelectByIndex(i);
                Thread.Sleep(2000);
            }
            oSelection.DeselectAll();

            driver.Close();
        }
コード例 #3
0
        public void CanValidateMultiString_InitiallyBlank()
        {
            var paragraph = Browser.FindElement(By.Id("validate-multi-string-initially-blank"));
            var select    = new SelectElement(paragraph.FindElement(By.TagName("select")));

            WaitAssert.True(() => paragraph.ElementIsPresent(By.ClassName("invalid-feedback")));

            select.SelectByIndex(1);
            select.SelectByIndex(2);
            WaitAssert.False(() => paragraph.ElementIsPresent(By.ClassName("invalid-feedback")));

            select.DeselectByIndex(1);
            WaitAssert.False(() => paragraph.ElementIsPresent(By.ClassName("invalid-feedback")));

            select.DeselectByIndex(2);
            WaitAssert.True(() => paragraph.ElementIsPresent(By.ClassName("invalid-feedback")));

            select.SelectByIndex(0);
            WaitAssert.False(() => paragraph.ElementIsPresent(By.ClassName("invalid-feedback")));
        }
コード例 #4
0
        public void MultipleTest()
        {
            // Create a new instance of the Firefox driver
            IWebDriver driver = new ChromeDriver("D:\\SagarAutomation");

            //driver.Manage().Window.Maximize();
            // Launch the URL
            driver.Url = "http://toolsqa.com/automation-practice-form";

            driver.FindElement(By.Id("cookie_action_close_header")).Click();

            // Put an Implicit wait, this means that any search for elements on the page could take the time the implicit wait is set for before throwing exception
            //  driver.Manage().Timeouts().ImplicitWait(TimeSpan.FromSeconds(10));

            // Launch the URL
            //  driver.Url = "http://toolsqa.com/automation-practice-form";
            // Step 3: Select 'Selenium Commands' Multiple select box ( Use Name locator to identify the element )
            SelectElement oSelection = new SelectElement(driver.FindElement(By.Name("selenium_commands")));

            // Step 4: Select option 'Browser Commands'  and then deselect it (Use selectByIndex and deselectByIndex)
            oSelection.SelectByIndex(0);
            Thread.Sleep(2000);
            oSelection.DeselectByIndex(0);

            // Step 5: Select option 'Navigation Commands'  and then deselect it (Use selectByVisibleText and deselectByVisibleText)
            oSelection.SelectByText("Navigation Commands");
            Thread.Sleep(2000);

            oSelection.DeselectByText("Navigation Commands");

            // Step 6: Print and select all the options for the selected Multiple selection list.
            IList <IWebElement> oSize = oSelection.Options;
            int iListSize             = oSize.Count;

            // Setting up the loop to print all the options
            for (int i = 0; i < iListSize; i++)
            {
                // Storing the value of the option
                String sValue = oSelection.Options.ElementAt(i).Text;
                // Printing the stored value
                Console.WriteLine("Value of the Item is :" + sValue);
                // Selecting all the elements one by one
                oSelection.SelectByIndex(i);

                Thread.Sleep(2000);
            }

            // Step 7: Deselect all
            oSelection.DeselectAll();

            // Kill the browser
            driver.Close();
        }
コード例 #5
0
 /// <summary>
 /// Deselects a dropdown value based on the provided index.
 /// </summary>
 /// <param name="dropdownElement"></param>
 /// <param name="index"></param>
 public void DeselectDropdownValueByIndex(By dropdownElement, int index)
 {
     try
     {
         var select = new SelectElement(driver.FindElement(dropdownElement));
         select.DeselectByIndex(index);
     }
     catch (Exception e)
     {
         MyLogger.Log.Error($"Failed to de-select index: {index} from dropdown element: {dropdownElement}. {e.Message}");
         throw e;
     }
 }
        public void Exercise2()
        {
            //Get all option of Selenium commands multiple

            SelectElement selectOption = new SelectElement(driver.FindElement(By.Name("selenium_commands")));

            //Select option "Browser Commands" by index

            selectOption.SelectByIndex(0);

            Thread.Sleep(2000);

            //Deselect option "Browser Commands"

            selectOption.DeselectByIndex(0);

            //Select option "Navigation Commands"

            selectOption.SelectByIndex(1);

            Thread.Sleep(2000);

            //Deselect for option "Navigation Commands"

            selectOption.DeselectByIndex(1);

            //Print all options of selected multiple selection list

            for (int i = 0; i < selectOption.Options.Count; i++)
            {
                Console.WriteLine("The value of option at index " + i + " : " + selectOption.Options.ElementAt(i).Text);
            }


            //Deselect all options

            selectOption.DeselectAll();
        }
コード例 #7
0
ファイル: SelectTests.cs プロジェクト: nidhij6680/SELENIUM2
        public void TestMultipleSelectList()
        {
            //Get the List as a Select using it's name attribute
            SelectElement color = new SelectElement(driver.FindElement(By.Name("color")));

            //Verify List support multiple selection
            Assert.IsTrue(color.IsMultiple);

            //Verify List has five options for selection
            Assert.AreEqual(5, color.Options.Count);

            //Select multiple options in the list using visible text
            color.SelectByText("Black");
            color.SelectByText("Red");
            color.SelectByText("Silver");

            //Verify there 3 options selected in the list
            Assert.AreEqual(3, color.AllSelectedOptions.Count);

            //We will verify list has multiple options selected as listed in a array
            var exp_sel_options = new ArrayList(new String[] { "Black", "Red", "Silver" });
            var act_sel_options = new ArrayList();

            foreach (IWebElement option in color.AllSelectedOptions)
            {
                act_sel_options.Add(option.Text);
            }

            //Verify expected array for selected options match with actual options selected
            Assert.AreEqual(exp_sel_options.ToArray(), act_sel_options.ToArray());

            //Deselect an option using visible text
            color.DeselectByText("Silver");
            //Verify selected options count
            Assert.AreEqual(2, color.AllSelectedOptions.Count);

            //Deselect an option using value attribute of the option
            color.DeselectByValue("rd");
            //Verify selected options count
            Assert.AreEqual(1, color.AllSelectedOptions.Count);

            //Deselect an option using index of the option
            color.DeselectByIndex(0);
            //Verify selected options count
            Assert.AreEqual(0, color.AllSelectedOptions.Count);
        }
コード例 #8
0
        public void SelectFromDropDow()
        {
            var dropDown          = new SelectElement(element);
            var allSelectedOption = dropDown.AllSelectedOptions;
            var selectedOption    = dropDown.SelectedOption;
            var isMultiple        = dropDown.IsMultiple;
            var listOfAllOption   = dropDown.Options;
            var wrappedElement    = dropDown.WrappedElement;

            dropDown.DeselectAll();
            dropDown.DeselectByIndex(50);
            dropDown.DeselectByText("roma");
            dropDown.DeselectByValue("12345");
            dropDown.SelectByIndex(60);
            dropDown.SelectByText("Roma");
            dropDown.SelectByValue("hgfdsa");
        }
コード例 #9
0
        public void InputSelectHandlesHostileStringValues()
        {
            var appElement         = MountTypicalValidationComponent();
            var selectParagraph    = appElement.FindElement(By.ClassName("select-multiple-hostile"));
            var hostileSelectInput = new SelectElement(selectParagraph.FindElement(By.TagName("select")));
            var select             = hostileSelectInput.WrappedElement;
            var hostileSelectLabel = selectParagraph.FindElement(By.TagName("span"));

            // Check initial selection
            Browser.Equal(new[] { "\"", "{" }, () => hostileSelectInput.AllSelectedOptions.Select(o => o.Text));

            hostileSelectInput.DeselectByIndex(0);
            hostileSelectInput.SelectByIndex(2);

            // Bindings work from JS -> C#
            Browser.Equal("{,", () => hostileSelectLabel.Text);
        }
コード例 #10
0
        public void SelectWithMultipleAttributeCanBindValue()
        {
            var appElement = Browser.MountTestComponent <SelectVariantsComponent>();
            var select     = new SelectElement(appElement.FindElement(By.Id("select-cities")));

            // Assert that the binding works in the .NET -> JS direction
            Browser.Equal(new[] { "\"sf\"", "\"sea\"" }, () => select.AllSelectedOptions.Select(option => option.GetAttribute("value")));

            select.DeselectByIndex(0);
            select.SelectByIndex(1);
            select.SelectByIndex(2);

            var label = appElement.FindElement(By.Id("selected-cities-label"));

            // Assert that the binding works in the JS -> .NET direction
            Browser.Equal("\"la\", \"pdx\", \"sea\"", () => label.Text);
        }
コード例 #11
0
        /*This command deselects an already selected value using its index.*/
        public void DeselectByIndex(string xpath, int index)
        {
            IWebElement   element       = FindElement(xpath);
            SelectElement selectElement = SelectTheElement(element);

            IList <IWebElement> allSelectedOptions = selectElement.AllSelectedOptions;
            bool indexIsEnebled = allSelectedOptions[index].Enabled;

            if (indexIsEnebled)
            {
                selectElement.DeselectByIndex(index);
            }
            else
            {
                throw new System.InvalidOperationException($"The option №{index} is not selected");
            }
        }
コード例 #12
0
 //
 // Summary:
 //     Deselect the option by the index, as determined by the "index" attribute
 //     of the element.
 //
 // Parameters:
 //   index:
 //     The value of the index attribute of the option to deselect.
 public void DeselectByIndex(int index)
 {
     try
     {
         SelectElement.DeselectByIndex(index);
     }
     catch (StaleElementReferenceException e)
     {
         Logger.Info("Caught exception {0}. Attempting to re-initialize element", e.Message);
         InitializeElement();
         SelectElement.DeselectByIndex(index);
     }
     catch (Exception e)
     {
         Logger.Error(e);
         throw;
     }
 }
コード例 #13
0
        public void MultiSelect()
        {
            // Open automation practice form
            driver.Navigate().GoToUrl("http://toolsqa.com/automation-practice-form/");

            // Select 'Selenium Commands' Mulitplie selection box (Use Name locator to identify the element)
            SelectElement seleniumCommandsOptions = new SelectElement(driver.FindElement(By.Name("selenium_commands")));

            // Select option 'Browser Commands' and then deselect it (Use SelectByIndex and DeselectByIndex)
            seleniumCommandsOptions.SelectByIndex(0);
            Thread.Sleep(1000);
            seleniumCommandsOptions.DeselectByIndex(0);

            // Select option 'Navigation Commands' and then deselect it (Use SelectByText and DeselectByText)
            seleniumCommandsOptions.SelectByText("Navigation Commands");
            Thread.Sleep(1000);
            seleniumCommandsOptions.DeselectByText("Navigation Commands");

            // Print and select all the options for the selected Mulitple selection list.
            IList <IWebElement> seleniumCommandsOptionsSize = seleniumCommandsOptions.Options;
            int iListSeleniumCommandsOptionsSize            = seleniumCommandsOptionsSize.Count;

            for (int i = 0; i < iListSeleniumCommandsOptionsSize; i++)
            {
                // Storing the value of the option
                String sValue = seleniumCommandsOptions.Options.ElementAt(i).Text;

                // Printing the stored value
                Console.WriteLine(sValue);

                // Selecting all the elements one by one
                seleniumCommandsOptions.SelectByIndex(i);

                Thread.Sleep(2000);
            }

            // Deselect all options
            seleniumCommandsOptions.DeselectAll();
            Thread.Sleep(2000);

            // Close the browser
            driver.Quit();
        }
コード例 #14
0
            public bool ByIndex(params int[] deselIndexes)
            {
                SelectElement select = new SelectElement(this.element);

                int numberOfValues = deselIndexes.Count();

                try
                {
                    for (int i = 0; i <= numberOfValues; i++)
                    {
                        select.DeselectByIndex(deselIndexes[i]);
                    }

                    return(true);
                }
                catch (Exception)
                {
                    //// Normal behaviour
                }

                return(false);
            }
コード例 #15
0
        public void multiselectTest()
        {
            IWebDriver driver = new FirefoxDriver();

            driver.Url = "http://toolsqa.wpengine.com/automation-practice-form/";

            //make a new selectelement called sSelect at the multiselect box
            SelectElement sSelect = new SelectElement(driver.FindElement(By.Name("selenium_commands")));

            //select and then deselect something by index
            sSelect.SelectByIndex(0);
            Thread.Sleep(2000);
            sSelect.DeselectByIndex(0);
            Thread.Sleep(2000);

            //select and then deselect something else by text
            sSelect.SelectByText("Navigation Commands");
            Thread.Sleep(2000);
            sSelect.DeselectByText("Navigation Commands");
            Thread.Sleep(2000);

            //get options in multiselect into a list
            IList <IWebElement> sList = sSelect.Options;
            int sLength = sList.Count;

            //Print all the options in the multiselect
            for (int i = 0; i < sLength; i++)
            {
                String sValue = sList.ElementAt(i).Text;
                Console.WriteLine(sValue);

                //select all options
                sSelect.SelectByIndex(i);
            }
            sSelect.DeselectAll();
            Thread.Sleep(2000);

            driver.Close();
        }
コード例 #16
0
ファイル: Sequence.cs プロジェクト: Tolvic/selenium-gui
        private void SelectAndDeselect(IWebElement element, Step step)
        {
            SelectElement select = new SelectElement(element);

            switch (step.Parameters[0])
            {
            case "Select By Index":
                var selectIndex = Convert.ToInt32(step.Parameters[1]);
                select.SelectByIndex(selectIndex);
                break;

            case "Select By Text":
                select.SelectByText(step.Parameters[1]);
                break;

            case "Select By Value":
                select.SelectByValue(step.Parameters[1]);
                break;

            case "Deselect All":
                select.DeselectAll();
                break;

            case "Deselect By Index":
                var deselectIndex = Convert.ToInt32(step.Parameters[1]);
                select.DeselectByIndex(deselectIndex);
                break;

            case "Deselect By Text":
                select.DeselectByText(step.Parameters[1]);
                break;

            case "Deselect By Value":
                select.DeselectByValue(step.Parameters[1]);
                break;
            }
        }
コード例 #17
0
        public void MultipleBox()
        {
            driver.Url = "https://demoqa.com/automation-practice-form/";
            driver.Manage().Window.Maximize();
            SelectElement selectElement = new SelectElement
                                              (driver.FindElement(By.Name("selenium_commands")));

            selectElement.SelectByIndex(0);
            selectElement.DeselectByIndex(0);
            selectElement.SelectByText("Navigation Commands");
            selectElement.DeselectByText("Navigation Commands");

            IList <IWebElement> webs = selectElement.Options;
            int iListSize            = webs.Count;

            for (int i = 0; i < iListSize; i++)
            {
                String sValu = selectElement.Options.ElementAt(i).Text;
                Console.WriteLine("Value of the Select item is : " + sValu);
                selectElement.SelectByIndex(i);
            }
            selectElement.DeselectAll();
            driver.Close();
        }
コード例 #18
0
        static void Main(string[] args)
        {
            #region Test1
            //var driver = new FirefoxDriver();

            //driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);

            //driver.Url = "http://toolsqa.wpengine.com/automation-practice-form";

            //SelectElement oSelection = new SelectElement(driver.FindElement(By.Id("continents")));

            //oSelection.SelectByText("Europe");
            //Thread.Sleep(2000);

            //oSelection.SelectByIndex(2);
            //Thread.Sleep(2000);

            //IList<IWebElement> oSize = oSelection.Options;
            //int iListSize = oSize.Count;
            //for (int i = 0; i < iListSize; i++)
            //{
            //    string sValue = oSelection.Options.ElementAt(i).Text;
            //    Console.WriteLine($"Value of the Select item is:{sValue}");

            //    if (sValue.Equals("Africa"))
            //    {
            //        oSelection.SelectByIndex(i);
            //        break;
            //    }
            //}
            //driver.Close();
            #endregion

            #region Test2
            // Create a new instance of the Firefox driver
            IWebDriver driver = new FirefoxDriver();

            // Put an Implicit wait, this means that any search for elements on the page could take the time the implicit wait is set for before throwing exception
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);

            // Launch the URL
            driver.Url = "http://toolsqa.wpengine.com/automation-practice-form";

            // Step 3: Select 'Selenium Commands' Multiple select box ( Use Name locator to identify the element )
            SelectElement oSelection = new SelectElement(driver.FindElement(By.Name("selenium_commands")));

            // Step 4: Select option 'Browser Commands'  and then deselect it (Use selectByIndex and deselectByIndex)
            oSelection.SelectByIndex(0);
            Thread.Sleep(2000);
            oSelection.DeselectByIndex(0);

            // Step 5: Select option 'Navigation Commands'  and then deselect it (Use selectByVisibleText and deselectByVisibleText)
            oSelection.SelectByText("Navigation Commands");
            Thread.Sleep(2000);

            oSelection.DeselectByText("Navigation Commands");

            // Step 6: Print and select all the options for the selected Multiple selection list.
            IList <IWebElement> oSize = oSelection.Options;
            int iListSize             = oSize.Count;

            // Setting up the loop to print all the options
            for (int i = 0; i < iListSize; i++)
            {
                // Storing the value of the option
                String sValue = oSelection.Options.ElementAt(i).Text;
                // Printing the stored value
                Console.WriteLine("Value of the Item is :" + sValue);
                // Selecting all the elements one by one
                oSelection.SelectByIndex(i);

                Thread.Sleep(2000);
            }

            // Step 7: Deselect all
            oSelection.DeselectAll();

            // Kill the browser
            driver.Close();
            #endregion
        }
コード例 #19
0
        public override void RunCommand(object sender)
        {
            var engine = (AutomationEngineInstance)sender;
            //convert to user variable -- https://github.com/saucepleez/taskt/issues/66
            var     seleniumSearchParam = v_SeleniumSearchParameter.ConvertUserVariableToString(engine);
            var     browserObject       = v_InstanceName.GetAppInstance(engine);
            var     seleniumInstance    = (IWebDriver)browserObject;
            dynamic element             = null;

            if (v_SeleniumElementAction == "Wait For Element To Exist")
            {
                var timeoutText = (from rw in v_WebActionParameterTable.AsEnumerable()
                                   where rw.Field <string>("Parameter Name") == "Timeout (Seconds)"
                                   select rw.Field <string>("Parameter Value")).FirstOrDefault();

                timeoutText = timeoutText.ConvertUserVariableToString(engine);
                int timeOut   = Convert.ToInt32(timeoutText);
                var timeToEnd = DateTime.Now.AddSeconds(timeOut);

                while (timeToEnd >= DateTime.Now)
                {
                    try
                    {
                        element = FindElement(seleniumInstance, seleniumSearchParam);
                        break;
                    }
                    catch (Exception)
                    {
                        engine.ReportProgress("Element Not Yet Found... " + (timeToEnd - DateTime.Now).Seconds + "s remain");
                        Thread.Sleep(1000);
                    }
                }

                if (element == null)
                {
                    throw new Exception("Element Not Found");
                }

                return;
            }
            else if (seleniumSearchParam != string.Empty)
            {
                element = FindElement(seleniumInstance, seleniumSearchParam);
            }

            switch (v_SeleniumElementAction)
            {
            case "Invoke Click":
                int seleniumWindowHeightY = seleniumInstance.Manage().Window.Size.Height;
                int elementPositionY      = element.Location.Y;
                if (elementPositionY > seleniumWindowHeightY)
                {
                    String scroll          = String.Format("window.scroll(0, {0})", elementPositionY);
                    IJavaScriptExecutor js = browserObject as IJavaScriptExecutor;
                    js.ExecuteScript(scroll);
                }
                element.Click();
                break;

            case "Left Click":
            case "Right Click":
            case "Middle Click":
            case "Double Left Click":
                int userXAdjust = Convert.ToInt32((from rw in v_WebActionParameterTable.AsEnumerable()
                                                   where rw.Field <string>("Parameter Name") == "X Adjustment"
                                                   select rw.Field <string>("Parameter Value")).FirstOrDefault().ConvertUserVariableToString(engine));

                int userYAdjust = Convert.ToInt32((from rw in v_WebActionParameterTable.AsEnumerable()
                                                   where rw.Field <string>("Parameter Name") == "Y Adjustment"
                                                   select rw.Field <string>("Parameter Value")).FirstOrDefault().ConvertUserVariableToString(engine));

                var elementLocation = element.Location;
                SendMouseMoveCommand newMouseMove = new SendMouseMoveCommand();
                var seleniumWindowPosition        = seleniumInstance.Manage().Window.Position;
                newMouseMove.v_XMousePosition = (seleniumWindowPosition.X + elementLocation.X + 30 + userXAdjust).ToString();     // added 30 for offset
                newMouseMove.v_YMousePosition = (seleniumWindowPosition.Y + elementLocation.Y + 130 + userYAdjust).ToString();    //added 130 for offset
                newMouseMove.v_MouseClick     = v_SeleniumElementAction;
                newMouseMove.RunCommand(sender);
                break;

            case "Set Text":
                string textToSet = (from rw in v_WebActionParameterTable.AsEnumerable()
                                    where rw.Field <string>("Parameter Name") == "Text To Set"
                                    select rw.Field <string>("Parameter Value")).FirstOrDefault().ConvertUserVariableToString(engine);


                string clearElement = (from rw in v_WebActionParameterTable.AsEnumerable()
                                       where rw.Field <string>("Parameter Name") == "Clear Element Before Setting Text"
                                       select rw.Field <string>("Parameter Value")).FirstOrDefault();

                string encryptedData = (from rw in v_WebActionParameterTable.AsEnumerable()
                                        where rw.Field <string>("Parameter Name") == "Encrypted Text"
                                        select rw.Field <string>("Parameter Value")).FirstOrDefault();

                if (clearElement == null)
                {
                    clearElement = "No";
                }

                if (clearElement.ToLower() == "yes")
                {
                    element.Clear();
                }

                if (encryptedData == "Encrypted")
                {
                    textToSet = EncryptionServices.DecryptString(textToSet, "TASKT");
                }

                string[] potentialKeyPresses = textToSet.Split('{', '}');

                Type        seleniumKeys = typeof(OpenQA.Selenium.Keys);
                FieldInfo[] fields       = seleniumKeys.GetFields(BindingFlags.Static | BindingFlags.Public);

                //check if chunked string contains a key press command like {ENTER}
                foreach (string chunkedString in potentialKeyPresses)
                {
                    if (chunkedString == "")
                    {
                        continue;
                    }

                    if (fields.Any(f => f.Name == chunkedString))
                    {
                        string keyPress = (string)fields.Where(f => f.Name == chunkedString).FirstOrDefault().GetValue(null);
                        element.SendKeys(keyPress);
                    }
                    else
                    {
                        //convert to user variable - https://github.com/saucepleez/taskt/issues/22
                        var convertedChunk = chunkedString.ConvertUserVariableToString(engine);
                        element.SendKeys(convertedChunk);
                    }
                }
                break;

            case "Set Secure Text":
                var secureString = (from rw in v_WebActionParameterTable.AsEnumerable()
                                    where rw.Field <string>("Parameter Name") == "Secure String Variable"
                                    select rw.Field <string>("Parameter Value")).FirstOrDefault();

                string _clearElement = (from rw in v_WebActionParameterTable.AsEnumerable()
                                        where rw.Field <string>("Parameter Name") == "Clear Element Before Setting Text"
                                        select rw.Field <string>("Parameter Value")).FirstOrDefault();

                var secureStrVariable = secureString.ConvertUserVariableToObject(engine);

                if (secureStrVariable is SecureString)
                {
                    secureString = ((SecureString)secureStrVariable).ConvertSecureStringToString();
                }
                else
                {
                    throw new ArgumentException("Provided Argument is not a 'Secure String'");
                }

                if (_clearElement == null)
                {
                    _clearElement = "No";
                }

                if (_clearElement.ToLower() == "yes")
                {
                    element.Clear();
                }

                string[] _potentialKeyPresses = secureString.Split('{', '}');

                Type        _seleniumKeys = typeof(OpenQA.Selenium.Keys);
                FieldInfo[] _fields       = _seleniumKeys.GetFields(BindingFlags.Static | BindingFlags.Public);

                //check if chunked string contains a key press command like {ENTER}
                foreach (string chunkedString in _potentialKeyPresses)
                {
                    if (chunkedString == "")
                    {
                        continue;
                    }

                    if (_fields.Any(f => f.Name == chunkedString))
                    {
                        string keyPress = (string)_fields.Where(f => f.Name == chunkedString).FirstOrDefault().GetValue(null);
                        element.SendKeys(keyPress);
                    }
                    else
                    {
                        //convert to user variable - https://github.com/saucepleez/taskt/issues/22
                        var convertedChunk = chunkedString.ConvertUserVariableToString(engine);
                        element.SendKeys(convertedChunk);
                    }
                }
                break;

            case "Get Options":
                string applyToVarName = (from rw in v_WebActionParameterTable.AsEnumerable()
                                         where rw.Field <string>("Parameter Name") == "Variable Name"
                                         select rw.Field <string>("Parameter Value")).FirstOrDefault();


                string attribName = (from rw in v_WebActionParameterTable.AsEnumerable()
                                     where rw.Field <string>("Parameter Name") == "Attribute Name"
                                     select rw.Field <string>("Parameter Value")).FirstOrDefault().ConvertUserVariableToString(engine);

                var optionsItems = new List <string>();
                var ele          = (IWebElement)element;
                var select       = new SelectElement(ele);
                var options      = select.Options;

                foreach (var option in options)
                {
                    var optionValue = option.GetAttribute(attribName);
                    optionsItems.Add(optionValue);
                }

                optionsItems.StoreInUserVariable(engine, applyToVarName);

                break;

            case "Select Option":
                string selectionType = (from rw in v_WebActionParameterTable.AsEnumerable()
                                        where rw.Field <string>("Parameter Name") == "Selection Type"
                                        select rw.Field <string>("Parameter Value")).FirstOrDefault();

                string selectionParam = (from rw in v_WebActionParameterTable.AsEnumerable()
                                         where rw.Field <string>("Parameter Name") == "Selection Parameter"
                                         select rw.Field <string>("Parameter Value")).FirstOrDefault().ConvertUserVariableToString(engine);

                seleniumInstance.SwitchTo().ActiveElement();

                var el = (IWebElement)element;
                var selectionElement = new SelectElement(el);

                switch (selectionType)
                {
                case "Select By Index":
                    selectionElement.SelectByIndex(int.Parse(selectionParam));
                    break;

                case "Select By Text":
                    selectionElement.SelectByText(selectionParam);
                    break;

                case "Select By Value":
                    selectionElement.SelectByValue(selectionParam);
                    break;

                case "Deselect By Index":
                    selectionElement.DeselectByIndex(int.Parse(selectionParam));
                    break;

                case "Deselect By Text":
                    selectionElement.DeselectByText(selectionParam);
                    break;

                case "Deselect By Value":
                    selectionElement.DeselectByValue(selectionParam);
                    break;

                case "Deselect All":
                    selectionElement.DeselectAll();
                    break;

                default:
                    throw new NotImplementedException();
                }
                break;

            case "Get Text":
            case "Get Attribute":
            case "Get Count":
                string VariableName = (from rw in v_WebActionParameterTable.AsEnumerable()
                                       where rw.Field <string>("Parameter Name") == "Variable Name"
                                       select rw.Field <string>("Parameter Value")).FirstOrDefault();

                string attributeName = (from rw in v_WebActionParameterTable.AsEnumerable()
                                        where rw.Field <string>("Parameter Name") == "Attribute Name"
                                        select rw.Field <string>("Parameter Value")).FirstOrDefault().ConvertUserVariableToString(engine);

                string elementValue;
                if (v_SeleniumElementAction == "Get Text")
                {
                    elementValue = element.Text;
                }
                else if (v_SeleniumElementAction == "Get Count")
                {
                    elementValue = "1";
                    if (element is ReadOnlyCollection <IWebElement> )
                    {
                        elementValue = ((ReadOnlyCollection <IWebElement>)element).Count().ToString();
                    }
                }
                else
                {
                    elementValue = element.GetAttribute(attributeName);
                }

                elementValue.StoreInUserVariable(engine, VariableName);
                break;

            case "Get Matching Element(s)":
                var variableName = (from rw in v_WebActionParameterTable.AsEnumerable()
                                    where rw.Field <string>("Parameter Name") == "Variable Name"
                                    select rw.Field <string>("Parameter Value")).FirstOrDefault();

                if (!(element is IWebElement))
                {
                    //create element list
                    List <IWebElement> elementList = new List <IWebElement>();
                    foreach (IWebElement item in element)
                    {
                        elementList.Add(item);
                    }
                    elementList.StoreInUserVariable(engine, variableName);
                }
                else
                {
                    ((IWebElement)element).StoreInUserVariable(engine, variableName);
                }
                break;

            case "Get Table":
                var DTVariableName = (from rw in v_WebActionParameterTable.AsEnumerable()
                                      where rw.Field <string>("Parameter Name") == "Variable Name"
                                      select rw.Field <string>("Parameter Value")).FirstOrDefault();

                // Get HTML (Source) of the Element
                string       tableHTML = element.GetAttribute("innerHTML").ToString();
                HtmlDocument doc       = new HtmlDocument();

                //Load Source (String) as HTML Document
                doc.LoadHtml(tableHTML);

                //Get Header Tags
                var       headers = doc.DocumentNode.SelectNodes("//tr/th");
                DataTable DT      = new DataTable();

                //If headers found
                if (headers != null && headers.Count != 0)
                {
                    // add columns from th (headers)
                    foreach (HtmlNode header in headers)
                    {
                        DT.Columns.Add(Regex.Replace(header.InnerText, @"\t|\n|\r", "").Trim());
                    }
                }
                else
                {
                    var columnsCount = doc.DocumentNode.SelectSingleNode("//tr[1]").ChildNodes.Where(node => node.Name == "td").Count();
                    DT.Columns.AddRange((Enumerable.Range(1, columnsCount).Select(dc => new DataColumn())).ToArray());
                }

                // select rows with td elements and load each row (containing <td> tags) into DataTable
                foreach (var row in doc.DocumentNode.SelectNodes("//tr[td]"))
                {
                    DT.Rows.Add(row.SelectNodes("td").Select(td => Regex.Replace(td.InnerText, @"\t|\n|\r", "").Trim()).ToArray());
                }

                DT.StoreInUserVariable(engine, DTVariableName);
                break;

            case "Clear Element":
                element.Clear();
                break;

            case "Switch to Frame":
                if (seleniumSearchParam == "")
                {
                    seleniumInstance.SwitchTo().DefaultContent();
                }
                else
                {
                    seleniumInstance.SwitchTo().Frame(element);
                }
                break;

            default:
                throw new Exception("Element Action was not found");
            }
        }
コード例 #20
0
 public static void DeselectByIndex(this IWebElement webElement, int index)
 {
     var selectElement = new SelectElement(webElement);
     selectElement.DeselectByIndex(index);
 }
コード例 #21
0
        public void DeselectByIndex(int index)
        {
            SelectElement element = new SelectElement(aWebElement);

            element.DeselectByIndex(index);
        }
コード例 #22
0
        //private void ElementsGridViewHelper_MouseEnter(object sender, EventArgs e)
        //{
        //    seleniumAction_SelectionChangeCommitted(null, null);
        //}

        public override void RunCommand(object sender)
        {
            var engine = (Core.Automation.Engine.AutomationEngineInstance)sender;
            //convert to user variable -- https://github.com/saucepleez/taskt/issues/66
            var seleniumSearchParam = v_SeleniumSearchParameter.ConvertToUserVariable(sender);


            var vInstance = v_InstanceName.ConvertToUserVariable(engine);

            var browserObject = engine.GetAppInstance(vInstance);

            var seleniumInstance = (OpenQA.Selenium.IWebDriver)browserObject;

            dynamic element = null;

            if (v_SeleniumElementAction == "Wait For Element To Exist")
            {
                var timeoutText = (from rw in v_WebActionParameterTable.AsEnumerable()
                                   where rw.Field <string>("Parameter Name") == "Timeout (Seconds)"
                                   select rw.Field <string>("Parameter Value")).FirstOrDefault();

                timeoutText = timeoutText.ConvertToUserVariable(sender);

                int timeOut = Convert.ToInt32(timeoutText);

                var timeToEnd = DateTime.Now.AddSeconds(timeOut);

                while (timeToEnd >= DateTime.Now)
                {
                    try
                    {
                        element = FindElement(seleniumInstance, seleniumSearchParam);
                        break;
                    }
                    catch (Exception)
                    {
                        engine.ReportProgress("Element Not Yet Found... " + (timeToEnd - DateTime.Now).Seconds + "s remain");
                        System.Threading.Thread.Sleep(1000);
                    }
                }

                if (element == null)
                {
                    throw new Exception("Element Not Found");
                }

                return;
            }
            else if (seleniumSearchParam != string.Empty)
            {
                element = FindElement(seleniumInstance, seleniumSearchParam);
            }



            switch (v_SeleniumElementAction)
            {
            case "Invoke Click":
                element.Click();
                break;

            case "Left Click":
            case "Right Click":
            case "Middle Click":
            case "Double Left Click":


                int userXAdjust = Convert.ToInt32((from rw in v_WebActionParameterTable.AsEnumerable()
                                                   where rw.Field <string>("Parameter Name") == "X Adjustment"
                                                   select rw.Field <string>("Parameter Value")).FirstOrDefault().ConvertToUserVariable(sender));

                int userYAdjust = Convert.ToInt32((from rw in v_WebActionParameterTable.AsEnumerable()
                                                   where rw.Field <string>("Parameter Name") == "Y Adjustment"
                                                   select rw.Field <string>("Parameter Value")).FirstOrDefault().ConvertToUserVariable(sender));

                var elementLocation = element.Location;
                SendMouseMoveCommand newMouseMove = new SendMouseMoveCommand();
                var seleniumWindowPosition        = seleniumInstance.Manage().Window.Position;
                newMouseMove.v_XMousePosition = (seleniumWindowPosition.X + elementLocation.X + 30 + userXAdjust).ToString();     // added 30 for offset
                newMouseMove.v_YMousePosition = (seleniumWindowPosition.Y + elementLocation.Y + 130 + userYAdjust).ToString();    //added 130 for offset
                newMouseMove.v_MouseClick     = v_SeleniumElementAction;
                newMouseMove.RunCommand(sender);
                break;

            case "Set Text":

                string textToSet = (from rw in v_WebActionParameterTable.AsEnumerable()
                                    where rw.Field <string>("Parameter Name") == "Text To Set"
                                    select rw.Field <string>("Parameter Value")).FirstOrDefault();


                string clearElement = (from rw in v_WebActionParameterTable.AsEnumerable()
                                       where rw.Field <string>("Parameter Name") == "Clear Element Before Setting Text"
                                       select rw.Field <string>("Parameter Value")).FirstOrDefault();

                string encryptedData = (from rw in v_WebActionParameterTable.AsEnumerable()
                                        where rw.Field <string>("Parameter Name") == "Encrypted Text"
                                        select rw.Field <string>("Parameter Value")).FirstOrDefault();



                if (clearElement == null)
                {
                    clearElement = "No";
                }

                if (clearElement.ToLower() == "yes")
                {
                    element.Clear();
                }


                if (encryptedData == "Encrypted")
                {
                    textToSet = Core.EncryptionServices.DecryptString(textToSet, "TASKT");
                }

                string[] potentialKeyPresses = textToSet.Split('{', '}');

                Type seleniumKeys = typeof(OpenQA.Selenium.Keys);
                System.Reflection.FieldInfo[] fields = seleniumKeys.GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);

                //check if chunked string contains a key press command like {ENTER}
                foreach (string chunkedString in potentialKeyPresses)
                {
                    if (chunkedString == "")
                    {
                        continue;
                    }

                    if (fields.Any(f => f.Name == chunkedString))
                    {
                        string keyPress = (string)fields.Where(f => f.Name == chunkedString).FirstOrDefault().GetValue(null);
                        element.SendKeys(keyPress);
                    }
                    else
                    {
                        //convert to user variable - https://github.com/saucepleez/taskt/issues/22
                        var convertedChunk = chunkedString.ConvertToUserVariable(sender);
                        element.SendKeys(convertedChunk);
                    }
                }

                break;

            case "Get Options":

                string applyToVarName = (from rw in v_WebActionParameterTable.AsEnumerable()
                                         where rw.Field <string>("Parameter Name") == "Variable Name"
                                         select rw.Field <string>("Parameter Value")).FirstOrDefault();


                string attribName = (from rw in v_WebActionParameterTable.AsEnumerable()
                                     where rw.Field <string>("Parameter Name") == "Attribute Name"
                                     select rw.Field <string>("Parameter Value")).FirstOrDefault().ConvertToUserVariable(sender);


                var optionsItems = new List <string>();
                var ele          = (IWebElement)element;
                var select       = new SelectElement(ele);
                var options      = select.Options;

                foreach (var option in options)
                {
                    var optionValue = option.GetAttribute(attribName);
                    optionsItems.Add(optionValue);
                }

                var requiredVariable = engine.VariableList.Where(x => x.VariableName == applyToVarName).FirstOrDefault();

                if (requiredVariable == null)
                {
                    engine.VariableList.Add(new Script.ScriptVariable()
                    {
                        VariableName = applyToVarName, CurrentPosition = 0
                    });
                    requiredVariable = engine.VariableList.Where(x => x.VariableName == applyToVarName).FirstOrDefault();
                }

                requiredVariable.VariableValue   = optionsItems;
                requiredVariable.CurrentPosition = 0;


                break;

            case "Select Option":

                string selectionType = (from rw in v_WebActionParameterTable.AsEnumerable()
                                        where rw.Field <string>("Parameter Name") == "Selection Type"
                                        select rw.Field <string>("Parameter Value")).FirstOrDefault();

                string selectionParam = (from rw in v_WebActionParameterTable.AsEnumerable()
                                         where rw.Field <string>("Parameter Name") == "Selection Parameter"
                                         select rw.Field <string>("Parameter Value")).FirstOrDefault();


                seleniumInstance.SwitchTo().ActiveElement();

                var el = (IWebElement)element;
                var selectionElement = new SelectElement(el);

                switch (selectionType)
                {
                case "Select By Index":
                    selectionElement.SelectByIndex(int.Parse(selectionParam));
                    break;

                case "Select By Text":
                    selectionElement.SelectByText(selectionParam);
                    break;

                case "Select By Value":
                    selectionElement.SelectByValue(selectionParam);
                    break;

                case "Deselect By Index":
                    selectionElement.DeselectByIndex(int.Parse(selectionParam));
                    break;

                case "Deselect By Text":
                    selectionElement.DeselectByText(selectionParam);
                    break;

                case "Deselect By Value":
                    selectionElement.DeselectByValue(selectionParam);
                    break;

                case "Deselect All":
                    selectionElement.DeselectAll();
                    break;

                default:
                    throw new NotImplementedException();
                }

                break;

            case "Get Text":
            case "Get Attribute":
            case "Get Count":

                string VariableName = (from rw in v_WebActionParameterTable.AsEnumerable()
                                       where rw.Field <string>("Parameter Name") == "Variable Name"
                                       select rw.Field <string>("Parameter Value")).FirstOrDefault();

                string attributeName = (from rw in v_WebActionParameterTable.AsEnumerable()
                                        where rw.Field <string>("Parameter Name") == "Attribute Name"
                                        select rw.Field <string>("Parameter Value")).FirstOrDefault().ConvertToUserVariable(sender);

                string elementValue;
                if (v_SeleniumElementAction == "Get Text")
                {
                    elementValue = element.Text;
                }
                else if (v_SeleniumElementAction == "Get Count")
                {
                    elementValue = "1";
                    if (element is ReadOnlyCollection <IWebElement> )
                    {
                        elementValue = ((ReadOnlyCollection <IWebElement>)element).Count().ToString();
                    }
                }
                else
                {
                    elementValue = element.GetAttribute(attributeName);
                }

                elementValue.StoreInUserVariable(sender, VariableName);

                break;

            case "Get Matching Elements":
                var variableName = (from rw in v_WebActionParameterTable.AsEnumerable()
                                    where rw.Field <string>("Parameter Name") == "Variable Name"
                                    select rw.Field <string>("Parameter Value")).FirstOrDefault();

                var requiredComplexVariable = engine.VariableList.Where(x => x.VariableName == variableName).FirstOrDefault();

                if (requiredComplexVariable == null)
                {
                    engine.VariableList.Add(new Script.ScriptVariable()
                    {
                        VariableName = variableName, CurrentPosition = 0
                    });
                    requiredComplexVariable = engine.VariableList.Where(x => x.VariableName == variableName).FirstOrDefault();
                }


                //set json settings
                JsonSerializerSettings settings = new JsonSerializerSettings();
                settings.Error = (serializer, err) => {
                    err.ErrorContext.Handled = true;
                };

                settings.Formatting = Formatting.Indented;

                //create json list
                List <string> jsonList = new List <string>();
                foreach (OpenQA.Selenium.IWebElement item in element)
                {
                    var json = Newtonsoft.Json.JsonConvert.SerializeObject(item, settings);
                    jsonList.Add(json);
                }

                requiredComplexVariable.VariableValue   = jsonList;
                requiredComplexVariable.CurrentPosition = 0;

                break;

            case "Clear Element":
                element.Clear();
                break;

            case "Switch to frame":
                if (seleniumSearchParam == "")
                {
                    seleniumInstance.SwitchTo().DefaultContent();
                }
                else
                {
                    seleniumInstance.SwitchTo().Frame(element);
                }
                break;

            default:
                throw new Exception("Element Action was not found");
            }
        }
コード例 #23
0
        public void DropDownMultipleSelectDropDownTest()
        {
            try
            {
                driver.Url = "http://www.uitestpractice.com/Students/Select";       //Url of website

                driver.Manage().Window.Maximize();                                  //Maximize the windows

                driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10); // implicit wait

                IWebElement dropdown = driver.FindElement(By.Id("countriesSingle"));

                SelectElement selectElement = new SelectElement(dropdown); //Create select element

                //options properties gets the list of optins belonging to the select tag
                IList <IWebElement> elements = selectElement.Options; //options for multiple drowndown list and store in list

                Console.WriteLine(elements.Count);                    // print the number presents in dropdown list
                Thread.Sleep(3000);


                foreach (var item in elements)
                {
                    Console.WriteLine(item.Text); //print all the test in dropdown list
                }
                Thread.Sleep(3000);

                IWebElement multiDropdown = driver.FindElement(By.Id("countriesMultiple"));
                Thread.Sleep(3000);

                SelectElement selectmultiple = new SelectElement(multiDropdown); //create multiple select downlaod
                Thread.Sleep(3000);

                bool isMultiple = selectmultiple.IsMultiple; //checking selected dropdown is multiple dropdown or simple dropdown
                Thread.Sleep(2000);
                Console.WriteLine(isMultiple);               // return value in true and false
                Thread.Sleep(2000);

                //slect by test works on multiple dropdown list

                selectmultiple.SelectByText("India");
                Thread.Sleep(2000); //in multiple dorpdown list select by test "india"

                selectmultiple.DeselectByText("India");
                Thread.Sleep(2000);             // here selected by test element is deselected by this properties

                selectElement.SelectByIndex(1); // here selected elements by index
                Thread.Sleep(2000);

                selectmultiple.DeselectByIndex(1); //here deslecting by index
                Thread.Sleep(2000);

                selectmultiple.SelectByValue("china"); //value is comming from inspecting element you want to select and take value
                Thread.Sleep(2000);

                selectmultiple.DeselectByValue("china"); //here deselecting the value
                Thread.Sleep(2000);

                //select multiple value in multiple dropdown and print the value you selected
                selectmultiple.SelectByIndex(1);
                selectmultiple.SelectByIndex(2);                                 // selecting 1 n 2 both

                IList <IWebElement> element = selectmultiple.AllSelectedOptions; // here select mulltiple value store in list
                Thread.Sleep(2000);
                Console.WriteLine(element.Count);                                // count the multiple selected item

                foreach (var item in element)                                    // here printing all the selected values
                {
                    Console.WriteLine(item.Text);
                    Thread.Sleep(2000);
                }
                Thread.Sleep(2000);

                selectmultiple.DeselectAll(); // here multiple values is diselected
                Thread.Sleep(2000);
            }
            catch (Exception exception)
            {
                Screenshot.Capture(driver, exception.Message);
                Console.WriteLine(exception.Message);
                Email.SendMailTest.SendEmail(exception.Message.Trim(), exception.StackTrace);
            }
            finally
            {
                driver.Quit();
            }
        }
コード例 #24
0
        /// <summary>
        /// Deselect the &lt;option&gt; element with the specified index, as determined by the "index" attribute.
        /// </summary>
        /// <typeparam name="TResult">The type of block to return.</typeparam>
        /// <param name="index">The index of the element to select.</param>
        /// <returns>The closest related element of type <typeparamref name="TResult" />.</returns>
        public TResult DeselectByIndex <TResult>(int index) where TResult : IBlock
        {
            SelectElement.DeselectByIndex(index);

            return(this.FindRelated <TResult>());
        }
コード例 #25
0
        public async override Task RunCommand(object sender)
        {
            var engine = (IAutomationEngineInstance)sender;

            var vTimeout = (int)await v_Timeout.EvaluateCode(engine);

            var seleniumSearchParamRows = (from rw in v_SeleniumSearchParameters.AsEnumerable()
                                           where rw.Field <string>("Enabled") == "True" &&
                                           rw.Field <string>("Parameter Value").ToString() != ""
                                           select rw.ItemArray.Cast <string>().ToArray()).ToList();

            var     browserObject    = ((OBAppInstance)await v_InstanceName.EvaluateCode(engine)).Value;
            var     seleniumInstance = (IWebDriver)browserObject;
            dynamic element          = await CommandsHelper.FindElement(engine, seleniumInstance, seleniumSearchParamRows, v_SeleniumSearchOption, vTimeout);

            if (element == null && v_SeleniumElementAction != "Element Exists")
            {
                throw new ElementNotVisibleException("Unable to find element within the provided time limit");
            }

            if (v_SeleniumElementAction.Contains("Click"))
            {
                int seleniumWindowHeightY = seleniumInstance.Manage().Window.Size.Height;
                int elementPositionY      = ((IWebElement)element).Location.Y;
                if (elementPositionY > seleniumWindowHeightY)
                {
                    string scroll          = string.Format("window.scroll(0, {0})", elementPositionY);
                    IJavaScriptExecutor js = browserObject as IJavaScriptExecutor;
                    js.ExecuteScript(scroll);
                }
            }
            Actions actions = new Actions(seleniumInstance);

            switch (v_SeleniumElementAction)
            {
            case "Invoke Click":
                ((IWebElement)element).Click();
                break;

            case "Left Click":
                actions.Click((IWebElement)element).Perform();
                break;

            case "Right Click":
                actions.ContextClick((IWebElement)element).Perform();
                break;

            case "Middle Click":
                string userXAdjustString = (from rw in v_WebActionParameterTable.AsEnumerable()
                                            where rw.Field <string>("Parameter Name") == "X Adjustment"
                                            select rw.Field <string>("Parameter Value")).FirstOrDefault();
                int userXAdjust = (int)await userXAdjustString.EvaluateCode(engine);

                string userYAdjustString = (from rw in v_WebActionParameterTable.AsEnumerable()
                                            where rw.Field <string>("Parameter Name") == "Y Adjustment"
                                            select rw.Field <string>("Parameter Value")).FirstOrDefault();
                int userYAdjust = (int)await userYAdjustString.EvaluateCode(engine);

                var elementLocation        = ((IWebElement)element).Location;
                var seleniumWindowPosition = seleniumInstance.Manage().Window.Position;
                User32Functions.SendMouseMove(seleniumWindowPosition.X + elementLocation.X + userXAdjust, seleniumWindowPosition.Y + elementLocation.Y + userYAdjust,
                                              v_SeleniumElementAction);

                break;

            case "Double Left Click":
                actions.DoubleClick((IWebElement)element).Perform();
                break;

            case "Hover Over Element":
                string hoverTime = (from rw in v_WebActionParameterTable.AsEnumerable()
                                    where rw.Field <string>("Parameter Name") == "Hover Time (Seconds)"
                                    select rw.Field <string>("Parameter Value")).FirstOrDefault();
                int hoverTimeInt = (int)await hoverTime.EvaluateCode(engine) * 1000;

                actions.MoveToElement((IWebElement)element).Perform();
                Thread.Sleep(hoverTimeInt);
                break;

            case "Set Text":
                string textToSetString = (from rw in v_WebActionParameterTable.AsEnumerable()
                                          where rw.Field <string>("Parameter Name") == "Text To Set"
                                          select rw.Field <string>("Parameter Value")).FirstOrDefault();
                string textToSet = (string)await textToSetString.EvaluateCode(engine);

                string clearElement = (from rw in v_WebActionParameterTable.AsEnumerable()
                                       where rw.Field <string>("Parameter Name") == "Clear Element Before Setting Text"
                                       select rw.Field <string>("Parameter Value")).FirstOrDefault();

                if (clearElement == null)
                {
                    clearElement = "No";
                }

                if (clearElement.ToLower() == "yes")
                {
                    ((IWebElement)element).Clear();
                }

                string[] potentialKeyPresses = textToSet.Split('[', ']');

                Type        seleniumKeys = typeof(OpenQA.Selenium.Keys);
                FieldInfo[] fields       = seleniumKeys.GetFields(BindingFlags.Static | BindingFlags.Public);

                //check if chunked string contains a key press command like {ENTER}
                foreach (string chunkedString in potentialKeyPresses)
                {
                    if (chunkedString == "")
                    {
                        continue;
                    }

                    if (fields.Any(f => f.Name.ToLower() == chunkedString.ToLower()) && textToSet.Contains($"[{chunkedString}]"))
                    {
                        string keyPress = (string)fields.Where(f => f.Name.ToLower() == chunkedString.ToLower()).FirstOrDefault().GetValue(null);
                        textToSet = textToSet.Replace($"[{chunkedString}]", keyPress);
                    }
                }

                ((IWebElement)element).SendKeys(textToSet);
                break;

            case "Set Secure Text":
                var secureString = (from rw in v_WebActionParameterTable.AsEnumerable()
                                    where rw.Field <string>("Parameter Name") == "Secure String Variable"
                                    select rw.Field <string>("Parameter Value")).FirstOrDefault();

                string _clearElement = (from rw in v_WebActionParameterTable.AsEnumerable()
                                        where rw.Field <string>("Parameter Name") == "Clear Element Before Setting Text"
                                        select rw.Field <string>("Parameter Value")).FirstOrDefault();

                var secureStrVariable = (SecureString)await secureString.EvaluateCode(engine);

                secureString = secureStrVariable.ConvertSecureStringToString();

                if (_clearElement == null)
                {
                    _clearElement = "No";
                }

                if (_clearElement.ToLower() == "yes")
                {
                    ((IWebElement)element).Clear();
                }

                string[] _potentialKeyPresses = secureString.Split('[', ']');

                Type        _seleniumKeys   = typeof(OpenQA.Selenium.Keys);
                FieldInfo[] _fields         = _seleniumKeys.GetFields(BindingFlags.Static | BindingFlags.Public);
                string      _finalTextToSet = "";

                //check if chunked string contains a key press command like {ENTER}
                foreach (string chunkedString in _potentialKeyPresses)
                {
                    if (chunkedString == "")
                    {
                        continue;
                    }

                    if (_fields.Any(f => f.Name.ToLower() == chunkedString.ToLower()) && secureString.Contains("[" + chunkedString + "]"))
                    {
                        string keyPress = (string)_fields.Where(f => f.Name.ToLower() == chunkedString.ToLower()).FirstOrDefault().GetValue(null);
                        _finalTextToSet += keyPress;
                    }
                    else
                    {
                        _finalTextToSet += chunkedString;
                    }
                }
                ((IWebElement)element).SendKeys(_finalTextToSet);
                break;

            case "Get Options":
                string applyToVarName = (from rw in v_WebActionParameterTable.AsEnumerable()
                                         where rw.Field <string>("Parameter Name") == "Variable Name"
                                         select rw.Field <string>("Parameter Value")).FirstOrDefault();


                string attribNameString = (from rw in v_WebActionParameterTable.AsEnumerable()
                                           where rw.Field <string>("Parameter Name") == "Attribute Name"
                                           select rw.Field <string>("Parameter Value")).FirstOrDefault();
                string attribName = (string)await attribNameString.EvaluateCode(engine);

                var optionsItems = new List <string>();
                var ele          = (IWebElement)element;
                var select       = new SelectElement(ele);
                var options      = select.Options;

                foreach (var option in options)
                {
                    var optionValue = option.GetAttribute(attribName);
                    optionsItems.Add(optionValue);
                }

                optionsItems.SetVariableValue(engine, applyToVarName);

                break;

            case "Select Option":
                string selectionType = (from rw in v_WebActionParameterTable.AsEnumerable()
                                        where rw.Field <string>("Parameter Name") == "Selection Type"
                                        select rw.Field <string>("Parameter Value")).FirstOrDefault();

                string selectionParamString = (from rw in v_WebActionParameterTable.AsEnumerable()
                                               where rw.Field <string>("Parameter Name") == "Selection Parameter"
                                               select rw.Field <string>("Parameter Value")).FirstOrDefault();
                string selectionParam = (string)await selectionParamString.EvaluateCode(engine);

                seleniumInstance.SwitchTo().ActiveElement();

                var el = (IWebElement)element;
                var selectionElement = new SelectElement(el);

                switch (selectionType)
                {
                case "Select By Index":
                    selectionElement.SelectByIndex(int.Parse(selectionParam));
                    break;

                case "Select By Text":
                    selectionElement.SelectByText(selectionParam);
                    break;

                case "Select By Value":
                    selectionElement.SelectByValue(selectionParam);
                    break;

                case "Deselect By Index":
                    selectionElement.DeselectByIndex(int.Parse(selectionParam));
                    break;

                case "Deselect By Text":
                    selectionElement.DeselectByText(selectionParam);
                    break;

                case "Deselect By Value":
                    selectionElement.DeselectByValue(selectionParam);
                    break;

                case "Deselect All":
                    selectionElement.DeselectAll();
                    break;

                default:
                    throw new NotImplementedException();
                }
                break;

            case "Get Text":
            case "Get Attribute":
            case "Get Count":
                string VariableName = (from rw in v_WebActionParameterTable.AsEnumerable()
                                       where rw.Field <string>("Parameter Name") == "Variable Name"
                                       select rw.Field <string>("Parameter Value")).FirstOrDefault();

                string attributeNameString = (from rw in v_WebActionParameterTable.AsEnumerable()
                                              where rw.Field <string>("Parameter Name") == "Attribute Name"
                                              select rw.Field <string>("Parameter Value")).FirstOrDefault();
                string attributeName = (string)await attributeNameString.EvaluateCode(engine);

                string elementValue;
                if (v_SeleniumElementAction == "Get Text")
                {
                    elementValue = element.Text;
                }
                else if (v_SeleniumElementAction == "Get Count")
                {
                    elementValue = "1";
                    if (element is ReadOnlyCollection <IWebElement> )
                    {
                        elementValue = ((ReadOnlyCollection <IWebElement>)element).Count().ToString();
                    }
                }
                else
                {
                    elementValue = ((IWebElement)element).GetAttribute(attributeName);
                }

                elementValue.SetVariableValue(engine, VariableName);
                break;

            case "Get Matching Element(s)":
                var variableName = (from rw in v_WebActionParameterTable.AsEnumerable()
                                    where rw.Field <string>("Parameter Name") == "Variable Name"
                                    select rw.Field <string>("Parameter Value")).FirstOrDefault();

                if (!(element is IWebElement))
                {
                    //create element list
                    List <IWebElement> elementList = new List <IWebElement>();
                    foreach (IWebElement item in element)
                    {
                        elementList.Add(item);
                    }
                    elementList.SetVariableValue(engine, variableName);
                }
                else
                {
                    ((IWebElement)element).SetVariableValue(engine, variableName);
                }
                break;

            case "Get Table":
                var DTVariableName = (from rw in v_WebActionParameterTable.AsEnumerable()
                                      where rw.Field <string>("Parameter Name") == "Variable Name"
                                      select rw.Field <string>("Parameter Value")).FirstOrDefault();

                // Get HTML (Source) of the Element
                string       tableHTML = ((IWebElement)element).GetAttribute("innerHTML").ToString();
                HtmlDocument doc       = new HtmlDocument();

                //Load Source (String) as HTML Document
                doc.LoadHtml(tableHTML);

                //Get Header Tags
                var       headers = doc.DocumentNode.SelectNodes("//tr/th");
                DataTable DT      = new DataTable();

                //If headers found
                if (headers != null && headers.Count != 0)
                {
                    // add columns from th (headers)
                    foreach (HtmlNode header in headers)
                    {
                        DT.Columns.Add(Regex.Replace(header.InnerText, @"\t|\n|\r", "").Trim());
                    }
                }
                else
                {
                    var columnsCount = doc.DocumentNode.SelectSingleNode("//tr[1]").ChildNodes.Where(node => node.Name == "td").Count();
                    DT.Columns.AddRange((Enumerable.Range(1, columnsCount).Select(dc => new DataColumn())).ToArray());
                }

                // select rows with td elements and load each row (containing <td> tags) into DataTable
                foreach (var row in doc.DocumentNode.SelectNodes("//tr[td]"))
                {
                    DT.Rows.Add(row.SelectNodes("td").Select(td => Regex.Replace(td.InnerText, @"\t|\n|\r", "").Trim()).ToArray());
                }

                DT.SetVariableValue(engine, DTVariableName);
                break;

            case "Clear Element":
                ((IWebElement)element).Clear();
                break;

            case "Switch to Frame":
                if (seleniumSearchParamRows.Count == 0)
                {
                    seleniumInstance.SwitchTo().DefaultContent();
                }
                else
                {
                    seleniumInstance.SwitchTo().Frame((IWebElement)element);
                }
                break;

            case "Wait For Element To Exist":
                break;

            case "Element Exists":
                string existsBoolVariableName = (from rw in v_WebActionParameterTable.AsEnumerable()
                                                 where rw.Field <string>("Parameter Name") == "Variable Name"
                                                 select rw.Field <string>("Parameter Value")).FirstOrDefault();

                if (element == null)
                {
                    false.SetVariableValue(engine, existsBoolVariableName);
                }
                else
                {
                    true.SetVariableValue(engine, existsBoolVariableName);
                }

                break;

            default:
                throw new Exception("Element Action was not found");
            }
        }
コード例 #26
0
ファイル: HtmlComboBox.cs プロジェクト: Bisu1909/bisucalog
 public void DeselectByIndex(int index)
 {
     _wrapper.DeselectByIndex(index);
 }