예제 #1
0
        /// <summary>
        /// Add to the script args.
        /// </summary>
        /// <param name="scriptArgs">Arguments to be added.</param>
        /// <returns>A Driver result from adding it.</returns>
        internal WebDriverResult AddToScriptArgs(SafeScriptArgsHandle scriptArgs)
        {
            WebDriverResult result = NativeDriverLibrary.Instance.AddElementScriptArg(scriptArgs, elementHandle);

            ResultHandler.VerifyResultCode(result, "adding to script arguments");
            return(result);
        }
예제 #2
0
        /// <summary>
        /// Converts the Collection to a list
        /// </summary>
        /// <returns>A list of strings </returns>
        public List <string> ToList()
        {
            int             elementCount = 0;
            WebDriverResult result       = NativeDriverLibrary.Instance.GetStringCollectionLength(handle, ref elementCount);

            if (result != WebDriverResult.Success)
            {
                Dispose();
                throw new WebDriverException(string.Format(CultureInfo.InvariantCulture, "Cannot extract strings from collection: {0}", result));
            }

            List <string> toReturn = new List <string>();

            for (int i = 0; i < elementCount; i++)
            {
                SafeStringWrapperHandle stringHandle = new SafeStringWrapperHandle();
                result = NativeDriverLibrary.Instance.GetStringAtIndex(handle, i, ref stringHandle);
                if (result != WebDriverResult.Success)
                {
                    stringHandle.Dispose();
                    Dispose();
                    throw new WebDriverException(string.Format(CultureInfo.InvariantCulture, "Cannot extract string from collection at index: {0} ({1})", i, result));
                }

                using (StringWrapper wrapper = new StringWrapper(stringHandle))
                {
                    toReturn.Add(wrapper.Value);
                }
            }

            // TODO(andre.nogueira): from the java code (elementcollection.java)... "Free memory from the collection"
            // Dispose();
            return(toReturn);
        }
        /// <summary>
        /// Converts a Collection of elements into a list
        /// </summary>
        /// <returns>List of IWebElement</returns>
        public List <IWebElement> ToList()
        {
            List <IWebElement> toReturn = new List <IWebElement>();
            int numberOfElements        = 0;

            NativeDriverLibrary.Instance.GetElementCollectionLength(collectionHandle, ref numberOfElements);
            for (int i = 0; i < numberOfElements; i++)
            {
                SafeInternetExplorerWebElementHandle wrapper = new SafeInternetExplorerWebElementHandle();
                WebDriverResult result = NativeDriverLibrary.Instance.GetElementAtIndex(collectionHandle, i, ref wrapper);

                // OPTIMIZATION: Check for a success value, then run through the
                // VerifyErrorCode which will throw the proper exception
                if (result != WebDriverResult.Success)
                {
                    try
                    {
                        ResultHandler.VerifyResultCode(result, string.Empty);
                    }
                    catch (Exception e)
                    {
                        // We need to process the exception to free the memory.
                        // Then we can wrap and rethrow.
                        collectionHandle.FreeElementsOnDispose = true;
                        Dispose();
                        throw new WebDriverException("Could not retrieve element " + i + " from element collection", e);
                    }
                }

                toReturn.Add(new InternetExplorerWebElement(driver, wrapper));
            }
            ////TODO(andre.nogueira): from the java code (elementcollection.java)... "Free memory from the collection"
            return(toReturn);
        }
        /// <summary>
        /// Executes JavaScript in the context of the currently selected frame or window.
        /// </summary>
        /// <param name="script">The JavaScript code to execute.</param>
        /// <param name="args">The arguments to the script.</param>
        /// <returns>The value returned by the script.</returns>
        /// <remarks>
        /// <para>
        /// The <see cref="ExecuteScript"/>method executes JavaScript in the context of
        /// the currently selected frame or window. This means that "document" will refer
        /// to the current document. If the script has a return value, then the following
        /// steps will be taken:
        /// </para>
        /// <para>
        /// <list type="bullet">
        /// <item><description>For an HTML element, this method returns a <see cref="IWebElement"/></description></item>
        /// <item><description>For a number, a <see cref="System.Int64"/> is returned</description></item>
        /// <item><description>For a boolean, a <see cref="System.Boolean"/> is returned</description></item>
        /// <item><description>For all other cases a <see cref="System.String"/> is returned.</description></item>
        /// <item><description>For an array,we check the first element, and attempt to return a
        /// <see cref="List{T}"/> of that type, following the rules above. Nested lists are not
        /// supported.</description></item>
        /// <item><description>If the value is null or there is no return value,
        /// <see langword="null"/> is returned.</description></item>
        /// </list>
        /// </para>
        /// <para>
        /// Arguments must be a number (which will be converted to a <see cref="System.Int64"/>),
        /// a <see cref="System.Boolean"/>, a <see cref="System.String"/> or a <see cref="IWebElement"/>.
        /// An exception will be thrown if the arguments do not meet these criteria.
        /// The arguments will be made available to the JavaScript via the "arguments" magic
        /// variable, as if the function were called via "Function.apply"
        /// </para>
        /// </remarks>
        public object ExecuteScript(string script, params object[] args)
        {
            object toReturn = null;
            SafeScriptArgsHandle scriptArgsHandle = new SafeScriptArgsHandle();
            WebDriverResult      result           = NativeDriverLibrary.Instance.NewScriptArgs(ref scriptArgsHandle, args.Length);

            ResultHandler.VerifyResultCode(result, "Unable to create new script arguments array");

            try
            {
                PopulateArguments(scriptArgsHandle, args);

                script = "(function() { return function(){" + script + "};})();";

                SafeScriptResultHandle scriptResultHandle = new SafeScriptResultHandle();
                result = NativeDriverLibrary.Instance.ExecuteScript(handle, script, scriptArgsHandle, ref scriptResultHandle);

                ResultHandler.VerifyResultCode(result, "Cannot execute script");

                // Note that ExtractReturnValue frees the memory for the script result.
                toReturn = ExtractReturnValue(scriptResultHandle);
            }
            finally
            {
                scriptArgsHandle.Dispose();
            }

            return(toReturn);
        }
예제 #5
0
 private Response(Dictionary <string, object> rawResponse)
 {
     if (rawResponse.ContainsKey("sessionId") && rawResponse["sessionId"] != null)
     {
         this.responseSessionId = rawResponse["sessionId"].ToString();
     }
     if (rawResponse.ContainsKey("value"))
     {
         this.responseValue = rawResponse["value"];
     }
     if (rawResponse.ContainsKey("status"))
     {
         this.responseStatus = (WebDriverResult)Convert.ToInt32(rawResponse["status"], CultureInfo.InvariantCulture);
         return;
     }
     this.isSpecificationCompliant = true;
     if (!rawResponse.ContainsKey("value") && this.responseValue == null)
     {
         if (rawResponse.ContainsKey("capabilities"))
         {
             this.responseValue = rawResponse["capabilities"];
         }
         else
         {
             this.responseValue = rawResponse;
         }
     }
     if (rawResponse.ContainsKey("error"))
     {
         this.responseStatus = WebDriverError.ResultFromError(rawResponse["error"].ToString());
     }
 }
예제 #6
0
                /// <summary>
                /// Specifies the amount of time the driver should wait when searching for an
                /// element if it is not immediately present.
                /// </summary>
                /// <param name="timeToWait">A <see cref="TimeSpan"/> structure defining the amount of time to wait.</param>
                /// <returns>A self reference</returns>
                /// <remarks>
                /// When searching for a single element, the driver should poll the page
                /// until the element has been found, or this timeout expires before throwing
                /// a <see cref="ElementNotFoundException"/>. When searching for multiple elements,
                /// the driver should poll the page until at least one element has been found
                /// or this timeout has expired.
                /// <para>
                /// Increasing the implicit wait timeout should be used judiciously as it
                /// will have an adverse effect on test run time, especially when used with
                /// slower location strategies like XPath.
                /// </para>
                /// </remarks>
                public ITimeouts ImplicitlyWait(TimeSpan timeToWait)
                {
                    int             timeInMilliseconds = Convert.ToInt32(timeToWait.TotalMilliseconds);
                    WebDriverResult result             = NativeDriverLibrary.Instance.SetImplicitWaitTimeout(driver.handle, timeInMilliseconds);

                    return(this);
                }
예제 #7
0
        /// <summary>
        /// Drag and Drop an element to another element.
        /// </summary>
        /// <param name="element">Element you wish to drop on.</param>
        public void DragAndDropOn(IRenderedWebElement element)
        {
            IntPtr          hwnd   = IntPtr.Zero;
            int             x      = 0;
            int             y      = 0;
            int             width  = 0;
            int             height = 0;
            WebDriverResult result = NativeDriverLibrary.Instance.GetElementDetailsOnceScrolledOnToScreen(elementHandle, ref hwnd, ref x, ref y, ref width, ref height);

            ResultHandler.VerifyResultCode(result, "Unable to determine location once scrolled on to screen");

            int startX = x + (width / 2);
            int startY = y + (height / 2);

            NativeDriverLibrary.Instance.MouseDownAt(hwnd, startX, startY);

            SafeInternetExplorerWebElementHandle other = ((InternetExplorerWebElement)element).Wrapper;

            result = NativeDriverLibrary.Instance.GetElementDetailsOnceScrolledOnToScreen(other, ref hwnd, ref x, ref y, ref width, ref height);
            ResultHandler.VerifyResultCode(result, "Unable to determine location of target once scrolled on to screen");

            int endX = x + (width / 2);
            int endY = y + (height / 2);

            int duration = driver.Manage().Speed.Timeout;

            NativeDriverLibrary.Instance.MouseMoveTo(hwnd, duration, startX, startY, endX, endY);
            NativeDriverLibrary.Instance.MouseUpAt(hwnd, endX, endY);
        }
            /// <summary>
            /// Change to the Window by passing in the name.
            /// </summary>
            /// <param name="windowName">name of the window that you wish to move to.</param>
            /// <returns>A WebDriver instance that is currently in use.</returns>
            public IWebDriver Window(string windowName)
            {
                WebDriverResult result = NativeDriverLibrary.Instance.SwitchToWindow(driver.handle, windowName);

                ResultHandler.VerifyResultCode(result, "Could not switch to window " + windowName);
                return(driver);
            }
            /// <summary>
            /// Method for getting a Collection of Cookies that are present in the browser.
            /// </summary>
            /// <returns>ReadOnlyCollection of Cookies in the browser.</returns>
            public ReadOnlyCollection <Cookie> GetCookies()
            {
                Uri currentUri = GetCurrentUri();

                SafeStringWrapperHandle stringHandle = new SafeStringWrapperHandle();
                WebDriverResult         result       = NativeDriverLibrary.Instance.GetCookies(driver.handle, ref stringHandle);

                ResultHandler.VerifyResultCode(result, "Getting Cookies");
                string allDomainCookies = string.Empty;

                using (StringWrapper wrapper = new StringWrapper(stringHandle))
                {
                    allDomainCookies = wrapper.Value;
                }

                List <Cookie> toReturn = new List <Cookie>();

                string[] cookies = allDomainCookies.Split(new string[] { "; " }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string cookie in cookies)
                {
                    string[] parts = cookie.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length != 2)
                    {
                        continue;
                    }

                    toReturn.Add(new ReturnedCookie(parts[0], parts[1], currentUri.Host, string.Empty, null, false, currentUri));
                }

                return(new ReadOnlyCollection <Cookie>(toReturn));
            }
예제 #10
0
        /// <summary>
        /// Method to return the first element that matches the CSS class passed in
        /// </summary>
        /// <param name="className">CSS class name</param>
        /// <returns>IWebElement object so that you can interact that object</returns>
        public IWebElement FindElementByClassName(string className)
        {
            SafeInternetExplorerWebElementHandle rawElement = new SafeInternetExplorerWebElementHandle();
            WebDriverResult result = NativeDriverLibrary.Instance.FindElementByClassName(handle, parent, className, ref rawElement);

            ResultHandler.VerifyResultCode(result, "FindElementByClassName");
            return(new InternetExplorerWebElement(driver, rawElement));
        }
예제 #11
0
        /// <summary>
        /// Finds the first of elements that match the link text supplied
        /// </summary>
        /// <param name="linkText">Link text of element </param>
        /// <returns>IWebElement object so that you can interact that object</returns>
        public IWebElement FindElementByLinkText(string linkText)
        {
            SafeInternetExplorerWebElementHandle rawElement = new SafeInternetExplorerWebElementHandle();
            WebDriverResult result = NativeDriverLibrary.Instance.FindElementByLinkText(handle, parent, linkText, ref rawElement);

            ResultHandler.VerifyResultCode(result, "FindElementByLinkText");
            return(new InternetExplorerWebElement(driver, rawElement));
        }
예제 #12
0
        /// <summary>
        /// If the element is a checkbox this will toggle the elements state from selected to not selected, or from not selected to selected.
        /// </summary>
        /// <returns>Whether the toggled element is selected (true) or not (false) after this toggle is complete.</returns>
        public bool Toggle()
        {
            int             toggled = 0;
            WebDriverResult result  = NativeDriverLibrary.Instance.ToggleElement(elementHandle, ref toggled);

            ResultHandler.VerifyResultCode(result, "Toggling element");
            return(toggled == 1);
        }
예제 #13
0
        private Response(Dictionary <string, object> rawResponse)
        {
            if (rawResponse.ContainsKey("sessionId"))
            {
                if (rawResponse["sessionId"] != null)
                {
                    this.responseSessionId = rawResponse["sessionId"].ToString();
                }
            }

            if (rawResponse.ContainsKey("value"))
            {
                this.responseValue = rawResponse["value"];
            }

            // If the returned object does *not* have a "value" property
            // the response value should be the entirety of the response.
            // TODO: Remove this if statement altogether; there should
            // never be a spec-compliant response that does not contain a
            // value property.
            if (!rawResponse.ContainsKey("value") && this.responseValue == null)
            {
                // Special-case for the new session command, where the "capabilities"
                // property of the response is the actual value we're interested in.
                if (rawResponse.ContainsKey("capabilities"))
                {
                    this.responseValue = rawResponse["capabilities"];
                }
                else
                {
                    this.responseValue = rawResponse;
                }
            }

            Dictionary <string, object> valueDictionary = this.responseValue as Dictionary <string, object>;

            if (valueDictionary != null)
            {
                // Special case code for the new session command. If the response contains
                // sessionId and capabilities properties, fix up the session ID and value members.
                if (valueDictionary.ContainsKey("sessionId"))
                {
                    this.responseSessionId = valueDictionary["sessionId"].ToString();
                    if (valueDictionary.ContainsKey("capabilities"))
                    {
                        this.responseValue = valueDictionary["capabilities"];
                    }
                    else
                    {
                        this.responseValue = valueDictionary["value"];
                    }
                }
                else if (valueDictionary.ContainsKey("error"))
                {
                    this.responseStatus = WebDriverError.ResultFromError(valueDictionary["error"].ToString());
                }
            }
        }
예제 #14
0
            /// <summary>
            /// Finds the currently active element.
            /// </summary>
            /// <returns>WebElement of the active element.</returns>
            public IWebElement ActiveElement()
            {
                SafeInternetExplorerWebElementHandle rawElement = new SafeInternetExplorerWebElementHandle();
                WebDriverResult result = NativeDriverLibrary.Instance.SwitchToActiveElement(driver.handle, ref rawElement);

                ResultHandler.VerifyResultCode(result, "Unable to find active element");

                return(new InternetExplorerWebElement(driver, rawElement));
            }
예제 #15
0
        /// <summary>
        /// Closes the Browser.
        /// </summary>
        public void Close()
        {
            WebDriverResult result = NativeDriverLibrary.Instance.Close(handle);

            if (result != WebDriverResult.Success)
            {
                throw new InvalidOperationException("Unable to close driver: " + result.ToString());
            }
        }
예제 #16
0
        /// <summary>
        /// Initializes a new instance of the InternetExplorerDriver class.
        /// </summary>
        public InternetExplorerDriver()
        {
            handle = new SafeInternetExplorerDriverHandle();
            WebDriverResult result = NativeDriverLibrary.Instance.NewDriverInstance(ref handle);

            if (result != WebDriverResult.Success)
            {
                throw new WebDriverException(string.Format(CultureInfo.InvariantCulture, "Cannot create new browser instance: {0}", result.ToString()));
            }
        }
예제 #17
0
        public void Constructor_CopiesData()
        {
            var data = new WebDriverResponse();

            WebDriverResult result = new WebDriverResult(data);

            Assert.Same(data, result.Value);
            Assert.Equal("application/json; charset=utf-8", result.ContentType);
            Assert.Equal(200, result.StatusCode);
        }
예제 #18
0
        private static WebDriverResult PopulateArguments(SafeScriptArgsHandle scriptArgs, object[] args)
        {
            WebDriverResult result = WebDriverResult.Success;

            foreach (object arg in args)
            {
                string stringArg = arg as string;
                InternetExplorerWebElement webElementArg = arg as InternetExplorerWebElement;

                if (stringArg != null)
                {
                    result = NativeDriverLibrary.Instance.AddStringScriptArg(scriptArgs, stringArg);
                }
                else if (arg is bool)
                {
                    bool param = (bool)arg;
                    result = NativeDriverLibrary.Instance.AddBooleanScriptArg(scriptArgs, !param ? 0 : 1);
                }
                else if (webElementArg != null)
                {
                    result = webElementArg.AddToScriptArgs(scriptArgs);
                }
                else if (arg is int || arg is short || arg is long)
                {
                    int  param;
                    bool parseSucceeded = int.TryParse(arg.ToString(), out param);
                    if (!parseSucceeded)
                    {
                        throw new ArgumentException("Parameter is not recognized as an int: " + arg);
                    }

                    result = NativeDriverLibrary.Instance.AddNumberScriptArg(scriptArgs, param);
                }
                else if (arg is float || arg is double)
                {
                    double param;
                    bool   parseSucceeded = double.TryParse(arg.ToString(), out param);
                    if (!parseSucceeded)
                    {
                        throw new ArgumentException("Parameter is not of recognized as a double: " + arg);
                    }

                    result = NativeDriverLibrary.Instance.AddDoubleScriptArg(scriptArgs, param);
                }
                else
                {
                    throw new ArgumentException("Parameter is not of recognized type: " + arg);
                }

                ResultHandler.VerifyResultCode(result, "Unable to add argument: " + arg);
            }

            return(result);
        }
예제 #19
0
        public void Constructor_Error()
        {
            var data = new WebDriverResponse(
                new WebDriverError(WebDriverErrorCode.InvalidSessionId));

            WebDriverResult result = new WebDriverResult(data);

            Assert.Same(data, result.Value);
            Assert.Equal("application/json; charset=utf-8", result.ContentType);
            Assert.Equal(404, result.StatusCode);
        }
예제 #20
0
        private Response(Dictionary<string, object> rawResponse)
        {
            if (rawResponse.ContainsKey("sessionId"))
            {
                if (rawResponse["sessionId"] != null)
                {
                    this.responseSessionId = rawResponse["sessionId"].ToString();
                }
            }

            if (rawResponse.ContainsKey("value"))
            {
                this.responseValue = rawResponse["value"];
            }

            if (rawResponse.ContainsKey("status"))
            {
                this.responseStatus = (WebDriverResult)Convert.ToInt32(rawResponse["status"], CultureInfo.InvariantCulture);
            }
            else
            {
                // If the response does *not* have a "status" property, it
                // is compliant with the specification, which does not put
                // status in its responses.
                this.isSpecificationCompliant = true;

                // If the returned object does *not* have a "value" property
                // the response value should be the entirety of the response.
                if (!rawResponse.ContainsKey("value") && this.responseValue == null)
                {
                    // Special-case for the new session command, where the "capabilities"
                    // property of the response is the actual value we're interested in.
                    if (rawResponse.ContainsKey("capabilities"))
                    {
                        this.responseValue = rawResponse["capabilities"];
                    }
                    else
                    {
                        this.responseValue = rawResponse;
                    }
                }

                // Check for an error response by looking for an "error" property,
                // and if found, convert to a numeric status code.
                if (rawResponse.ContainsKey("error"))
                {
                    this.responseStatus = WebDriverError.ResultFromError(rawResponse["error"].ToString());
                }
            }
        }
예제 #21
0
        private Response(Dictionary <string, object> rawResponse)
        {
            if (rawResponse.ContainsKey("sessionId"))
            {
                if (rawResponse["sessionId"] != null)
                {
                    this.responseSessionId = rawResponse["sessionId"].ToString();
                }
            }

            if (rawResponse.ContainsKey("value"))
            {
                this.responseValue = rawResponse["value"];
            }

            if (rawResponse.ContainsKey("status"))
            {
                this.responseStatus = (WebDriverResult)Convert.ToInt32(rawResponse["status"], CultureInfo.InvariantCulture);
            }
            else
            {
                // If the response does *not* have a "status" property, it
                // is compliant with the specification, which does not put
                // status in its responses.
                this.isSpecificationCompliant = true;

                // If the returned object does *not* have a "value" property
                // the response value should be the entirety of the response.
                if (!rawResponse.ContainsKey("value") && this.responseValue == null)
                {
                    // Special-case for the new session command, where the "capabilities"
                    // property of the response is the actual value we're interested in.
                    if (rawResponse.ContainsKey("capabilities"))
                    {
                        this.responseValue = rawResponse["capabilities"];
                    }
                    else
                    {
                        this.responseValue = rawResponse;
                    }
                }

                // Check for an error response by looking for an "error" property,
                // and if found, convert to a numeric status code.
                if (rawResponse.ContainsKey("error"))
                {
                    this.responseStatus = WebDriverError.ResultFromError(rawResponse["error"].ToString());
                }
            }
        }
예제 #22
0
        /// <summary>
        /// Verifies the results
        /// </summary>
        /// <param name="resultCode">Code returned from the driver</param>
        /// <param name="messageReturned">Message to be returned</param>
        internal static void VerifyResultCode(WebDriverResult resultCode, string messageReturned)
        {
            switch (resultCode)
            {
                case WebDriverResult.Success:
                    break; // Nothing to do

                case WebDriverResult.NoSuchElement:
                    throw new NoSuchElementException(messageReturned);

                case WebDriverResult.NoSuchFrame:
                    throw new NoSuchFrameException(messageReturned);

                case WebDriverResult.NotImplemented:
                    throw new NotImplementedException("You may not perform the requested action");

                case WebDriverResult.ObsoleteElement:
                    throw new StaleElementReferenceException(string.Format(CultureInfo.InvariantCulture, "You may not {0} this element. It looks as if the reference is stale. Did you navigate away from the page with this element on?", messageReturned));

                case WebDriverResult.ElementNotDisplayed:
                    throw new ElementNotVisibleException(string.Format(CultureInfo.InvariantCulture, "You may not {0} an element that is not displayed", messageReturned));

                case WebDriverResult.ElementNotEnabled:
                    throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "You may not {0} an element that is not enabled", messageReturned));

                case WebDriverResult.UnhandledError:
                    throw new WebDriverException(string.Format(CultureInfo.InvariantCulture, "Unhandled Error: {0}", messageReturned));

                case WebDriverResult.ElementNotSelected:
                    throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "The element appears to be unselectable: {0}", messageReturned));

                case WebDriverResult.NoSuchDocument:
                    throw new NoSuchElementException(messageReturned + " (no document found)");

                case WebDriverResult.Timeout:
                    throw new TimeoutException("The driver reported that the command timed out. There may "
                                               + "be several reasons for this. Check that the destination "
                                               + "site is in IE's 'Trusted Sites' (accessed from Tools->"
                                               + "Internet Options in the 'Security' tab) If it is a "
                                               + "trusted site, then the request may have taken more than "
                                               + "a minute to finish.");

                case WebDriverResult.NoSuchWindow:
                    throw new NoSuchWindowException(messageReturned);

                default:
                    throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "{0} ({1})", messageReturned, resultCode));
            }
        }
예제 #23
0
        /// <summary>
        /// Verifies the results
        /// </summary>
        /// <param name="resultCode">Code returned from the driver</param>
        /// <param name="messageReturned">Message to be returned</param>
        internal static void VerifyResultCode(WebDriverResult resultCode, string messageReturned)
        {
            switch (resultCode)
            {
            case WebDriverResult.Success:
                break;     // Nothing to do

            case WebDriverResult.NoSuchElement:
                throw new NoSuchElementException(messageReturned);

            case WebDriverResult.NoSuchFrame:
                throw new NoSuchFrameException(messageReturned);

            case WebDriverResult.NotImplemented:
                throw new NotImplementedException("You may not perform the requested action");

            case WebDriverResult.ObsoleteElement:
                throw new StaleElementReferenceException(string.Format(CultureInfo.InvariantCulture, "You may not {0} this element. It looks as if the reference is stale. Did you navigate away from the page with this element on?", messageReturned));

            case WebDriverResult.ElementNotDisplayed:
                throw new ElementNotVisibleException(string.Format(CultureInfo.InvariantCulture, "You may not {0} an element that is not displayed", messageReturned));

            case WebDriverResult.ElementNotEnabled:
                throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "You may not {0} an element that is not enabled", messageReturned));

            case WebDriverResult.UnhandledError:
                throw new WebDriverException(string.Format(CultureInfo.InvariantCulture, "Unhandled Error: {0}", messageReturned));

            case WebDriverResult.ElementNotSelected:
                throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "The element appears to be unselectable: {0}", messageReturned));

            case WebDriverResult.NoSuchDocument:
                throw new NoSuchElementException(messageReturned + " (no document found)");

            case WebDriverResult.Timeout:
                throw new TimeoutException("The driver reported that the command timed out. There may "
                                           + "be several reasons for this. Check that the destination"
                                           + "site is in IE's 'Trusted Sites' (accessed from Tools->"
                                           + "Internet Options in the 'Security' tab) If it is a "
                                           + "trusted site, then the request may have taken more than"
                                           + "a minute to finish.");

            case WebDriverResult.NoSuchWindow:
                throw new NoSuchWindowException(messageReturned);

            default:
                throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "{0} ({1})", messageReturned, resultCode));
            }
        }
예제 #24
0
        /// <summary>
        /// Returns the Name of Window that the driver is working in.
        /// </summary>
        /// <returns>Returns the name of the Window.</returns>
        /// <example>
        /// IWebDriver driver = new InternetExplorerDriver();
        /// string windowName = driver.GetWindowHandles();
        /// </example>
        public string GetWindowHandle()
        {
            SafeStringWrapperHandle stringHandle = new SafeStringWrapperHandle();
            WebDriverResult         result       = NativeDriverLibrary.Instance.GetCurrentWindowHandle(handle, ref stringHandle);

            ResultHandler.VerifyResultCode(result, "Unable to obtain current window handle");
            string handleValue = string.Empty;

            using (StringWrapper wrapper = new StringWrapper(stringHandle))
            {
                handleValue = wrapper.Value;
            }

            return(handleValue);
        }
예제 #25
0
        /// <summary>
        /// Method to return the value of a CSS Property
        /// </summary>
        /// <param name="propertyName">CSS property key</param>
        /// <returns>string value of the CSS property</returns>
        public string GetValueOfCssProperty(string propertyName)
        {
            SafeStringWrapperHandle stringHandle = new SafeStringWrapperHandle();
            WebDriverResult         result       = NativeDriverLibrary.Instance.GetElementValueOfCssProperty(elementHandle, propertyName, ref stringHandle);

            ResultHandler.VerifyResultCode(result, string.Format(CultureInfo.InvariantCulture, "get the value of CSS property '{0}'", propertyName));
            string returnValue = string.Empty;

            using (StringWrapper wrapper = new StringWrapper(stringHandle))
            {
                returnValue = wrapper.Value;
            }

            return(returnValue);
        }
예제 #26
0
        /// <summary>
        /// Finds a list of elements that match the link text supplied
        /// </summary>
        /// <param name="linkText">Link text of element</param>
        /// <returns>ReadOnlyCollection of IWebElement object so that you can interact with those objects</returns>
        public ReadOnlyCollection <IWebElement> FindElementsByLinkText(string linkText)
        {
            SafeWebElementCollectionHandle collectionHandle = new SafeWebElementCollectionHandle();
            WebDriverResult result = NativeDriverLibrary.Instance.FindElementsByLinkText(handle, parent, linkText, ref collectionHandle);

            ResultHandler.VerifyResultCode(result, "FindElementsByLinkText");
            List <IWebElement> elementList = new List <IWebElement>();

            using (InternetExplorerWebElementCollection elements = new InternetExplorerWebElementCollection(driver, collectionHandle))
            {
                elementList = elements.ToList();
            }

            return(new ReadOnlyCollection <IWebElement>(elementList));
        }
예제 #27
0
        /// <summary>
        /// Method for returning a collection of WindowHandles that the driver has access to.
        /// </summary>
        /// <returns>Returns a ReadOnlyCollection of Window Handles.</returns>
        /// <example>
        /// IWebDriver driver = new InternetExplorerDriver();
        /// ReadOnlyCollection<![CDATA[<string>]]> windowNames = driver.GetWindowHandles();
        /// </example>
        public ReadOnlyCollection <string> GetWindowHandles()
        {
            SafeStringCollectionHandle handlesPtr = new SafeStringCollectionHandle();
            WebDriverResult            result     = NativeDriverLibrary.Instance.GetAllWindowHandles(handle, ref handlesPtr);

            ResultHandler.VerifyResultCode(result, "Unable to obtain all window handles");

            List <string> windowHandleList = new List <string>();

            using (StringCollection windowHandleStringCollection = new StringCollection(handlesPtr))
            {
                windowHandleList = windowHandleStringCollection.ToList();
            }

            return(new ReadOnlyCollection <string>(windowHandleList));
        }
예제 #28
0
        /// <summary>
        /// If this current element is a form, or an element within a form, then this will be submitted to the remote server. If this causes the current page to change, then this method will block until the new page is loaded.
        /// </summary>
        /// <param name="attributeName">Attribute you wish to get details of.</param>
        /// <returns>The attribute's current value or null if the value is not set.</returns>
        public string GetAttribute(string attributeName)
        {
            SafeStringWrapperHandle          stringHandle = new SafeStringWrapperHandle();
            SafeInternetExplorerDriverHandle driverHandle = driver.GetUnderlayingHandle();
            WebDriverResult result = NativeDriverLibrary.Instance.GetElementAttribute(driverHandle, elementHandle, attributeName, ref stringHandle);

            ResultHandler.VerifyResultCode(result, string.Format(CultureInfo.InvariantCulture, "getting attribute '{0}' of the element", attributeName));
            string returnValue = null;

            using (StringWrapper wrapper = new StringWrapper(stringHandle))
            {
                returnValue = wrapper.Value;
            }

            return(returnValue);
        }
예제 #29
0
        private Response(Dictionary <string, object> rawResponse, int protocolSpecLevel)
        {
            if (rawResponse.ContainsKey("sessionId"))
            {
                if (rawResponse["sessionId"] != null)
                {
                    this.responseSessionId = rawResponse["sessionId"].ToString();
                }
            }

            if (rawResponse.ContainsKey("value"))
            {
                this.responseValue = rawResponse["value"];
            }

            if (protocolSpecLevel > 0)
            {
                // If the returned object does *not* have a "value" property,
                // then the responseValue member of the response will be null.
                if (this.responseValue == null)
                {
                    this.responseValue = rawResponse;
                }

                // Check for an error response by looking for an "error" property,
                // and if found, convert to a numeric status code.
                if (rawResponse.ContainsKey("error"))
                {
                    this.responseStatus = WebDriverError.ResultFromError(rawResponse["error"].ToString());
                }
            }
            else
            {
                if (rawResponse.ContainsKey("status"))
                {
                    this.responseStatus = (WebDriverResult)Convert.ToInt32(rawResponse["status"], CultureInfo.InvariantCulture);
                }

                // Special-case for the new session command, in the case where
                // the remote end is using the W3C dialect of the protocol.
                if (rawResponse.ContainsKey("capabilities"))
                {
                    this.responseValue = rawResponse["capabilities"];
                }
            }
        }
예제 #30
0
        private Response(Dictionary<string, object> rawResponse)
        {
            if (rawResponse.ContainsKey("sessionId"))
            {
                this.responseSessionId = rawResponse["sessionId"].ToString();
            }

            if (rawResponse.ContainsKey("status"))
            {
                this.responseStatus = (WebDriverResult)Convert.ToInt32(rawResponse["status"]);
            }

            if (rawResponse.ContainsKey("value"))
            {
                this.responseValue = rawResponse["value"];
            }
        }
예제 #31
0
        /// <summary>
        /// Moves the mouse over the element to do a hover.
        /// </summary>
        public void Hover()
        {
            IntPtr          hwnd   = IntPtr.Zero;
            int             x      = 0;
            int             y      = 0;
            int             width  = 0;
            int             height = 0;
            WebDriverResult result = NativeDriverLibrary.Instance.GetElementDetailsOnceScrolledOnToScreen(elementHandle, ref hwnd, ref x, ref y, ref width, ref height);

            ResultHandler.VerifyResultCode(result, "hover");

            int midX = x + (width / 2);
            int midY = y + (height / 2);

            result = NativeDriverLibrary.Instance.MouseMoveTo(hwnd, 100, 0, 0, midX, midY);

            ResultHandler.VerifyResultCode(result, "hover mouse move");
        }
예제 #32
0
            /// <summary>
            /// Move to different frame using its name.
            /// </summary>
            /// <param name="frameName">name of the frame.</param>
            /// <returns>A WebDriver instance that is currently in use.</returns>
            public IWebDriver Frame(string frameName)
            {
                if (frameName == null)
                {
                    /* TODO(andre.nogueira): At least the IE driver crashes when
                     * a null is received. I'd much rather move this to the driver itself.
                     * In Java this is not a problem because of "new WString" which
                     * does this check for us. */
                    throw new ArgumentNullException("frameName", "Frame name cannot be null");
                }

                WebDriverResult res = NativeDriverLibrary.Instance.SwitchToFrame(driver.handle, frameName);

                ResultHandler.VerifyResultCode(res, "switch to frame " + frameName);
                ////TODO(andre.nogueira): If this fails, driver cannot be used and has to be
                ////set to a valid frame... What's the best way of doing this?
                return(driver);
            }
예제 #33
0
        private Response(Dictionary <string, object> rawResponse)
        {
            if (rawResponse.ContainsKey("sessionId"))
            {
                if (rawResponse["sessionId"] != null)
                {
                    this.responseSessionId = rawResponse["sessionId"].ToString();
                }
            }

            if (rawResponse.ContainsKey("status"))
            {
                this.responseStatus = (WebDriverResult)Convert.ToInt32(rawResponse["status"]);
            }

            if (rawResponse.ContainsKey("value"))
            {
                this.responseValue = rawResponse["value"];
            }
        }
예제 #34
0
        private Response(Dictionary<string, object> rawResponse, int protocolSpecLevel)
        {
            if (rawResponse.ContainsKey("sessionId"))
            {
                if (rawResponse["sessionId"] != null)
                {
                    this.responseSessionId = rawResponse["sessionId"].ToString();
                }
            }

            if (rawResponse.ContainsKey("value"))
            {
                this.responseValue = rawResponse["value"];
            }

            if (protocolSpecLevel > 0)
            {
                // If the returned object does *not* have a "value" property,
                // then the responseValue member of the response will be null.
                if (this.responseValue == null)
                {
                    this.responseValue = rawResponse;
                }

                // Check for an error response by looking for an "error" property,
                // and if found, convert to a numeric status code.
                if (rawResponse.ContainsKey("error"))
                {
                    this.responseStatus = WebDriverError.ResultFromError(rawResponse["error"].ToString());
                }
            }
            else
            {
                if (rawResponse.ContainsKey("status"))
                {
                    this.responseStatus = (WebDriverResult)Convert.ToInt32(rawResponse["status"], CultureInfo.InvariantCulture);
                }

                // Special-case for the new session command, in the case where
                // the remote end is using the W3C dialect of the protocol.
                if (rawResponse.ContainsKey("capabilities"))
                {
                    this.responseValue = rawResponse["capabilities"];
                }
            }
        }