From 866f81cad25fd898ae0b652753a6a1a311804587 Mon Sep 17 00:00:00 2001
From: Nikolay Borisenko <22616990+nvborisenko@users.noreply.github.com>
Date: Sun, 20 Apr 2025 22:50:30 +0300
Subject: [PATCH] [dotnet] Use namespace file scoped
---
dotnet/.editorconfig | 2 +
.../support/Events/EventFiringWebDriver.cs | 2937 ++++++++---------
.../support/Events/FindElementEventArgs.cs | 77 +-
.../support/Events/GetShadowRootEventArgs.cs | 45 +-
.../Events/WebDriverExceptionEventArgs.cs | 45 +-
.../Events/WebDriverNavigationEventArgs.cs | 63 +-
.../Events/WebDriverScriptEventArgs.cs | 45 +-
.../src/support/Events/WebElementEventArgs.cs | 45 +-
.../Events/WebElementValueEventArgs.cs | 39 +-
.../support/Extensions/WebDriverExtensions.cs | 189 +-
dotnet/src/support/UI/ILoadableComponent.cs | 47 +-
.../support/UI/LoadableComponentException.cs | 63 +-
dotnet/src/support/UI/LoadableComponent{T}.cs | 193 +-
dotnet/src/support/UI/PopupWindowFinder.cs | 203 +-
dotnet/src/support/UI/SelectElement.cs | 643 ++--
.../support/UI/SlowLoadableComponent{T}.cs | 185 +-
.../support/UI/UnexpectedTagNameException.cs | 83 +-
dotnet/src/webdriver/Alert.cs | 97 +-
dotnet/src/webdriver/By.cs | 635 ++--
dotnet/src/webdriver/CapabilityType.cs | 353 +-
dotnet/src/webdriver/Chrome/ChromeDriver.cs | 293 +-
.../webdriver/Chrome/ChromeDriverService.cs | 111 +-
dotnet/src/webdriver/Chrome/ChromeOptions.cs | 125 +-
.../Chromium/ChromiumAndroidOptions.cs | 37 +-
.../src/webdriver/Chromium/ChromiumDriver.cs | 795 +++--
.../Chromium/ChromiumDriverService.cs | 315 +-
.../ChromiumMobileEmulationDeviceSettings.cs | 89 +-
.../Chromium/ChromiumNetworkConditions.cs | 173 +-
.../src/webdriver/Chromium/ChromiumOptions.cs | 1063 +++---
.../ChromiumPerformanceLoggingPreferences.cs | 141 +-
dotnet/src/webdriver/Command.cs | 255 +-
dotnet/src/webdriver/CommandInfo.cs | 143 +-
dotnet/src/webdriver/CommandInfoRepository.cs | 205 +-
dotnet/src/webdriver/Cookie.cs | 587 ++--
dotnet/src/webdriver/CookieJar.cs | 167 +-
dotnet/src/webdriver/DefaultFileDetector.cs | 27 +-
.../webdriver/DetachedShadowRootException.cs | 63 +-
.../DevTools/AuthRequiredEventArgs.cs | 43 +-
.../DevTools/BindingCalledEventArgs.cs | 55 +-
.../DevTools/CommandResponseException.cs | 65 +-
.../DevTools/CommandResponseExtensions.cs | 27 +-
.../DevTools/CommandResponseTypeMap.cs | 85 +-
.../webdriver/DevTools/ConsoleApiArgument.cs | 45 +-
.../DevTools/ConsoleApiCalledEventArgs.cs | 57 +-
.../webdriver/DevTools/DevToolsCommandData.cs | 133 +-
.../src/webdriver/DevTools/DevToolsDomains.cs | 193 +-
.../webdriver/DevTools/DevToolsEventData.cs | 45 +-
.../DevTools/DevToolsExtensionMethods.cs | 121 +-
.../src/webdriver/DevTools/DevToolsOptions.cs | 29 +-
.../src/webdriver/DevTools/DevToolsSession.cs | 1015 +++---
.../DevTools/DevToolsSessionDomains.cs | 37 +-
.../DevToolsSessionEventReceivedEventArgs.cs | 55 +-
.../DevToolsSessionLogMessageEventArgs.cs | 69 +-
.../webdriver/DevTools/DevToolsVersionInfo.cs | 193 +-
.../webdriver/DevTools/EntryAddedEventArgs.cs | 33 +-
.../DevTools/ExceptionThrownEventArgs.cs | 43 +-
dotnet/src/webdriver/DevTools/ICommand.cs | 39 +-
dotnet/src/webdriver/DevTools/IDevTools.cs | 79 +-
.../webdriver/DevTools/IDevToolsSession.cs | 133 +-
dotnet/src/webdriver/DevTools/JavaScript.cs | 215 +-
.../DevTools/Json/JsonEnumMemberConverter.cs | 77 +-
dotnet/src/webdriver/DevTools/Log.cs | 63 +-
dotnet/src/webdriver/DevTools/LogEntry.cs | 43 +-
dotnet/src/webdriver/DevTools/Network.cs | 347 +-
.../DevTools/RequestPausedEventArgs.cs | 43 +-
.../DevTools/ResponsePausedEventArgs.cs | 33 +-
dotnet/src/webdriver/DevTools/Target.cs | 127 +-
.../DevTools/TargetAttachedEventArgs.cs | 55 +-
.../DevTools/TargetDetachedEventArgs.cs | 43 +-
dotnet/src/webdriver/DevTools/TargetInfo.cs | 103 +-
.../webdriver/DevTools/WebSocketConnection.cs | 447 ++-
...ebSocketConnectionDataReceivedEventArgs.cs | 33 +-
.../webdriver/DevTools/v133/V133Domains.cs | 77 +-
.../webdriver/DevTools/v133/V133JavaScript.cs | 279 +-
dotnet/src/webdriver/DevTools/v133/V133Log.cs | 93 +-
.../webdriver/DevTools/v133/V133Network.cs | 555 ++--
.../src/webdriver/DevTools/v133/V133Target.cs | 235 +-
.../webdriver/DevTools/v134/V134Domains.cs | 77 +-
.../webdriver/DevTools/v134/V134JavaScript.cs | 279 +-
dotnet/src/webdriver/DevTools/v134/V134Log.cs | 93 +-
.../webdriver/DevTools/v134/V134Network.cs | 555 ++--
.../src/webdriver/DevTools/v134/V134Target.cs | 235 +-
.../webdriver/DevTools/v135/V135Domains.cs | 77 +-
.../webdriver/DevTools/v135/V135JavaScript.cs | 279 +-
dotnet/src/webdriver/DevTools/v135/V135Log.cs | 93 +-
.../webdriver/DevTools/v135/V135Network.cs | 555 ++--
.../src/webdriver/DevTools/v135/V135Target.cs | 235 +-
dotnet/src/webdriver/DomMutatedEventArgs.cs | 27 +-
dotnet/src/webdriver/DomMutationData.cs | 81 +-
dotnet/src/webdriver/DriverCommand.cs | 933 +++---
dotnet/src/webdriver/DriverFinder.cs | 229 +-
dotnet/src/webdriver/DriverOptions.cs | 901 +++--
.../src/webdriver/DriverOptionsMergeResult.cs | 25 +-
.../DriverProcessStartedEventArgs.cs | 73 +-
.../DriverProcessStartingEventArgs.cs | 37 +-
dotnet/src/webdriver/DriverService.cs | 569 ++--
.../DriverServiceNotFoundException.cs | 63 +-
dotnet/src/webdriver/Edge/EdgeDriver.cs | 233 +-
.../src/webdriver/Edge/EdgeDriverService.cs | 129 +-
dotnet/src/webdriver/Edge/EdgeOptions.cs | 133 +-
.../ElementClickInterceptedException.cs | 63 +-
dotnet/src/webdriver/ElementCoordinates.cs | 73 +-
.../ElementNotInteractableException.cs | 63 +-
dotnet/src/webdriver/EncodedFile.cs | 75 +-
dotnet/src/webdriver/ErrorResponse.cs | 123 +-
.../Firefox/FirefoxAndroidOptions.cs | 65 +-
.../Firefox/FirefoxCommandContext.cs | 29 +-
dotnet/src/webdriver/Firefox/FirefoxDriver.cs | 691 ++--
.../Firefox/FirefoxDriverLogLevel.cs | 73 +-
.../webdriver/Firefox/FirefoxDriverService.cs | 411 ++-
.../src/webdriver/Firefox/FirefoxExtension.cs | 265 +-
.../src/webdriver/Firefox/FirefoxOptions.cs | 571 ++--
.../src/webdriver/Firefox/FirefoxProfile.cs | 503 ++-
.../Firefox/FirefoxProfileManager.cs | 121 +-
.../Firefox/Internal/IniFileReader.cs | 173 +-
dotnet/src/webdriver/Firefox/Preferences.cs | 281 +-
dotnet/src/webdriver/HttpCommandInfo.cs | 183 +-
dotnet/src/webdriver/HttpRequestData.cs | 67 +-
dotnet/src/webdriver/HttpResponseContent.cs | 73 +-
dotnet/src/webdriver/HttpResponseData.cs | 101 +-
dotnet/src/webdriver/IActionExecutor.cs | 39 +-
dotnet/src/webdriver/IAlert.cs | 45 +-
dotnet/src/webdriver/IAllowsFileDetection.cs | 23 +-
dotnet/src/webdriver/ICapabilities.cs | 53 +-
dotnet/src/webdriver/ICommandExecutor.cs | 51 +-
dotnet/src/webdriver/ICookieJar.cs | 77 +-
dotnet/src/webdriver/ICredentials.cs | 15 +-
.../webdriver/ICustomDriverCommandExecutor.cs | 49 +-
.../webdriver/IE/InternetExplorerDriver.cs | 325 +-
.../IE/InternetExplorerDriverLogLevel.cs | 57 +-
.../IE/InternetExplorerDriverService.cs | 241 +-
.../webdriver/IE/InternetExplorerOptions.cs | 639 ++--
dotnet/src/webdriver/IFileDetector.cs | 25 +-
dotnet/src/webdriver/IHasCapabilities.cs | 17 +-
dotnet/src/webdriver/IHasCommandExecutor.cs | 17 +-
dotnet/src/webdriver/IHasDownloads.cs | 39 +-
dotnet/src/webdriver/IHasSessionId.cs | 17 +-
dotnet/src/webdriver/IJavaScriptEngine.cs | 277 +-
dotnet/src/webdriver/IJavascriptExecutor.cs | 169 +-
dotnet/src/webdriver/ILocatable.cs | 29 +-
dotnet/src/webdriver/ILogs.cs | 33 +-
dotnet/src/webdriver/INavigation.cs | 155 +-
dotnet/src/webdriver/INetwork.cs | 113 +-
dotnet/src/webdriver/IOptions.cs | 55 +-
dotnet/src/webdriver/IRotatable.cs | 21 +-
dotnet/src/webdriver/ISearchContext.cs | 41 +-
dotnet/src/webdriver/ISupportsLogs.cs | 15 +-
dotnet/src/webdriver/ISupportsPrint.cs | 23 +-
dotnet/src/webdriver/ITakesScreenshot.cs | 19 +-
dotnet/src/webdriver/ITargetLocator.cs | 139 +-
dotnet/src/webdriver/ITimeouts.cs | 71 +-
dotnet/src/webdriver/IWebDriver.cs | 177 +-
dotnet/src/webdriver/IWebElement.cs | 383 ++-
dotnet/src/webdriver/IWindow.cs | 53 +-
dotnet/src/webdriver/IWrapsDriver.cs | 17 +-
dotnet/src/webdriver/IWrapsElement.cs | 17 +-
dotnet/src/webdriver/IWritableCapabilities.cs | 31 +-
dotnet/src/webdriver/InitializationScript.cs | 101 +-
.../webdriver/InsecureCertificateException.cs | 63 +-
.../webdriver/Interactions/ActionBuilder.cs | 177 +-
.../webdriver/Interactions/ActionSequence.cs | 169 +-
dotnet/src/webdriver/Interactions/Actions.cs | 1081 +++---
dotnet/src/webdriver/Interactions/IAction.cs | 17 +-
.../webdriver/Interactions/ICoordinates.cs | 41 +-
.../src/webdriver/Interactions/InputDevice.cs | 127 +-
.../webdriver/Interactions/InputDeviceKind.cs | 41 +-
.../src/webdriver/Interactions/Interaction.cs | 59 +-
.../webdriver/Interactions/KeyInputDevice.cs | 169 +-
.../Interactions/PauseInteraction.cs | 101 +-
.../Interactions/PointerInputDevice.cs | 909 +++--
.../Interactions/WheelInputDevice.cs | 323 +-
.../src/webdriver/Internal/AndroidOptions.cs | 55 +-
.../webdriver/Internal/Base64UrlEncoder.cs | 247 +-
.../src/webdriver/Internal/FileUtilities.cs | 301 +-
.../src/webdriver/Internal/IFindsElement.cs | 37 +-
.../Internal/IHasCapabilitiesDictionary.cs | 17 +-
.../Internal/IWebDriverObjectReference.cs | 27 +-
.../Internal/Logging/ConsoleLogHandler.cs | 15 +-
.../Internal/Logging/FileLogHandler.cs | 163 +-
.../webdriver/Internal/Logging/ILogContext.cs | 117 +-
.../webdriver/Internal/Logging/ILogHandler.cs | 19 +-
.../Internal/Logging/ILogHandlerList.cs | 43 +-
.../src/webdriver/Internal/Logging/ILogger.cs | 87 +-
dotnet/src/webdriver/Internal/Logging/Log.cs | 175 +-
.../webdriver/Internal/Logging/LogContext.cs | 195 +-
.../Internal/Logging/LogContextManager.cs | 31 +-
.../webdriver/Internal/Logging/LogEvent.cs | 69 +-
.../Internal/Logging/LogEventLevel.cs | 57 +-
.../Internal/Logging/LogHandlerList.cs | 63 +-
.../src/webdriver/Internal/Logging/Logger.cs | 81 +-
.../Internal/Logging/TextWriterHandler.cs | 27 +-
.../webdriver/Internal/NullableAttributes.cs | 257 +-
.../src/webdriver/Internal/PortUtilities.cs | 51 +-
.../webdriver/Internal/ResourceUtilities.cs | 175 +-
.../Internal/ResponseValueJsonConverter.cs | 183 +-
.../Internal/ReturnedCapabilities.cs | 173 +-
.../src/webdriver/Internal/ReturnedCookie.cs | 109 +-
.../webdriver/Internal/TrimmingAttributes.cs | 757 +++--
.../webdriver/InvalidCookieDomainException.cs | 63 +-
.../webdriver/InvalidElementStateException.cs | 63 +-
.../src/webdriver/InvalidSelectorException.cs | 91 +-
.../JavaScriptCallbackExecutedEventArgs.cs | 43 +-
.../JavaScriptConsoleApiCalledEventArgs.cs | 55 +-
dotnet/src/webdriver/JavaScriptEngine.cs | 689 ++--
dotnet/src/webdriver/JavaScriptException.cs | 63 +-
.../JavaScriptExceptionThrownEventArgs.cs | 31 +-
dotnet/src/webdriver/Keys.cs | 807 +++--
dotnet/src/webdriver/LogEntry.cs | 113 +-
dotnet/src/webdriver/LogLevel.cs | 57 +-
dotnet/src/webdriver/LogType.cs | 57 +-
dotnet/src/webdriver/Logs.cs | 113 +-
.../MoveTargetOutOfBoundsException.cs | 65 +-
dotnet/src/webdriver/Navigator.cs | 233 +-
.../webdriver/NetworkAuthenticationHandler.cs | 33 +-
dotnet/src/webdriver/NetworkManager.cs | 389 ++-
dotnet/src/webdriver/NetworkRequestHandler.cs | 45 +-
.../webdriver/NetworkRequestSentEventArgs.cs | 79 +-
.../src/webdriver/NetworkResponseHandler.cs | 35 +-
.../NetworkResponseReceivedEventArgs.cs | 101 +-
.../src/webdriver/NoAlertPresentException.cs | 63 +-
dotnet/src/webdriver/NoSuchCookieException.cs | 63 +-
dotnet/src/webdriver/NoSuchDriverException.cs | 93 +-
.../src/webdriver/NoSuchElementException.cs | 93 +-
dotnet/src/webdriver/NoSuchFrameException.cs | 63 +-
.../webdriver/NoSuchShadowRootException.cs | 63 +-
dotnet/src/webdriver/NoSuchWindowException.cs | 63 +-
dotnet/src/webdriver/NotFoundException.cs | 63 +-
dotnet/src/webdriver/OptionsManager.cs | 73 +-
dotnet/src/webdriver/PasswordCredentials.cs | 57 +-
dotnet/src/webdriver/PinnedScript.cs | 103 +-
dotnet/src/webdriver/Platform.cs | 321 +-
dotnet/src/webdriver/PrintDocument.cs | 75 +-
dotnet/src/webdriver/PrintOptions.cs | 615 ++--
dotnet/src/webdriver/Proxy.cs | 825 +++--
dotnet/src/webdriver/RelativeBy.cs | 623 ++--
.../webdriver/Remote/DesiredCapabilities.cs | 415 ++-
.../Remote/DriverServiceCommandExecutor.cs | 235 +-
.../webdriver/Remote/HttpCommandExecutor.cs | 683 ++--
dotnet/src/webdriver/Remote/ICommandServer.cs | 17 +-
.../src/webdriver/Remote/LocalFileDetector.cs | 27 +-
.../Remote/ReadOnlyDesiredCapabilities.cs | 311 +-
.../webdriver/Remote/RemoteSessionSettings.cs | 393 ++-
.../src/webdriver/Remote/RemoteWebDriver.cs | 1017 +++---
.../SendingRemoteHttpRequestEventArgs.cs | 115 +-
.../W3CWireProtocolCommandInfoRepository.cs | 211 +-
dotnet/src/webdriver/Response.cs | 279 +-
dotnet/src/webdriver/Safari/SafariDriver.cs | 415 ++-
.../webdriver/Safari/SafariDriverService.cs | 171 +-
dotnet/src/webdriver/Safari/SafariOptions.cs | 151 +-
dotnet/src/webdriver/ScreenOrientation.cs | 25 +-
dotnet/src/webdriver/Screenshot.cs | 53 +-
dotnet/src/webdriver/SeleniumManager.cs | 371 ++-
dotnet/src/webdriver/SessionId.cs | 77 +-
dotnet/src/webdriver/ShadowRoot.cs | 179 +-
dotnet/src/webdriver/StackTraceElement.cs | 173 +-
.../StaleElementReferenceException.cs | 91 +-
.../src/webdriver/Support/DefaultWait{T}.cs | 305 +-
dotnet/src/webdriver/Support/IClock.cs | 41 +-
dotnet/src/webdriver/Support/IWait{T}.cs | 67 +-
dotnet/src/webdriver/Support/SystemClock.cs | 49 +-
dotnet/src/webdriver/Support/WebDriverWait.cs | 69 +-
dotnet/src/webdriver/TargetLocator.cs | 331 +-
dotnet/src/webdriver/Timeouts.cs | 205 +-
.../webdriver/UnableToSetCookieException.cs | 63 +-
.../src/webdriver/UnhandledAlertException.cs | 95 +-
dotnet/src/webdriver/UnknownErrorException.cs | 41 +-
.../src/webdriver/UnknownMethodException.cs | 37 +-
.../UnsupportedOperationException.cs | 39 +-
dotnet/src/webdriver/UserAgent.cs | 63 +-
.../src/webdriver/VirtualAuth/Credential.cs | 215 +-
.../VirtualAuth/IHasVirtualAuthenticator.cs | 111 +-
.../VirtualAuthenticatorOptions.cs | 259 +-
dotnet/src/webdriver/WebDriver.cs | 1759 +++++-----
.../webdriver/WebDriverArgumentException.cs | 63 +-
dotnet/src/webdriver/WebDriverError.cs | 377 ++-
dotnet/src/webdriver/WebDriverException.cs | 81 +-
dotnet/src/webdriver/WebDriverResult.cs | 299 +-
.../webdriver/WebDriverTimeoutException.cs | 63 +-
dotnet/src/webdriver/WebElement.cs | 1161 ++++---
dotnet/src/webdriver/WebElementFactory.cs | 125 +-
dotnet/src/webdriver/Window.cs | 145 +-
dotnet/src/webdriver/WindowType.cs | 25 +-
dotnet/src/webdriver/XPathLookupException.cs | 63 +-
dotnet/test/chrome/ChromeSpecificTests.cs | 17 +-
dotnet/test/common/AlertsTest.cs | 869 +++--
dotnet/test/common/AssemblyFixture.cs | 47 +-
dotnet/test/common/Browser.cs | 21 +-
dotnet/test/common/ChildrenFindingTest.cs | 747 +++--
dotnet/test/common/ClearTest.cs | 363 +-
dotnet/test/common/ClickScrollingTest.cs | 421 ++-
dotnet/test/common/ClickTest.cs | 547 ++-
dotnet/test/common/CommandTests.cs | 23 +-
dotnet/test/common/ContentEditableTest.cs | 219 +-
.../test/common/CookieImplementationTest.cs | 1479 +++++----
dotnet/test/common/CookieTest.cs | 151 +-
dotnet/test/common/CorrectEventFiringTest.cs | 765 +++--
dotnet/test/common/CssValueTest.cs | 65 +-
.../DefaultSafariDriver.cs | 27 +-
.../DevChannelChromeDriver.cs | 37 +-
.../DevChannelEdgeDriver.cs | 37 +-
.../EdgeInternetExplorerModeDriver.cs | 43 +-
.../NightlyChannelFirefoxDriver.cs | 43 +-
.../SafariTechnologyPreviewDriver.cs | 49 +-
.../StableChannelChromeDriver.cs | 37 +-
.../StableChannelEdgeDriver.cs | 39 +-
.../StableChannelFirefoxDriver.cs | 43 +-
.../StableChannelRemoteChromeDriver.cs | 13 +-
.../IgnoreBrowserAttribute.cs | 165 +-
.../IgnorePlatformAttribute.cs | 143 +-
.../IgnoreTargetAttribute.cs | 91 +-
.../NeedsFreshDriverAttribute.cs | 59 +-
.../common/DevTools/DevToolsConsoleTest.cs | 53 +-
.../test/common/DevTools/DevToolsLogTest.cs | 61 +-
.../common/DevTools/DevToolsNetworkTest.cs | 777 +++--
.../DevTools/DevToolsPerformanceTest.cs | 189 +-
.../common/DevTools/DevToolsProfilerTest.cs | 207 +-
.../common/DevTools/DevToolsSecurityTest.cs | 89 +-
.../test/common/DevTools/DevToolsTabsTest.cs | 49 +-
.../common/DevTools/DevToolsTargetTest.cs | 303 +-
.../common/DevTools/DevToolsTestFixture.cs | 55 +-
dotnet/test/common/DownloadsTest.cs | 143 +-
.../test/common/DriverElementFindingTest.cs | 241 +-
dotnet/test/common/DriverTestFixture.cs | 311 +-
dotnet/test/common/ElementAttributeTest.cs | 693 ++--
.../test/common/ElementElementFindingTest.cs | 297 +-
dotnet/test/common/ElementEqualityTest.cs | 83 +-
dotnet/test/common/ElementFindingTest.cs | 1677 +++++-----
dotnet/test/common/ElementPropertyTest.cs | 43 +-
dotnet/test/common/ElementSelectingTest.cs | 499 ++-
.../test/common/Environment/DriverConfig.cs | 31 +-
.../test/common/Environment/DriverFactory.cs | 331 +-
.../Environment/DriverStartingEventArgs.cs | 25 +-
.../common/Environment/EnvironmentManager.cs | 411 ++-
dotnet/test/common/Environment/InlinePage.cs | 137 +-
.../Environment/RemoteSeleniumServer.cs | 121 +-
.../common/Environment/TestEnvironment.cs | 41 +-
.../test/common/Environment/TestWebServer.cs | 191 +-
.../common/Environment/TestWebServerConfig.cs | 23 +-
dotnet/test/common/Environment/UrlBuilder.cs | 193 +-
.../test/common/Environment/WebsiteConfig.cs | 29 +-
dotnet/test/common/ErrorsTest.cs | 33 +-
.../common/ExecutingAsyncJavascriptTest.cs | 591 ++--
dotnet/test/common/ExecutingJavascriptTest.cs | 1479 +++++----
dotnet/test/common/FormHandlingTests.cs | 701 ++--
dotnet/test/common/FrameSwitchingTest.cs | 981 +++---
dotnet/test/common/GetLogsTest.cs | 137 +-
.../test/common/GetMultipleAttributeTest.cs | 75 +-
dotnet/test/common/I18Test.cs | 121 +-
dotnet/test/common/ImplicitWaitTest.cs | 215 +-
.../common/Interactions/ActionBuilderTest.cs | 93 +-
.../BasicKeyboardInterfaceTest.cs | 511 ++-
.../Interactions/BasicMouseInterfaceTest.cs | 727 ++--
.../Interactions/BasicWheelInterfaceTest.cs | 261 +-
.../Interactions/CombinedInputActionsTest.cs | 665 ++--
.../common/Interactions/DragAndDropTest.cs | 393 ++-
.../Internal/Logging/FileLogHandlerTest.cs | 175 +-
.../test/common/Internal/Logging/LogTest.cs | 345 +-
.../common/JavascriptEnabledBrowserTest.cs | 331 +-
dotnet/test/common/MiscTest.cs | 169 +-
dotnet/test/common/NavigationTest.cs | 303 +-
.../test/common/NetworkInterceptionTests.cs | 135 +-
.../test/common/ObjectStateAssumptionsTest.cs | 77 +-
dotnet/test/common/PageLoadingTest.cs | 741 +++--
.../test/common/PartialLinkTextMatchTest.cs | 113 +-
dotnet/test/common/PositionAndSizeTest.cs | 339 +-
dotnet/test/common/PrintTest.cs | 217 +-
dotnet/test/common/ProxySettingTest.cs | 563 ++--
dotnet/test/common/ProxyTest.cs | 537 ++-
dotnet/test/common/RelativeLocatorTest.cs | 361 +-
.../test/common/SelectElementHandlingTest.cs | 253 +-
dotnet/test/common/SessionHandlingTest.cs | 231 +-
dotnet/test/common/ShadowRootHandlingTest.cs | 99 +-
dotnet/test/common/SlowLoadingPageTest.cs | 79 +-
.../test/common/StaleElementReferenceTest.cs | 93 +-
dotnet/test/common/StubDriver.cs | 143 +-
dotnet/test/common/SvgDocumentTest.cs | 55 +-
dotnet/test/common/SvgElementTest.cs | 93 +-
dotnet/test/common/TagNameTest.cs | 19 +-
dotnet/test/common/TakesScreenshotTest.cs | 635 ++--
dotnet/test/common/TargetLocatorTest.cs | 223 +-
dotnet/test/common/TestUtilities.cs | 147 +-
dotnet/test/common/TextHandlingTest.cs | 801 +++--
dotnet/test/common/TextPagesTest.cs | 65 +-
.../test/common/TimeoutDriverOptionsTest.cs | 177 +-
dotnet/test/common/TypingTest.cs | 1305 ++++----
.../common/UnexpectedAlertBehaviorTest.cs | 173 +-
dotnet/test/common/UploadTest.cs | 193 +-
.../VirtualAuthn/VirtualAuthenticatorTest.cs | 881 +++--
dotnet/test/common/VisibilityTest.cs | 475 ++-
dotnet/test/common/WebElementTest.cs | 289 +-
dotnet/test/common/WindowSwitchingTest.cs | 699 ++--
dotnet/test/common/WindowTest.cs | 407 ++-
dotnet/test/edge/AssemblyTeardown.cs | 29 +-
dotnet/test/edge/EdgeSpecificTests.cs | 9 +-
dotnet/test/firefox/AssemblyTeardown.cs | 29 +-
dotnet/test/firefox/FirefoxDriverTest.cs | 543 ++-
.../test/firefox/FirefoxProfileManagerTest.cs | 75 +-
dotnet/test/firefox/FirefoxProfileTests.cs | 125 +-
dotnet/test/ie/AssemblyTeardown.cs | 29 +-
dotnet/test/ie/IeSpecificTests.cs | 617 ++--
dotnet/test/remote/AssemblyTeardown.cs | 37 +-
dotnet/test/remote/ChromeRemoteWebDriver.cs | 15 +-
dotnet/test/remote/EdgeRemoteWebDriver.cs | 15 +-
dotnet/test/remote/FirefoxRemoteWebDriver.cs | 15 +-
.../test/remote/RemoteSessionCreationTests.cs | 195 +-
.../remote/RemoteWebDriverSpecificTests.cs | 109 +-
.../TestInternetExplorerRemoteWebDriver.cs | 17 +-
dotnet/test/safari/SafariSpecificTests.cs | 9 +-
.../Events/EventFiringWebDriverElementTest.cs | 31 +-
.../Events/EventFiringWebDriverTest.cs | 505 ++-
.../Extensions/ExecuteJavaScriptTest.cs | 235 +-
dotnet/test/support/UI/DefaultWaitTest.cs | 263 +-
dotnet/test/support/UI/HandCrankClock.cs | 33 +-
.../test/support/UI/LoadableComponentTests.cs | 175 +-
.../test/support/UI/PopupWindowFinderTest.cs | 179 +-
dotnet/test/support/UI/SelectBrowserTests.cs | 789 +++--
dotnet/test/support/UI/SelectTests.cs | 893 +++--
.../support/UI/SlowLoadableComponentTest.cs | 251 +-
dotnet/test/support/UI/WebDriverWaitTest.cs | 241 +-
419 files changed, 46153 insertions(+), 46569 deletions(-)
create mode 100644 dotnet/.editorconfig
diff --git a/dotnet/.editorconfig b/dotnet/.editorconfig
new file mode 100644
index 0000000000000..e25f2c3ede71c
--- /dev/null
+++ b/dotnet/.editorconfig
@@ -0,0 +1,2 @@
+[*.cs]
+csharp_style_namespace_declarations=file_scoped:suggestion
diff --git a/dotnet/src/support/Events/EventFiringWebDriver.cs b/dotnet/src/support/Events/EventFiringWebDriver.cs
index 9f0355cc204cd..a23c4a04bf9ed 100644
--- a/dotnet/src/support/Events/EventFiringWebDriver.cs
+++ b/dotnet/src/support/Events/EventFiringWebDriver.cs
@@ -23,269 +23,154 @@
using System.Drawing;
using System.Threading.Tasks;
-namespace OpenQA.Selenium.Support.Events
+namespace OpenQA.Selenium.Support.Events;
+
+///
+/// A wrapper around an arbitrary WebDriver instance which supports registering for
+/// events, e.g. for logging purposes.
+///
+public class EventFiringWebDriver : IWebDriver, IJavaScriptExecutor, ITakesScreenshot, IWrapsDriver
{
///
- /// A wrapper around an arbitrary WebDriver instance which supports registering for
- /// events, e.g. for logging purposes.
+ /// Initializes a new instance of the class.
///
- public class EventFiringWebDriver : IWebDriver, IJavaScriptExecutor, ITakesScreenshot, IWrapsDriver
+ /// The driver to register events for.
+ /// If is .
+ public EventFiringWebDriver(IWebDriver parentDriver)
{
- ///
- /// Initializes a new instance of the class.
- ///
- /// The driver to register events for.
- /// If is .
- public EventFiringWebDriver(IWebDriver parentDriver)
- {
- this.WrappedDriver = parentDriver ?? throw new ArgumentNullException(nameof(parentDriver));
- }
-
- ///
- /// Fires before the driver begins navigation.
- ///
- public event EventHandler? Navigating;
-
- ///
- /// Fires after the driver completes navigation
- ///
- public event EventHandler? Navigated;
-
- ///
- /// Fires before the driver begins navigation back one entry in the browser history list.
- ///
- public event EventHandler? NavigatingBack;
-
- ///
- /// Fires after the driver completes navigation back one entry in the browser history list.
- ///
- public event EventHandler? NavigatedBack;
-
- ///
- /// Fires before the driver begins navigation forward one entry in the browser history list.
- ///
- public event EventHandler? NavigatingForward;
+ this.WrappedDriver = parentDriver ?? throw new ArgumentNullException(nameof(parentDriver));
+ }
- ///
- /// Fires after the driver completes navigation forward one entry in the browser history list.
- ///
- public event EventHandler? NavigatedForward;
+ ///
+ /// Fires before the driver begins navigation.
+ ///
+ public event EventHandler? Navigating;
- ///
- /// Fires before the driver clicks on an element.
- ///
- public event EventHandler? ElementClicking;
+ ///
+ /// Fires after the driver completes navigation
+ ///
+ public event EventHandler? Navigated;
- ///
- /// Fires after the driver has clicked on an element.
- ///
- public event EventHandler? ElementClicked;
+ ///
+ /// Fires before the driver begins navigation back one entry in the browser history list.
+ ///
+ public event EventHandler? NavigatingBack;
- ///
- /// Fires before the driver changes the value of an element via Clear(), SendKeys() or Toggle().
- ///
- public event EventHandler? ElementValueChanging;
+ ///
+ /// Fires after the driver completes navigation back one entry in the browser history list.
+ ///
+ public event EventHandler? NavigatedBack;
- ///
- /// Fires after the driver has changed the value of an element via Clear(), SendKeys() or Toggle().
- ///
- public event EventHandler? ElementValueChanged;
+ ///
+ /// Fires before the driver begins navigation forward one entry in the browser history list.
+ ///
+ public event EventHandler? NavigatingForward;
- ///
- /// Fires before the driver starts to find an element.
- ///
- public event EventHandler? FindingElement;
+ ///
+ /// Fires after the driver completes navigation forward one entry in the browser history list.
+ ///
+ public event EventHandler? NavigatedForward;
- ///
- /// Fires after the driver completes finding an element.
- ///
- public event EventHandler? FindElementCompleted;
+ ///
+ /// Fires before the driver clicks on an element.
+ ///
+ public event EventHandler? ElementClicking;
- ///
- /// Fires before the driver starts to get a shadow root.
- ///
- public event EventHandler? GettingShadowRoot;
+ ///
+ /// Fires after the driver has clicked on an element.
+ ///
+ public event EventHandler? ElementClicked;
- ///
- /// Fires after the driver completes getting a shadow root.
- ///
- public event EventHandler? GetShadowRootCompleted;
+ ///
+ /// Fires before the driver changes the value of an element via Clear(), SendKeys() or Toggle().
+ ///
+ public event EventHandler? ElementValueChanging;
- ///
- /// Fires before a script is executed.
- ///
- public event EventHandler? ScriptExecuting;
+ ///
+ /// Fires after the driver has changed the value of an element via Clear(), SendKeys() or Toggle().
+ ///
+ public event EventHandler? ElementValueChanged;
- ///
- /// Fires after a script is executed.
- ///
- public event EventHandler? ScriptExecuted;
+ ///
+ /// Fires before the driver starts to find an element.
+ ///
+ public event EventHandler? FindingElement;
- ///
- /// Fires when an exception is thrown.
- ///
- public event EventHandler? ExceptionThrown;
+ ///
+ /// Fires after the driver completes finding an element.
+ ///
+ public event EventHandler? FindElementCompleted;
- ///
- /// Gets the wrapped by this EventsFiringWebDriver instance.
- ///
- public IWebDriver WrappedDriver { get; }
+ ///
+ /// Fires before the driver starts to get a shadow root.
+ ///
+ public event EventHandler? GettingShadowRoot;
- ///
- /// Gets or sets the URL the browser is currently displaying.
- ///
- ///
- /// Setting the property will load a new web page in the current browser window.
- /// This is done using an HTTP GET operation, and the method will block until the
- /// load is complete. This will follow redirects issued either by the server or
- /// as a meta-redirect from within the returned HTML. Should a meta-redirect "rest"
- /// for any duration of time, it is best to wait until this timeout is over, since
- /// should the underlying page change while your test is executing the results of
- /// future calls against this interface will be against the freshly loaded page.
- ///
- ///
- ///
- public string Url
- {
- get
- {
- string url;
- try
- {
- url = this.WrappedDriver.Url;
- }
- catch (Exception ex)
- {
- this.OnException(new WebDriverExceptionEventArgs(this.WrappedDriver, ex));
- throw;
- }
+ ///
+ /// Fires after the driver completes getting a shadow root.
+ ///
+ public event EventHandler? GetShadowRootCompleted;
- return url;
- }
+ ///
+ /// Fires before a script is executed.
+ ///
+ public event EventHandler? ScriptExecuting;
- set
- {
- try
- {
- WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.WrappedDriver, value);
- this.OnNavigating(e);
- this.WrappedDriver.Url = value;
- this.OnNavigated(e);
- }
- catch (Exception ex)
- {
- this.OnException(new WebDriverExceptionEventArgs(this.WrappedDriver, ex));
- throw;
- }
- }
- }
+ ///
+ /// Fires after a script is executed.
+ ///
+ public event EventHandler? ScriptExecuted;
- ///
- /// Gets the title of the current browser window.
- ///
- public string Title
- {
- get
- {
- string title;
- try
- {
- title = this.WrappedDriver.Title;
- }
- catch (Exception ex)
- {
- this.OnException(new WebDriverExceptionEventArgs(this.WrappedDriver, ex));
- throw;
- }
+ ///
+ /// Fires when an exception is thrown.
+ ///
+ public event EventHandler? ExceptionThrown;
- return title;
- }
- }
+ ///
+ /// Gets the wrapped by this EventsFiringWebDriver instance.
+ ///
+ public IWebDriver WrappedDriver { get; }
- ///
- /// Gets the source of the page last loaded by the browser.
- ///
- ///
- /// If the page has been modified after loading (for example, by JavaScript)
- /// there is no guarantee that the returned text is that of the modified page.
- /// Please consult the documentation of the particular driver being used to
- /// determine whether the returned text reflects the current state of the page
- /// or the text last sent by the web server. The page source returned is a
- /// representation of the underlying DOM: do not expect it to be formatted
- /// or escaped in the same way as the response sent from the web server.
- ///
- public string PageSource
+ ///
+ /// Gets or sets the URL the browser is currently displaying.
+ ///
+ ///
+ /// Setting the property will load a new web page in the current browser window.
+ /// This is done using an HTTP GET operation, and the method will block until the
+ /// load is complete. This will follow redirects issued either by the server or
+ /// as a meta-redirect from within the returned HTML. Should a meta-redirect "rest"
+ /// for any duration of time, it is best to wait until this timeout is over, since
+ /// should the underlying page change while your test is executing the results of
+ /// future calls against this interface will be against the freshly loaded page.
+ ///
+ ///
+ ///
+ public string Url
+ {
+ get
{
- get
+ string url;
+ try
{
- string source;
- try
- {
- source = this.WrappedDriver.PageSource;
- }
- catch (Exception ex)
- {
- this.OnException(new WebDriverExceptionEventArgs(this.WrappedDriver, ex));
- throw;
- }
-
- return source;
+ url = this.WrappedDriver.Url;
}
- }
-
- ///
- /// Gets the current window handle, which is an opaque handle to this
- /// window that uniquely identifies it within this driver instance.
- ///
- public string CurrentWindowHandle
- {
- get
+ catch (Exception ex)
{
- string handle;
- try
- {
- handle = this.WrappedDriver.CurrentWindowHandle;
- }
- catch (Exception ex)
- {
- this.OnException(new WebDriverExceptionEventArgs(this.WrappedDriver, ex));
- throw;
- }
-
- return handle;
+ this.OnException(new WebDriverExceptionEventArgs(this.WrappedDriver, ex));
+ throw;
}
- }
-
- ///
- /// Gets the window handles of open browser windows.
- ///
- public ReadOnlyCollection WindowHandles
- {
- get
- {
- ReadOnlyCollection handles;
- try
- {
- handles = this.WrappedDriver.WindowHandles;
- }
- catch (Exception ex)
- {
- this.OnException(new WebDriverExceptionEventArgs(this.WrappedDriver, ex));
- throw;
- }
- return handles;
- }
+ return url;
}
- ///
- /// Close the current window, quitting the browser if it is the last window currently open.
- ///
- public void Close()
+ set
{
try
{
- this.WrappedDriver.Close();
+ WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.WrappedDriver, value);
+ this.OnNavigating(e);
+ this.WrappedDriver.Url = value;
+ this.OnNavigated(e);
}
catch (Exception ex)
{
@@ -293,69 +178,50 @@ public void Close()
throw;
}
}
+ }
- ///
- /// Quits this driver, closing every associated window.
- ///
- public void Quit()
+ ///
+ /// Gets the title of the current browser window.
+ ///
+ public string Title
+ {
+ get
{
+ string title;
try
{
- this.WrappedDriver.Quit();
+ title = this.WrappedDriver.Title;
}
catch (Exception ex)
{
this.OnException(new WebDriverExceptionEventArgs(this.WrappedDriver, ex));
throw;
}
- }
-
- ///
- /// Instructs the driver to change its settings.
- ///
- /// An object allowing the user to change
- /// the settings of the driver.
- public IOptions Manage()
- {
- return new EventFiringOptions(this);
- }
-
- ///
- /// Instructs the driver to navigate the browser to another location.
- ///
- /// An object allowing the user to access
- /// the browser's history and to navigate to a given URL.
- public INavigation Navigate()
- {
- return new EventFiringNavigation(this);
- }
- ///
- /// Instructs the driver to send future commands to a different frame or window.
- ///
- /// An object which can be used to select
- /// a frame or window.
- public ITargetLocator SwitchTo()
- {
- return new EventFiringTargetLocator(this);
+ return title;
}
+ }
- ///
- /// Find the first using the given method.
- ///
- /// The locating mechanism to use.
- /// The first matching on the current context.
- /// If no element matches the criteria.
- public IWebElement FindElement(By by)
+ ///
+ /// Gets the source of the page last loaded by the browser.
+ ///
+ ///
+ /// If the page has been modified after loading (for example, by JavaScript)
+ /// there is no guarantee that the returned text is that of the modified page.
+ /// Please consult the documentation of the particular driver being used to
+ /// determine whether the returned text reflects the current state of the page
+ /// or the text last sent by the web server. The page source returned is a
+ /// representation of the underlying DOM: do not expect it to be formatted
+ /// or escaped in the same way as the response sent from the web server.
+ ///
+ public string PageSource
+ {
+ get
{
- IWebElement wrappedElement;
+ string source;
try
{
- FindElementEventArgs e = new FindElementEventArgs(this.WrappedDriver, by);
- this.OnFindingElement(e);
- IWebElement element = this.WrappedDriver.FindElement(by);
- this.OnFindElementCompleted(e);
- wrappedElement = this.WrapElement(element);
+ source = this.WrappedDriver.PageSource;
}
catch (Exception ex)
{
@@ -363,32 +229,22 @@ public IWebElement FindElement(By by)
throw;
}
- return wrappedElement;
+ return source;
}
+ }
- ///
- /// Find all IWebElements within the current context
- /// using the given mechanism.
- ///
- /// The locating mechanism to use.
- /// A of all WebElements
- /// matching the current criteria, or an empty list if nothing matches.
- public ReadOnlyCollection FindElements(By by)
+ ///
+ /// Gets the current window handle, which is an opaque handle to this
+ /// window that uniquely identifies it within this driver instance.
+ ///
+ public string CurrentWindowHandle
+ {
+ get
{
+ string handle;
try
{
- FindElementEventArgs e = new FindElementEventArgs(this.WrappedDriver, by);
- this.OnFindingElement(e);
- ReadOnlyCollection elements = this.WrappedDriver.FindElements(by);
- this.OnFindElementCompleted(e);
-
- List wrappedElementList = new List(elements.Count);
- foreach (IWebElement element in elements)
- {
- IWebElement wrappedElement = this.WrapElement(element);
- wrappedElementList.Add(wrappedElement);
- }
- return wrappedElementList.AsReadOnly();
+ handle = this.WrappedDriver.CurrentWindowHandle;
}
catch (Exception ex)
{
@@ -396,68 +252,21 @@ public ReadOnlyCollection FindElements(By by)
throw;
}
+ return handle;
}
+ }
- ///
- /// Frees all managed and unmanaged resources used by this instance.
- ///
- public void Dispose()
- {
- this.Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- ///
- /// Executes JavaScript in the context of the currently selected frame or window.
- ///
- /// The JavaScript code to execute.
- /// The arguments to the script.
- /// The value returned by the script.
- ///
- ///
- /// The 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:
- ///
- ///
- ///
- /// For an HTML element, this method returns a
- /// For a number, a is returned
- /// For a boolean, a is returned
- /// For all other cases a is returned.
- /// For an array,we check the first element, and attempt to return a
- /// of that type, following the rules above. Nested lists are not
- /// supported.
- /// If the value is null or there is no return value,
- /// is returned.
- ///
- ///
- ///
- /// Arguments must be a number (which will be converted to a ),
- /// a , a or a ,
- /// or a .
- /// 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"
- ///
- ///
- public object? ExecuteScript(string script, params object?[] args)
+ ///
+ /// Gets the window handles of open browser windows.
+ ///
+ public ReadOnlyCollection WindowHandles
+ {
+ get
{
- if (this.WrappedDriver is not IJavaScriptExecutor javascriptDriver)
- {
- throw new NotSupportedException("Underlying driver instance does not support executing JavaScript");
- }
-
- object? scriptResult;
+ ReadOnlyCollection handles;
try
{
- object?[] unwrappedArgs = UnwrapElementArguments(args);
-
- WebDriverScriptEventArgs e = new WebDriverScriptEventArgs(this.WrappedDriver, script);
- this.OnScriptExecuting(e);
- scriptResult = javascriptDriver.ExecuteScript(script, unwrappedArgs);
- this.OnScriptExecuted(e);
+ handles = this.WrappedDriver.WindowHandles;
}
catch (Exception ex)
{
@@ -465,1198 +274,1154 @@ public void Dispose()
throw;
}
- return scriptResult;
+ return handles;
}
+ }
-
- ///
- /// Executes JavaScript in the context of the currently selected frame or window.
- ///
- /// A object containing the code to execute.
- /// The arguments to the script.
- /// The value returned by the script.
- /// If is .
- ///
- ///
- /// The 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:
- ///
- ///
- ///
- /// For an HTML element, this method returns a
- /// For a number, a is returned
- /// For a boolean, a is returned
- /// For all other cases a is returned.
- /// For an array,we check the first element, and attempt to return a
- /// of that type, following the rules above. Nested lists are not
- /// supported.
- /// If the value is null or there is no return value,
- /// is returned.
- ///
- ///
- ///
- /// Arguments must be a number (which will be converted to a ),
- /// a , a or a ,
- /// or a .
- /// 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"
- ///
- ///
- public object? ExecuteScript(PinnedScript script, params object?[] args)
+ ///
+ /// Close the current window, quitting the browser if it is the last window currently open.
+ ///
+ public void Close()
+ {
+ try
{
- if (script == null)
- {
- throw new ArgumentNullException(nameof(script));
- }
+ this.WrappedDriver.Close();
+ }
+ catch (Exception ex)
+ {
+ this.OnException(new WebDriverExceptionEventArgs(this.WrappedDriver, ex));
+ throw;
+ }
+ }
- if (this.WrappedDriver is not IJavaScriptExecutor javascriptDriver)
- {
- throw new NotSupportedException("Underlying driver instance does not support executing JavaScript");
- }
+ ///
+ /// Quits this driver, closing every associated window.
+ ///
+ public void Quit()
+ {
+ try
+ {
+ this.WrappedDriver.Quit();
+ }
+ catch (Exception ex)
+ {
+ this.OnException(new WebDriverExceptionEventArgs(this.WrappedDriver, ex));
+ throw;
+ }
+ }
- object? scriptResult;
- try
- {
- object?[] unwrappedArgs = UnwrapElementArguments(args);
+ ///
+ /// Instructs the driver to change its settings.
+ ///
+ /// An object allowing the user to change
+ /// the settings of the driver.
+ public IOptions Manage()
+ {
+ return new EventFiringOptions(this);
+ }
- WebDriverScriptEventArgs e = new WebDriverScriptEventArgs(this.WrappedDriver, script.Source);
- this.OnScriptExecuting(e);
- scriptResult = javascriptDriver.ExecuteScript(script, unwrappedArgs);
- this.OnScriptExecuted(e);
- }
- catch (Exception ex)
- {
- this.OnException(new WebDriverExceptionEventArgs(this.WrappedDriver, ex));
- throw;
- }
+ ///
+ /// Instructs the driver to navigate the browser to another location.
+ ///
+ /// An object allowing the user to access
+ /// the browser's history and to navigate to a given URL.
+ public INavigation Navigate()
+ {
+ return new EventFiringNavigation(this);
+ }
+
+ ///
+ /// Instructs the driver to send future commands to a different frame or window.
+ ///
+ /// An object which can be used to select
+ /// a frame or window.
+ public ITargetLocator SwitchTo()
+ {
+ return new EventFiringTargetLocator(this);
+ }
- return scriptResult;
+ ///
+ /// Find the first using the given method.
+ ///
+ /// The locating mechanism to use.
+ /// The first matching on the current context.
+ /// If no element matches the criteria.
+ public IWebElement FindElement(By by)
+ {
+ IWebElement wrappedElement;
+ try
+ {
+ FindElementEventArgs e = new FindElementEventArgs(this.WrappedDriver, by);
+ this.OnFindingElement(e);
+ IWebElement element = this.WrappedDriver.FindElement(by);
+ this.OnFindElementCompleted(e);
+ wrappedElement = this.WrapElement(element);
+ }
+ catch (Exception ex)
+ {
+ this.OnException(new WebDriverExceptionEventArgs(this.WrappedDriver, ex));
+ throw;
}
- ///
- /// Executes JavaScript asynchronously in the context of the currently selected frame or window.
- ///
- /// The JavaScript code to execute.
- /// The arguments to the script.
- /// The value returned by the script.
- public object? ExecuteAsyncScript(string script, params object?[] args)
+ return wrappedElement;
+ }
+
+ ///
+ /// Find all IWebElements within the current context
+ /// using the given mechanism.
+ ///
+ /// The locating mechanism to use.
+ /// A of all WebElements
+ /// matching the current criteria, or an empty list if nothing matches.
+ public ReadOnlyCollection FindElements(By by)
+ {
+ try
{
- if (this.WrappedDriver is not IJavaScriptExecutor javascriptDriver)
+ FindElementEventArgs e = new FindElementEventArgs(this.WrappedDriver, by);
+ this.OnFindingElement(e);
+ ReadOnlyCollection elements = this.WrappedDriver.FindElements(by);
+ this.OnFindElementCompleted(e);
+
+ List wrappedElementList = new List(elements.Count);
+ foreach (IWebElement element in elements)
{
- throw new NotSupportedException("Underlying driver instance does not support executing JavaScript");
+ IWebElement wrappedElement = this.WrapElement(element);
+ wrappedElementList.Add(wrappedElement);
}
+ return wrappedElementList.AsReadOnly();
+ }
+ catch (Exception ex)
+ {
+ this.OnException(new WebDriverExceptionEventArgs(this.WrappedDriver, ex));
+ throw;
+ }
- object? scriptResult;
- try
- {
- object?[] unwrappedArgs = UnwrapElementArguments(args);
+ }
- WebDriverScriptEventArgs e = new WebDriverScriptEventArgs(this.WrappedDriver, script);
- this.OnScriptExecuting(e);
- scriptResult = javascriptDriver.ExecuteAsyncScript(script, unwrappedArgs);
- this.OnScriptExecuted(e);
- }
- catch (Exception ex)
- {
- this.OnException(new WebDriverExceptionEventArgs(this.WrappedDriver, ex));
- throw;
- }
+ ///
+ /// Frees all managed and unmanaged resources used by this instance.
+ ///
+ public void Dispose()
+ {
+ this.Dispose(true);
+ GC.SuppressFinalize(this);
+ }
- return scriptResult;
+ ///
+ /// Executes JavaScript in the context of the currently selected frame or window.
+ ///
+ /// The JavaScript code to execute.
+ /// The arguments to the script.
+ /// The value returned by the script.
+ ///
+ ///
+ /// The 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:
+ ///
+ ///
+ ///
+ /// For an HTML element, this method returns a
+ /// For a number, a is returned
+ /// For a boolean, a is returned
+ /// For all other cases a is returned.
+ /// For an array,we check the first element, and attempt to return a
+ /// of that type, following the rules above. Nested lists are not
+ /// supported.
+ /// If the value is null or there is no return value,
+ /// is returned.
+ ///
+ ///
+ ///
+ /// Arguments must be a number (which will be converted to a ),
+ /// a , a or a ,
+ /// or a .
+ /// 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"
+ ///
+ ///
+ public object? ExecuteScript(string script, params object?[] args)
+ {
+ if (this.WrappedDriver is not IJavaScriptExecutor javascriptDriver)
+ {
+ throw new NotSupportedException("Underlying driver instance does not support executing JavaScript");
}
- ///
- /// Gets a object representing the image of the page on the screen.
- ///
- /// A object containing the image.
- public Screenshot GetScreenshot()
+ object? scriptResult;
+ try
{
- if (this.WrappedDriver is not ITakesScreenshot screenshotDriver)
- {
- throw new NotSupportedException("Underlying driver instance does not support taking screenshots");
- }
+ object?[] unwrappedArgs = UnwrapElementArguments(args);
- return screenshotDriver.GetScreenshot();
+ WebDriverScriptEventArgs e = new WebDriverScriptEventArgs(this.WrappedDriver, script);
+ this.OnScriptExecuting(e);
+ scriptResult = javascriptDriver.ExecuteScript(script, unwrappedArgs);
+ this.OnScriptExecuted(e);
}
-
- ///
- /// Frees all managed and, optionally, unmanaged resources used by this instance.
- ///
- /// to dispose of only managed resources;
- /// to dispose of managed and unmanaged resources.
- protected virtual void Dispose(bool disposing)
+ catch (Exception ex)
{
- if (disposing)
- {
- this.WrappedDriver.Dispose();
- }
+ this.OnException(new WebDriverExceptionEventArgs(this.WrappedDriver, ex));
+ throw;
}
- ///
- /// Raises the event.
- ///
- /// A that contains the event data.
- protected virtual void OnNavigating(WebDriverNavigationEventArgs e)
+ return scriptResult;
+ }
+
+
+ ///
+ /// Executes JavaScript in the context of the currently selected frame or window.
+ ///
+ /// A object containing the code to execute.
+ /// The arguments to the script.
+ /// The value returned by the script.
+ /// If is .
+ ///
+ ///
+ /// The 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:
+ ///
+ ///
+ ///
+ /// For an HTML element, this method returns a
+ /// For a number, a is returned
+ /// For a boolean, a is returned
+ /// For all other cases a is returned.
+ /// For an array,we check the first element, and attempt to return a
+ /// of that type, following the rules above. Nested lists are not
+ /// supported.
+ /// If the value is null or there is no return value,
+ /// is returned.
+ ///
+ ///
+ ///
+ /// Arguments must be a number (which will be converted to a ),
+ /// a , a or a ,
+ /// or a .
+ /// 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"
+ ///
+ ///
+ public object? ExecuteScript(PinnedScript script, params object?[] args)
+ {
+ if (script == null)
{
- if (this.Navigating != null)
- {
- this.Navigating(this, e);
- }
+ throw new ArgumentNullException(nameof(script));
}
- ///
- /// Raises the event.
- ///
- /// A that contains the event data.
- protected virtual void OnNavigated(WebDriverNavigationEventArgs e)
+ if (this.WrappedDriver is not IJavaScriptExecutor javascriptDriver)
{
- if (this.Navigated != null)
- {
- this.Navigated(this, e);
- }
+ throw new NotSupportedException("Underlying driver instance does not support executing JavaScript");
}
- ///
- /// Raises the event.
- ///
- /// A that contains the event data.
- protected virtual void OnNavigatingBack(WebDriverNavigationEventArgs e)
+ object? scriptResult;
+ try
{
- if (this.NavigatingBack != null)
- {
- this.NavigatingBack(this, e);
- }
- }
+ object?[] unwrappedArgs = UnwrapElementArguments(args);
- ///
- /// Raises the event.
- ///
- /// A that contains the event data.
- protected virtual void OnNavigatedBack(WebDriverNavigationEventArgs e)
+ WebDriverScriptEventArgs e = new WebDriverScriptEventArgs(this.WrappedDriver, script.Source);
+ this.OnScriptExecuting(e);
+ scriptResult = javascriptDriver.ExecuteScript(script, unwrappedArgs);
+ this.OnScriptExecuted(e);
+ }
+ catch (Exception ex)
{
- if (this.NavigatedBack != null)
- {
- this.NavigatedBack(this, e);
- }
+ this.OnException(new WebDriverExceptionEventArgs(this.WrappedDriver, ex));
+ throw;
}
- ///
- /// Raises the event.
- ///
- /// A that contains the event data.
- protected virtual void OnNavigatingForward(WebDriverNavigationEventArgs e)
+ return scriptResult;
+ }
+
+ ///
+ /// Executes JavaScript asynchronously in the context of the currently selected frame or window.
+ ///
+ /// The JavaScript code to execute.
+ /// The arguments to the script.
+ /// The value returned by the script.
+ public object? ExecuteAsyncScript(string script, params object?[] args)
+ {
+ if (this.WrappedDriver is not IJavaScriptExecutor javascriptDriver)
{
- if (this.NavigatingForward != null)
- {
- this.NavigatingForward(this, e);
- }
+ throw new NotSupportedException("Underlying driver instance does not support executing JavaScript");
}
- ///
- /// Raises the event.
- ///
- /// A that contains the event data.
- protected virtual void OnNavigatedForward(WebDriverNavigationEventArgs e)
+ object? scriptResult;
+ try
{
- if (this.NavigatedForward != null)
- {
- this.NavigatedForward(this, e);
- }
+ object?[] unwrappedArgs = UnwrapElementArguments(args);
+
+ WebDriverScriptEventArgs e = new WebDriverScriptEventArgs(this.WrappedDriver, script);
+ this.OnScriptExecuting(e);
+ scriptResult = javascriptDriver.ExecuteAsyncScript(script, unwrappedArgs);
+ this.OnScriptExecuted(e);
+ }
+ catch (Exception ex)
+ {
+ this.OnException(new WebDriverExceptionEventArgs(this.WrappedDriver, ex));
+ throw;
}
- ///
- /// Raises the event.
- ///
- /// A that contains the event data.
- protected virtual void OnElementClicking(WebElementEventArgs e)
+ return scriptResult;
+ }
+
+ ///
+ /// Gets a object representing the image of the page on the screen.
+ ///
+ /// A object containing the image.
+ public Screenshot GetScreenshot()
+ {
+ if (this.WrappedDriver is not ITakesScreenshot screenshotDriver)
{
- if (this.ElementClicking != null)
- {
- this.ElementClicking(this, e);
- }
+ throw new NotSupportedException("Underlying driver instance does not support taking screenshots");
}
- ///
- /// Raises the event.
- ///
- /// A that contains the event data.
- protected virtual void OnElementClicked(WebElementEventArgs e)
+ return screenshotDriver.GetScreenshot();
+ }
+
+ ///
+ /// Frees all managed and, optionally, unmanaged resources used by this instance.
+ ///
+ /// to dispose of only managed resources;
+ /// to dispose of managed and unmanaged resources.
+ protected virtual void Dispose(bool disposing)
+ {
+ if (disposing)
{
- if (this.ElementClicked != null)
- {
- this.ElementClicked(this, e);
- }
+ this.WrappedDriver.Dispose();
}
+ }
- ///
- /// Raises the event.
- ///
- /// A that contains the event data.
- protected virtual void OnElementValueChanging(WebElementValueEventArgs e)
+ ///
+ /// Raises the event.
+ ///
+ /// A that contains the event data.
+ protected virtual void OnNavigating(WebDriverNavigationEventArgs e)
+ {
+ if (this.Navigating != null)
{
- if (this.ElementValueChanging != null)
- {
- this.ElementValueChanging(this, e);
- }
+ this.Navigating(this, e);
}
+ }
- ///
- /// Raises the event.
- ///
- /// A that contains the event data.
- protected virtual void OnElementValueChanged(WebElementValueEventArgs e)
+ ///
+ /// Raises the event.
+ ///
+ /// A that contains the event data.
+ protected virtual void OnNavigated(WebDriverNavigationEventArgs e)
+ {
+ if (this.Navigated != null)
{
- if (this.ElementValueChanged != null)
- {
- this.ElementValueChanged(this, e);
- }
+ this.Navigated(this, e);
}
+ }
- ///
- /// Raises the event.
- ///
- /// A that contains the event data.
- protected virtual void OnFindingElement(FindElementEventArgs e)
+ ///
+ /// Raises the event.
+ ///
+ /// A that contains the event data.
+ protected virtual void OnNavigatingBack(WebDriverNavigationEventArgs e)
+ {
+ if (this.NavigatingBack != null)
{
- if (this.FindingElement != null)
- {
- this.FindingElement(this, e);
- }
+ this.NavigatingBack(this, e);
}
+ }
- ///
- /// Raises the event.
- ///
- /// A that contains the event data.
- protected virtual void OnFindElementCompleted(FindElementEventArgs e)
+ ///
+ /// Raises the event.
+ ///
+ /// A that contains the event data.
+ protected virtual void OnNavigatedBack(WebDriverNavigationEventArgs e)
+ {
+ if (this.NavigatedBack != null)
{
- if (this.FindElementCompleted != null)
- {
- this.FindElementCompleted(this, e);
- }
+ this.NavigatedBack(this, e);
}
+ }
- ///
- /// Raises the event.
- ///
- /// A that contains the event data.
- protected virtual void OnGettingShadowRoot(GetShadowRootEventArgs e)
+ ///
+ /// Raises the event.
+ ///
+ /// A that contains the event data.
+ protected virtual void OnNavigatingForward(WebDriverNavigationEventArgs e)
+ {
+ if (this.NavigatingForward != null)
{
- if (this.GettingShadowRoot != null)
- {
- this.GettingShadowRoot(this, e);
- }
+ this.NavigatingForward(this, e);
}
+ }
- ///
- /// Raises the event.
- ///
- /// A that contains the event data.
- protected virtual void OnGetShadowRootCompleted(GetShadowRootEventArgs e)
+ ///
+ /// Raises the event.
+ ///
+ /// A that contains the event data.
+ protected virtual void OnNavigatedForward(WebDriverNavigationEventArgs e)
+ {
+ if (this.NavigatedForward != null)
{
- if (this.GetShadowRootCompleted != null)
- {
- this.GetShadowRootCompleted(this, e);
- }
+ this.NavigatedForward(this, e);
}
+ }
- ///
- /// Raises the event.
- ///
- /// A that contains the event data.
- protected virtual void OnScriptExecuting(WebDriverScriptEventArgs e)
+ ///
+ /// Raises the event.
+ ///
+ /// A that contains the event data.
+ protected virtual void OnElementClicking(WebElementEventArgs e)
+ {
+ if (this.ElementClicking != null)
{
- if (this.ScriptExecuting != null)
- {
- this.ScriptExecuting(this, e);
- }
+ this.ElementClicking(this, e);
}
+ }
- ///
- /// Raises the event.
- ///
- /// A that contains the event data.
- protected virtual void OnScriptExecuted(WebDriverScriptEventArgs e)
+ ///
+ /// Raises the event.
+ ///
+ /// A that contains the event data.
+ protected virtual void OnElementClicked(WebElementEventArgs e)
+ {
+ if (this.ElementClicked != null)
{
- if (this.ScriptExecuted != null)
- {
- this.ScriptExecuted(this, e);
- }
+ this.ElementClicked(this, e);
}
+ }
- ///
- /// Raises the event.
- ///
- /// A that contains the event data.
- protected virtual void OnException(WebDriverExceptionEventArgs e)
+ ///
+ /// Raises the event.
+ ///
+ /// A that contains the event data.
+ protected virtual void OnElementValueChanging(WebElementValueEventArgs e)
+ {
+ if (this.ElementValueChanging != null)
{
- if (this.ExceptionThrown != null)
- {
- this.ExceptionThrown(this, e);
- }
+ this.ElementValueChanging(this, e);
}
+ }
- private static object?[] UnwrapElementArguments(object?[] args)
+ ///
+ /// Raises the event.
+ ///
+ /// A that contains the event data.
+ protected virtual void OnElementValueChanged(WebElementValueEventArgs e)
+ {
+ if (this.ElementValueChanged != null)
{
- if (args is null)
- {
- throw new InvalidOperationException("Cannot unwrap null args");
- }
+ this.ElementValueChanged(this, e);
+ }
+ }
- // Walk the args: the various drivers expect unwrapped versions of the elements
- List unwrappedArgs = new List(args.Length);
- foreach (object? arg in args)
- {
- if (arg is IWrapsElement eventElementArg)
- {
- unwrappedArgs.Add(eventElementArg.WrappedElement);
- }
- else
- {
- unwrappedArgs.Add(arg);
- }
- }
+ ///
+ /// Raises the event.
+ ///
+ /// A that contains the event data.
+ protected virtual void OnFindingElement(FindElementEventArgs e)
+ {
+ if (this.FindingElement != null)
+ {
+ this.FindingElement(this, e);
+ }
+ }
- return unwrappedArgs.ToArray();
+ ///
+ /// Raises the event.
+ ///
+ /// A that contains the event data.
+ protected virtual void OnFindElementCompleted(FindElementEventArgs e)
+ {
+ if (this.FindElementCompleted != null)
+ {
+ this.FindElementCompleted(this, e);
}
+ }
- private IWebElement WrapElement(IWebElement underlyingElement)
+ ///
+ /// Raises the event.
+ ///
+ /// A that contains the event data.
+ protected virtual void OnGettingShadowRoot(GetShadowRootEventArgs e)
+ {
+ if (this.GettingShadowRoot != null)
{
- return new EventFiringWebElement(this, underlyingElement);
+ this.GettingShadowRoot(this, e);
}
+ }
- ///
- /// Provides a mechanism for Navigating with the driver.
- ///
- private class EventFiringNavigation : INavigation
+ ///
+ /// Raises the event.
+ ///
+ /// A that contains the event data.
+ protected virtual void OnGetShadowRootCompleted(GetShadowRootEventArgs e)
+ {
+ if (this.GetShadowRootCompleted != null)
{
- private readonly EventFiringWebDriver parentDriver;
- private readonly INavigation wrappedNavigation;
+ this.GetShadowRootCompleted(this, e);
+ }
+ }
- ///
- /// Initializes a new instance of the class
- ///
- /// Driver in use
- public EventFiringNavigation(EventFiringWebDriver driver)
- {
- this.parentDriver = driver ?? throw new ArgumentNullException(nameof(driver));
- this.wrappedNavigation = this.parentDriver.WrappedDriver.Navigate();
- }
+ ///
+ /// Raises the event.
+ ///
+ /// A that contains the event data.
+ protected virtual void OnScriptExecuting(WebDriverScriptEventArgs e)
+ {
+ if (this.ScriptExecuting != null)
+ {
+ this.ScriptExecuting(this, e);
+ }
+ }
- ///
- /// Move the browser back
- ///
- public void Back()
- {
- Task.Run(async delegate
- {
- await this.BackAsync();
- }).GetAwaiter().GetResult();
- }
+ ///
+ /// Raises the event.
+ ///
+ /// A that contains the event data.
+ protected virtual void OnScriptExecuted(WebDriverScriptEventArgs e)
+ {
+ if (this.ScriptExecuted != null)
+ {
+ this.ScriptExecuted(this, e);
+ }
+ }
- ///
- /// Move the browser back as an asynchronous task.
- ///
- /// A task object representing the asynchronous operation
- public async Task BackAsync()
- {
- try
- {
- WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.parentDriver);
+ ///
+ /// Raises the event.
+ ///
+ /// A that contains the event data.
+ protected virtual void OnException(WebDriverExceptionEventArgs e)
+ {
+ if (this.ExceptionThrown != null)
+ {
+ this.ExceptionThrown(this, e);
+ }
+ }
- this.parentDriver.OnNavigatingBack(e);
- await this.wrappedNavigation.BackAsync().ConfigureAwait(false);
- this.parentDriver.OnNavigatedBack(e);
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
- }
+ private static object?[] UnwrapElementArguments(object?[] args)
+ {
+ if (args is null)
+ {
+ throw new InvalidOperationException("Cannot unwrap null args");
+ }
- ///
- /// Move a single "item" forward in the browser's history.
- ///
- public void Forward()
+ // Walk the args: the various drivers expect unwrapped versions of the elements
+ List unwrappedArgs = new List(args.Length);
+ foreach (object? arg in args)
+ {
+ if (arg is IWrapsElement eventElementArg)
{
- Task.Run(async delegate
- {
- await this.ForwardAsync();
- }).GetAwaiter().GetResult();
+ unwrappedArgs.Add(eventElementArg.WrappedElement);
}
-
- ///
- /// Move a single "item" forward in the browser's history as an asynchronous task.
- ///
- /// A task object representing the asynchronous operation.
- public async Task ForwardAsync()
+ else
{
- try
- {
- WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.parentDriver);
- this.parentDriver.OnNavigatingForward(e);
- await this.wrappedNavigation.ForwardAsync().ConfigureAwait(false);
- this.parentDriver.OnNavigatedForward(e);
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
+ unwrappedArgs.Add(arg);
}
+ }
- ///
- /// Navigate to a url.
- ///
- /// String of where you want the browser to go to
- public void GoToUrl(string url)
- {
- Task.Run(async delegate
- {
- await this.GoToUrlAsync(url);
- }).GetAwaiter().GetResult();
- }
+ return unwrappedArgs.ToArray();
+ }
- ///
- /// Navigate to a url as an asynchronous task.
- ///
- /// String of where you want the browser to go.
- /// A task object representing the asynchronous operation.
- public async Task GoToUrlAsync(string url)
- {
- if (url == null)
- {
- throw new ArgumentNullException(nameof(url), "url cannot be null");
- }
+ private IWebElement WrapElement(IWebElement underlyingElement)
+ {
+ return new EventFiringWebElement(this, underlyingElement);
+ }
- try
- {
- WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.parentDriver, url);
- this.parentDriver.OnNavigating(e);
- await this.wrappedNavigation.GoToUrlAsync(url).ConfigureAwait(false);
- this.parentDriver.OnNavigated(e);
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
- }
+ ///
+ /// Provides a mechanism for Navigating with the driver.
+ ///
+ private class EventFiringNavigation : INavigation
+ {
+ private readonly EventFiringWebDriver parentDriver;
+ private readonly INavigation wrappedNavigation;
+
+ ///
+ /// Initializes a new instance of the class
+ ///
+ /// Driver in use
+ public EventFiringNavigation(EventFiringWebDriver driver)
+ {
+ this.parentDriver = driver ?? throw new ArgumentNullException(nameof(driver));
+ this.wrappedNavigation = this.parentDriver.WrappedDriver.Navigate();
+ }
- ///
- /// Navigate to a url.
- ///
- /// Uri object of where you want the browser to go to
- public void GoToUrl(Uri url)
+ ///
+ /// Move the browser back
+ ///
+ public void Back()
+ {
+ Task.Run(async delegate
{
- Task.Run(async delegate
- {
- await this.GoToUrlAsync(url);
- }).GetAwaiter().GetResult();
- }
+ await this.BackAsync();
+ }).GetAwaiter().GetResult();
+ }
- ///
- /// Navigate to a url as an asynchronous task.
- ///
- /// Uri object of where you want the browser to go.
- /// A task object representing the asynchronous operation.
- public async Task GoToUrlAsync(Uri url)
+ ///
+ /// Move the browser back as an asynchronous task.
+ ///
+ /// A task object representing the asynchronous operation
+ public async Task BackAsync()
+ {
+ try
{
- if (url == null)
- {
- throw new ArgumentNullException(nameof(url), "url cannot be null");
- }
+ WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.parentDriver);
- await this.GoToUrlAsync(url.ToString()).ConfigureAwait(false);
+ this.parentDriver.OnNavigatingBack(e);
+ await this.wrappedNavigation.BackAsync().ConfigureAwait(false);
+ this.parentDriver.OnNavigatedBack(e);
}
-
- ///
- /// Reload the current page.
- ///
- public void Refresh()
+ catch (Exception ex)
{
- Task.Run(async delegate
- {
- await this.RefreshAsync();
- }).GetAwaiter().GetResult();
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
}
+ }
- ///
- /// Reload the current page as an asynchronous task.
- ///
- /// A task object representing the asynchronous operation.
- public async Task RefreshAsync()
+ ///
+ /// Move a single "item" forward in the browser's history.
+ ///
+ public void Forward()
+ {
+ Task.Run(async delegate
{
- try
- {
- await this.wrappedNavigation.RefreshAsync().ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
- }
+ await this.ForwardAsync();
+ }).GetAwaiter().GetResult();
}
///
- /// Provides a mechanism for setting options needed for the driver during the test.
+ /// Move a single "item" forward in the browser's history as an asynchronous task.
///
- private class EventFiringOptions : IOptions
+ /// A task object representing the asynchronous operation.
+ public async Task ForwardAsync()
{
- private readonly IOptions wrappedOptions;
-
- ///
- /// Initializes a new instance of the class
- ///
- /// Instance of the driver currently in use
- public EventFiringOptions(EventFiringWebDriver driver)
+ try
{
- this.wrappedOptions = driver.WrappedDriver.Manage();
+ WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.parentDriver);
+ this.parentDriver.OnNavigatingForward(e);
+ await this.wrappedNavigation.ForwardAsync().ConfigureAwait(false);
+ this.parentDriver.OnNavigatedForward(e);
}
-
- ///
- /// Gets an object allowing the user to manipulate cookies on the page.
- ///
- public ICookieJar Cookies => this.wrappedOptions.Cookies;
-
- ///
- /// Gets an object allowing the user to manipulate the currently-focused browser window.
- ///
- /// "Currently-focused" is defined as the browser window having the window handle
- /// returned when IWebDriver.CurrentWindowHandle is called.
- public IWindow Window => this.wrappedOptions.Window;
-
- public ILogs Logs => this.wrappedOptions.Logs;
-
- public INetwork Network => this.wrappedOptions.Network;
-
- ///
- /// Provides access to the timeouts defined for this driver.
- ///
- /// An object implementing the interface.
- public ITimeouts Timeouts()
+ catch (Exception ex)
{
- return new EventFiringTimeouts(this.wrappedOptions);
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
}
}
///
- /// Provides a mechanism for finding elements on the page with locators.
+ /// Navigate to a url.
///
- private class EventFiringTargetLocator : ITargetLocator
+ /// String of where you want the browser to go to
+ public void GoToUrl(string url)
{
- private readonly ITargetLocator wrappedLocator;
- private readonly EventFiringWebDriver parentDriver;
-
- ///
- /// Initializes a new instance of the class
- ///
- /// The driver that is currently in use
- public EventFiringTargetLocator(EventFiringWebDriver driver)
+ Task.Run(async delegate
{
- this.parentDriver = driver ?? throw new ArgumentNullException(nameof(driver));
- this.wrappedLocator = this.parentDriver.WrappedDriver.SwitchTo();
- }
+ await this.GoToUrlAsync(url);
+ }).GetAwaiter().GetResult();
+ }
- ///
- /// Move to a different frame using its index
- ///
- /// The index of the
- /// A WebDriver instance that is currently in use
- public IWebDriver Frame(int frameIndex)
+ ///
+ /// Navigate to a url as an asynchronous task.
+ ///
+ /// String of where you want the browser to go.
+ /// A task object representing the asynchronous operation.
+ public async Task GoToUrlAsync(string url)
+ {
+ if (url == null)
{
- IWebDriver driver;
- try
- {
- driver = this.wrappedLocator.Frame(frameIndex);
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
-
- return driver;
+ throw new ArgumentNullException(nameof(url), "url cannot be null");
}
- ///
- /// Move to different frame using its name
- ///
- /// name of the frame
- /// A WebDriver instance that is currently in use
- public IWebDriver Frame(string frameName)
+ try
{
- IWebDriver driver;
- try
- {
- driver = this.wrappedLocator.Frame(frameName);
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
-
- return driver;
+ WebDriverNavigationEventArgs e = new WebDriverNavigationEventArgs(this.parentDriver, url);
+ this.parentDriver.OnNavigating(e);
+ await this.wrappedNavigation.GoToUrlAsync(url).ConfigureAwait(false);
+ this.parentDriver.OnNavigated(e);
}
-
- ///
- /// Move to a frame element.
- ///
- /// a previously found FRAME or IFRAME element.
- /// A WebDriver instance that is currently in use.
- public IWebDriver Frame(IWebElement frameElement)
+ catch (Exception ex)
{
- IWebDriver driver;
- try
- {
- IWrapsElement wrapper = (IWrapsElement)frameElement;
- driver = this.wrappedLocator.Frame(wrapper.WrappedElement);
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
-
- return driver;
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
}
+ }
- ///
- /// Select the parent frame of the currently selected frame.
- ///
- /// An instance focused on the specified frame.
- public IWebDriver ParentFrame()
+ ///
+ /// Navigate to a url.
+ ///
+ /// Uri object of where you want the browser to go to
+ public void GoToUrl(Uri url)
+ {
+ Task.Run(async delegate
{
- IWebDriver driver;
- try
- {
- driver = this.wrappedLocator.ParentFrame();
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
+ await this.GoToUrlAsync(url);
+ }).GetAwaiter().GetResult();
+ }
- return driver;
+ ///
+ /// Navigate to a url as an asynchronous task.
+ ///
+ /// Uri object of where you want the browser to go.
+ /// A task object representing the asynchronous operation.
+ public async Task GoToUrlAsync(Uri url)
+ {
+ if (url == null)
+ {
+ throw new ArgumentNullException(nameof(url), "url cannot be null");
}
- ///
- /// Change to the Window by passing in the name
- ///
- /// name of the window that you wish to move to
- /// A WebDriver instance that is currently in use
- public IWebDriver Window(string windowName)
+ await this.GoToUrlAsync(url.ToString()).ConfigureAwait(false);
+ }
+
+ ///
+ /// Reload the current page.
+ ///
+ public void Refresh()
+ {
+ Task.Run(async delegate
{
- IWebDriver driver;
- try
- {
- driver = this.wrappedLocator.Window(windowName);
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
+ await this.RefreshAsync();
+ }).GetAwaiter().GetResult();
+ }
- return driver;
+ ///
+ /// Reload the current page as an asynchronous task.
+ ///
+ /// A task object representing the asynchronous operation.
+ public async Task RefreshAsync()
+ {
+ try
+ {
+ await this.wrappedNavigation.RefreshAsync().ConfigureAwait(false);
}
-
- ///
- /// Creates a new browser window and switches the focus for future commands
- /// of this driver to the new window.
- ///
- /// The type of new browser window to be created.
- /// The created window is not guaranteed to be of the requested type; if
- /// the driver does not support the requested type, a new browser window
- /// will be created of whatever type the driver does support.
- /// An instance focused on the new browser.
- public IWebDriver NewWindow(WindowType typeHint)
+ catch (Exception ex)
{
- IWebDriver driver;
- try
- {
- driver = this.wrappedLocator.NewWindow(typeHint);
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
-
- return driver;
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
}
+ }
+ }
- ///
- /// Change the active frame to the default
- ///
- /// Element of the default
- public IWebDriver DefaultContent()
- {
- IWebDriver driver;
- try
- {
- driver = this.wrappedLocator.DefaultContent();
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
+ ///
+ /// Provides a mechanism for setting options needed for the driver during the test.
+ ///
+ private class EventFiringOptions : IOptions
+ {
+ private readonly IOptions wrappedOptions;
- return driver;
- }
+ ///
+ /// Initializes a new instance of the class
+ ///
+ /// Instance of the driver currently in use
+ public EventFiringOptions(EventFiringWebDriver driver)
+ {
+ this.wrappedOptions = driver.WrappedDriver.Manage();
+ }
- ///
- /// Finds the active element on the page and returns it
- ///
- /// Element that is active
- public IWebElement ActiveElement()
- {
- IWebElement element;
- try
- {
- element = this.wrappedLocator.ActiveElement();
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
+ ///
+ /// Gets an object allowing the user to manipulate cookies on the page.
+ ///
+ public ICookieJar Cookies => this.wrappedOptions.Cookies;
- return element;
- }
+ ///
+ /// Gets an object allowing the user to manipulate the currently-focused browser window.
+ ///
+ /// "Currently-focused" is defined as the browser window having the window handle
+ /// returned when IWebDriver.CurrentWindowHandle is called.
+ public IWindow Window => this.wrappedOptions.Window;
- ///
- /// Switches to the currently active modal dialog for this particular driver instance.
- ///
- /// A handle to the dialog.
- public IAlert Alert()
- {
- IAlert alert;
- try
- {
- alert = this.wrappedLocator.Alert();
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
+ public ILogs Logs => this.wrappedOptions.Logs;
- return alert;
- }
+ public INetwork Network => this.wrappedOptions.Network;
+
+ ///
+ /// Provides access to the timeouts defined for this driver.
+ ///
+ /// An object implementing the interface.
+ public ITimeouts Timeouts()
+ {
+ return new EventFiringTimeouts(this.wrappedOptions);
}
+ }
+
+ ///
+ /// Provides a mechanism for finding elements on the page with locators.
+ ///
+ private class EventFiringTargetLocator : ITargetLocator
+ {
+ private readonly ITargetLocator wrappedLocator;
+ private readonly EventFiringWebDriver parentDriver;
///
- /// Defines the interface through which the user can define timeouts.
+ /// Initializes a new instance of the class
///
- private class EventFiringTimeouts : ITimeouts
+ /// The driver that is currently in use
+ public EventFiringTargetLocator(EventFiringWebDriver driver)
{
- private readonly ITimeouts wrappedTimeouts;
+ this.parentDriver = driver ?? throw new ArgumentNullException(nameof(driver));
+ this.wrappedLocator = this.parentDriver.WrappedDriver.SwitchTo();
+ }
- ///
- /// Initializes a new instance of the class
- ///
- /// The object to wrap.
- public EventFiringTimeouts(IOptions options)
+ ///
+ /// Move to a different frame using its index
+ ///
+ /// The index of the
+ /// A WebDriver instance that is currently in use
+ public IWebDriver Frame(int frameIndex)
+ {
+ IWebDriver driver;
+ try
{
- this.wrappedTimeouts = options.Timeouts();
+ driver = this.wrappedLocator.Frame(frameIndex);
}
-
- ///
- /// Gets or sets the implicit wait timeout, which is the amount of time the
- /// driver should wait when searching for an element if it is not immediately
- /// present.
- ///
- ///
- /// 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 . When searching for multiple elements,
- /// the driver should poll the page until at least one element has been found
- /// or this timeout has expired.
- ///
- /// 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.
- ///
- ///
- public TimeSpan ImplicitWait
+ catch (Exception ex)
{
- get => this.wrappedTimeouts.ImplicitWait;
- set => this.wrappedTimeouts.ImplicitWait = value;
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
}
- ///
- /// Gets or sets the asynchronous script timeout, which is the amount
- /// of time the driver should wait when executing JavaScript asynchronously.
- /// This timeout only affects the
- /// method.
- ///
- public TimeSpan AsynchronousJavaScript
+ return driver;
+ }
+
+ ///
+ /// Move to different frame using its name
+ ///
+ /// name of the frame
+ /// A WebDriver instance that is currently in use
+ public IWebDriver Frame(string frameName)
+ {
+ IWebDriver driver;
+ try
{
- get => this.wrappedTimeouts.AsynchronousJavaScript;
- set => this.wrappedTimeouts.AsynchronousJavaScript = value;
+ driver = this.wrappedLocator.Frame(frameName);
}
-
- ///
- /// Gets or sets the page load timeout, which is the amount of time the driver
- /// should wait for a page to load when setting the
- /// property.
- ///
- public TimeSpan PageLoad
+ catch (Exception ex)
{
- get => this.wrappedTimeouts.PageLoad;
- set => this.wrappedTimeouts.PageLoad = value;
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
}
+
+ return driver;
}
///
- /// EventFiringWebElement allows you to have access to specific items that are found on the page
+ /// Move to a frame element.
///
- private class EventFiringWebElement : ITakesScreenshot, IWebElement, IWrapsElement, IWrapsDriver
+ /// a previously found FRAME or IFRAME element.
+ /// A WebDriver instance that is currently in use.
+ public IWebDriver Frame(IWebElement frameElement)
{
- private readonly EventFiringWebDriver parentDriver;
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The instance hosting this element.
- /// The to wrap for event firing.
- public EventFiringWebElement(EventFiringWebDriver driver, IWebElement element)
+ IWebDriver driver;
+ try
{
- this.WrappedElement = element ?? throw new ArgumentNullException(nameof(element));
- this.parentDriver = driver ?? throw new ArgumentNullException(nameof(driver));
+ IWrapsElement wrapper = (IWrapsElement)frameElement;
+ driver = this.wrappedLocator.Frame(wrapper.WrappedElement);
+ }
+ catch (Exception ex)
+ {
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
}
- ///
- /// Gets the underlying wrapped .
- ///
- public IWebElement WrappedElement { get; }
-
- ///
- /// Gets the underlying parent wrapped
- ///
- public IWebDriver WrappedDriver => this.parentDriver;
+ return driver;
+ }
- ///
- /// Gets the DOM Tag of element
- ///
- public string TagName
+ ///
+ /// Select the parent frame of the currently selected frame.
+ ///
+ /// An instance focused on the specified frame.
+ public IWebDriver ParentFrame()
+ {
+ IWebDriver driver;
+ try
{
- get
- {
- string tagName;
- try
- {
- tagName = this.WrappedElement.TagName;
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
-
- return tagName;
- }
+ driver = this.wrappedLocator.ParentFrame();
}
-
- ///
- /// Gets the text from the element
- ///
- public string Text
+ catch (Exception ex)
{
- get
- {
- string text;
- try
- {
- text = this.WrappedElement.Text;
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
-
- return text;
- }
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
}
- ///
- /// Gets a value indicating whether an element is currently enabled
- ///
- public bool Enabled
+ return driver;
+ }
+
+ ///
+ /// Change to the Window by passing in the name
+ ///
+ /// name of the window that you wish to move to
+ /// A WebDriver instance that is currently in use
+ public IWebDriver Window(string windowName)
+ {
+ IWebDriver driver;
+ try
{
- get
- {
- bool enabled;
- try
- {
- enabled = this.WrappedElement.Enabled;
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
-
- return enabled;
- }
+ driver = this.wrappedLocator.Window(windowName);
}
-
- ///
- /// Gets a value indicating whether this element is selected or not. This operation only applies to input elements such as checkboxes, options in a select and radio buttons.
- ///
- public bool Selected
+ catch (Exception ex)
{
- get
- {
- bool selected;
- try
- {
- selected = this.WrappedElement.Selected;
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
-
- return selected;
- }
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
}
- ///
- /// Gets the Location of an element and returns a Point object
- ///
- public Point Location
+ return driver;
+ }
+
+ ///
+ /// Creates a new browser window and switches the focus for future commands
+ /// of this driver to the new window.
+ ///
+ /// The type of new browser window to be created.
+ /// The created window is not guaranteed to be of the requested type; if
+ /// the driver does not support the requested type, a new browser window
+ /// will be created of whatever type the driver does support.
+ /// An instance focused on the new browser.
+ public IWebDriver NewWindow(WindowType typeHint)
+ {
+ IWebDriver driver;
+ try
{
- get
- {
- Point location;
- try
- {
- location = this.WrappedElement.Location;
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
-
- return location;
- }
+ driver = this.wrappedLocator.NewWindow(typeHint);
}
-
- ///
- /// Gets the of the element on the page
- ///
- public Size Size
+ catch (Exception ex)
{
- get
- {
- Size size;
- try
- {
- size = this.WrappedElement.Size;
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
-
- return size;
- }
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
}
- ///
- /// Gets a value indicating whether the element is currently being displayed
- ///
- public bool Displayed
+ return driver;
+ }
+
+ ///
+ /// Change the active frame to the default
+ ///
+ /// Element of the default
+ public IWebDriver DefaultContent()
+ {
+ IWebDriver driver;
+ try
{
- get
- {
- bool displayed;
- try
- {
- displayed = this.WrappedElement.Displayed;
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
-
- return displayed;
- }
+ driver = this.wrappedLocator.DefaultContent();
+ }
+ catch (Exception ex)
+ {
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
}
- ///
- /// Gets the underlying EventFiringWebDriver for this element.
- ///
- protected EventFiringWebDriver ParentDriver => this.parentDriver;
+ return driver;
+ }
- ///
- /// Method to clear the text out of an Input element
- ///
- public void Clear()
+ ///
+ /// Finds the active element on the page and returns it
+ ///
+ /// Element that is active
+ public IWebElement ActiveElement()
+ {
+ IWebElement element;
+ try
{
- try
- {
- WebElementValueEventArgs e = new WebElementValueEventArgs(this.parentDriver.WrappedDriver, this.WrappedElement, null);
- this.parentDriver.OnElementValueChanging(e);
- this.WrappedElement.Clear();
- this.parentDriver.OnElementValueChanged(e);
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
+ element = this.wrappedLocator.ActiveElement();
}
-
- ///
- /// Method for sending native key strokes to the browser
- ///
- /// String containing what you would like to type onto the screen
- public void SendKeys(string text)
+ catch (Exception ex)
{
- try
- {
- WebElementValueEventArgs e = new WebElementValueEventArgs(this.parentDriver.WrappedDriver, this.WrappedElement, text);
- this.parentDriver.OnElementValueChanging(e);
- this.WrappedElement.SendKeys(text);
- this.parentDriver.OnElementValueChanged(e);
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
}
- ///
- /// 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.
- ///
- public void Submit()
+ return element;
+ }
+
+ ///
+ /// Switches to the currently active modal dialog for this particular driver instance.
+ ///
+ /// A handle to the dialog.
+ public IAlert Alert()
+ {
+ IAlert alert;
+ try
{
- try
- {
- this.WrappedElement.Submit();
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
+ alert = this.wrappedLocator.Alert();
}
-
- ///
- /// Click this element. If this causes a new page to load, this method will block until
- /// the page has loaded. At this point, you should discard all references to this element
- /// and any further operations performed on this element will have undefined behavior unless
- /// you know that the element and the page will still be present. If this element is not
- /// clickable, then this operation is a no-op since it's pretty common for someone to
- /// accidentally miss the target when clicking in Real Life
- ///
- public void Click()
+ catch (Exception ex)
{
- try
- {
- WebElementEventArgs e = new WebElementEventArgs(this.parentDriver.WrappedDriver, this.WrappedElement);
- this.parentDriver.OnElementClicking(e);
- this.WrappedElement.Click();
- this.parentDriver.OnElementClicked(e);
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
}
- ///
- /// 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.
- ///
- /// Attribute you wish to get details of
- /// The attribute's current value or null if the value is not set.
- public string? GetAttribute(string attributeName)
+ return alert;
+ }
+ }
+
+ ///
+ /// Defines the interface through which the user can define timeouts.
+ ///
+ private class EventFiringTimeouts : ITimeouts
+ {
+ private readonly ITimeouts wrappedTimeouts;
+
+ ///
+ /// Initializes a new instance of the class
+ ///
+ /// The object to wrap.
+ public EventFiringTimeouts(IOptions options)
+ {
+ this.wrappedTimeouts = options.Timeouts();
+ }
+
+ ///
+ /// Gets or sets the implicit wait timeout, which is the amount of time the
+ /// driver should wait when searching for an element if it is not immediately
+ /// present.
+ ///
+ ///
+ /// 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 . When searching for multiple elements,
+ /// the driver should poll the page until at least one element has been found
+ /// or this timeout has expired.
+ ///
+ /// 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.
+ ///
+ ///
+ public TimeSpan ImplicitWait
+ {
+ get => this.wrappedTimeouts.ImplicitWait;
+ set => this.wrappedTimeouts.ImplicitWait = value;
+ }
+
+ ///
+ /// Gets or sets the asynchronous script timeout, which is the amount
+ /// of time the driver should wait when executing JavaScript asynchronously.
+ /// This timeout only affects the
+ /// method.
+ ///
+ public TimeSpan AsynchronousJavaScript
+ {
+ get => this.wrappedTimeouts.AsynchronousJavaScript;
+ set => this.wrappedTimeouts.AsynchronousJavaScript = value;
+ }
+
+ ///
+ /// Gets or sets the page load timeout, which is the amount of time the driver
+ /// should wait for a page to load when setting the
+ /// property.
+ ///
+ public TimeSpan PageLoad
+ {
+ get => this.wrappedTimeouts.PageLoad;
+ set => this.wrappedTimeouts.PageLoad = value;
+ }
+ }
+
+ ///
+ /// EventFiringWebElement allows you to have access to specific items that are found on the page
+ ///
+ private class EventFiringWebElement : ITakesScreenshot, IWebElement, IWrapsElement, IWrapsDriver
+ {
+ private readonly EventFiringWebDriver parentDriver;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The instance hosting this element.
+ /// The to wrap for event firing.
+ public EventFiringWebElement(EventFiringWebDriver driver, IWebElement element)
+ {
+ this.WrappedElement = element ?? throw new ArgumentNullException(nameof(element));
+ this.parentDriver = driver ?? throw new ArgumentNullException(nameof(driver));
+ }
+
+ ///
+ /// Gets the underlying wrapped .
+ ///
+ public IWebElement WrappedElement { get; }
+
+ ///
+ /// Gets the underlying parent wrapped
+ ///
+ public IWebDriver WrappedDriver => this.parentDriver;
+
+ ///
+ /// Gets the DOM Tag of element
+ ///
+ public string TagName
+ {
+ get
{
+ string tagName;
try
{
- return this.WrappedElement.GetAttribute(attributeName);
+ tagName = this.WrappedElement.TagName;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
+
+ return tagName;
}
+ }
- ///
- /// Gets the value of a declared HTML attribute of this element.
- ///
- /// The name of the HTML attribute to get the value of.
- /// The HTML attribute's current value. Returns a if the
- /// value is not set or the declared attribute does not exist.
- ///
- /// As opposed to the method, this method
- /// only returns attributes declared in the element's HTML markup. To access the value
- /// of an IDL property of the element, either use the
- /// method or the method.
- ///
- public string? GetDomAttribute(string attributeName)
+ ///
+ /// Gets the text from the element
+ ///
+ public string Text
+ {
+ get
{
+ string text;
try
{
- return this.WrappedElement.GetDomAttribute(attributeName);
+ text = this.WrappedElement.Text;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
+
+ return text;
}
+ }
- ///
- /// Gets the value of a JavaScript property of this element.
- ///
- /// The name of the JavaScript property to get the value of.
- /// The JavaScript property's current value. Returns a if the
- /// value is not set or the property does not exist.
- public string? GetDomProperty(string propertyName)
+ ///
+ /// Gets a value indicating whether an element is currently enabled
+ ///
+ public bool Enabled
+ {
+ get
{
+ bool enabled;
try
{
- return this.WrappedElement.GetDomProperty(propertyName);
+ enabled = this.WrappedElement.Enabled;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
+
+ return enabled;
}
+ }
- ///
- /// Method to return the value of a CSS Property
- ///
- /// CSS property key
- /// string value of the CSS property
- public string GetCssValue(string propertyName)
+ ///
+ /// Gets a value indicating whether this element is selected or not. This operation only applies to input elements such as checkboxes, options in a select and radio buttons.
+ ///
+ public bool Selected
+ {
+ get
{
- string cssValue;
+ bool selected;
try
{
- cssValue = this.WrappedElement.GetCssValue(propertyName);
+ selected = this.WrappedElement.Selected;
}
catch (Exception ex)
{
@@ -1664,46 +1429,43 @@ public string GetCssValue(string propertyName)
throw;
}
- return cssValue;
+ return selected;
}
+ }
- ///
- /// Gets the representation of an element's shadow root for accessing the shadow DOM of a web component.
- ///
- /// Thrown when this element does not have a shadow root.
- /// A shadow root representation.
- public ISearchContext GetShadowRoot()
+ ///
+ /// Gets the Location of an element and returns a Point object
+ ///
+ public Point Location
+ {
+ get
{
+ Point location;
try
{
- GetShadowRootEventArgs e = new GetShadowRootEventArgs(this.parentDriver.WrappedDriver, this.WrappedElement);
- this.parentDriver.OnGettingShadowRoot(e);
- ISearchContext shadowRoot = this.WrappedElement.GetShadowRoot();
- this.parentDriver.OnGetShadowRootCompleted(e);
- return new EventFiringShadowRoot(this.parentDriver, shadowRoot);
+ location = this.WrappedElement.Location;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
+
+ return location;
}
+ }
- ///
- /// Finds the first element in the page that matches the object
- ///
- /// By mechanism to find the element
- /// IWebElement object so that you can interaction that object
- public IWebElement FindElement(By by)
+ ///
+ /// Gets the of the element on the page
+ ///
+ public Size Size
+ {
+ get
{
- IWebElement wrappedElement;
+ Size size;
try
{
- FindElementEventArgs e = new FindElementEventArgs(this.parentDriver.WrappedDriver, this.WrappedElement, by);
- this.parentDriver.OnFindingElement(e);
- IWebElement element = this.WrappedElement.FindElement(by);
- this.parentDriver.OnFindElementCompleted(e);
- wrappedElement = this.parentDriver.WrapElement(element);
+ size = this.WrappedElement.Size;
}
catch (Exception ex)
{
@@ -1711,190 +1473,427 @@ public IWebElement FindElement(By by)
throw;
}
- return wrappedElement;
+ return size;
}
+ }
- ///
- /// Finds the elements on the page by using the object and returns a ReadOnlyCollection of the Elements on the page
- ///
- /// By mechanism to find the element
- /// ReadOnlyCollection of IWebElement
- public ReadOnlyCollection FindElements(By by)
+ ///
+ /// Gets a value indicating whether the element is currently being displayed
+ ///
+ public bool Displayed
+ {
+ get
{
+ bool displayed;
try
{
- FindElementEventArgs e = new FindElementEventArgs(this.parentDriver.WrappedDriver, this.WrappedElement, by);
- this.parentDriver.OnFindingElement(e);
- ReadOnlyCollection elements = this.WrappedElement.FindElements(by);
- this.parentDriver.OnFindElementCompleted(e);
-
- List wrappedElementList = new List(elements.Count);
- foreach (IWebElement element in elements)
- {
- IWebElement wrappedElement = this.parentDriver.WrapElement(element);
- wrappedElementList.Add(wrappedElement);
- }
-
- return wrappedElementList.AsReadOnly();
+ displayed = this.WrappedElement.Displayed;
}
catch (Exception ex)
{
this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
throw;
}
+
+ return displayed;
}
+ }
- ///
- /// Gets a object representing the image of the page on the screen.
- ///
- /// A object containing the image.
- public Screenshot GetScreenshot()
+ ///
+ /// Gets the underlying EventFiringWebDriver for this element.
+ ///
+ protected EventFiringWebDriver ParentDriver => this.parentDriver;
+
+ ///
+ /// Method to clear the text out of an Input element
+ ///
+ public void Clear()
+ {
+ try
{
- if (this.WrappedElement is not ITakesScreenshot screenshotDriver)
- {
- throw new NotSupportedException("Underlying element instance does not support taking screenshots");
- }
+ WebElementValueEventArgs e = new WebElementValueEventArgs(this.parentDriver.WrappedDriver, this.WrappedElement, null);
+ this.parentDriver.OnElementValueChanging(e);
+ this.WrappedElement.Clear();
+ this.parentDriver.OnElementValueChanged(e);
+ }
+ catch (Exception ex)
+ {
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
+ }
+ }
- return screenshotDriver.GetScreenshot();
+ ///
+ /// Method for sending native key strokes to the browser
+ ///
+ /// String containing what you would like to type onto the screen
+ public void SendKeys(string text)
+ {
+ try
+ {
+ WebElementValueEventArgs e = new WebElementValueEventArgs(this.parentDriver.WrappedDriver, this.WrappedElement, text);
+ this.parentDriver.OnElementValueChanging(e);
+ this.WrappedElement.SendKeys(text);
+ this.parentDriver.OnElementValueChanged(e);
+ }
+ catch (Exception ex)
+ {
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
}
+ }
- ///
- /// Determines whether the specified is equal to the current .
- ///
- /// The to compare to the current .
- /// if the specified is equal to the current ; otherwise, .
- public override bool Equals(object obj)
+ ///
+ /// 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.
+ ///
+ public void Submit()
+ {
+ try
{
- if (obj is not IWebElement other)
- {
- return false;
- }
+ this.WrappedElement.Submit();
+ }
+ catch (Exception ex)
+ {
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
+ }
+ }
- if (other is IWrapsElement otherWrapper)
- {
- other = otherWrapper.WrappedElement;
- }
+ ///
+ /// Click this element. If this causes a new page to load, this method will block until
+ /// the page has loaded. At this point, you should discard all references to this element
+ /// and any further operations performed on this element will have undefined behavior unless
+ /// you know that the element and the page will still be present. If this element is not
+ /// clickable, then this operation is a no-op since it's pretty common for someone to
+ /// accidentally miss the target when clicking in Real Life
+ ///
+ public void Click()
+ {
+ try
+ {
+ WebElementEventArgs e = new WebElementEventArgs(this.parentDriver.WrappedDriver, this.WrappedElement);
+ this.parentDriver.OnElementClicking(e);
+ this.WrappedElement.Click();
+ this.parentDriver.OnElementClicked(e);
+ }
+ catch (Exception ex)
+ {
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
+ }
+ }
+
+ ///
+ /// 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.
+ ///
+ /// Attribute you wish to get details of
+ /// The attribute's current value or null if the value is not set.
+ public string? GetAttribute(string attributeName)
+ {
+ try
+ {
+ return this.WrappedElement.GetAttribute(attributeName);
+ }
+ catch (Exception ex)
+ {
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
+ }
+ }
- return WrappedElement.Equals(other);
+ ///
+ /// Gets the value of a declared HTML attribute of this element.
+ ///
+ /// The name of the HTML attribute to get the value of.
+ /// The HTML attribute's current value. Returns a if the
+ /// value is not set or the declared attribute does not exist.
+ ///
+ /// As opposed to the method, this method
+ /// only returns attributes declared in the element's HTML markup. To access the value
+ /// of an IDL property of the element, either use the
+ /// method or the method.
+ ///
+ public string? GetDomAttribute(string attributeName)
+ {
+ try
+ {
+ return this.WrappedElement.GetDomAttribute(attributeName);
+ }
+ catch (Exception ex)
+ {
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
}
+ }
- ///
- /// Return the hash code for this .
- ///
- /// A 32-bit signed integer hash code.
- public override int GetHashCode()
+ ///
+ /// Gets the value of a JavaScript property of this element.
+ ///
+ /// The name of the JavaScript property to get the value of.
+ /// The JavaScript property's current value. Returns a if the
+ /// value is not set or the property does not exist.
+ public string? GetDomProperty(string propertyName)
+ {
+ try
+ {
+ return this.WrappedElement.GetDomProperty(propertyName);
+ }
+ catch (Exception ex)
{
- return this.WrappedElement.GetHashCode();
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
}
}
///
- /// EventFiringShadowElement allows you to have access to specific shadow elements
+ /// Method to return the value of a CSS Property
///
- private class EventFiringShadowRoot : ISearchContext, IWrapsDriver
+ /// CSS property key
+ /// string value of the CSS property
+ public string GetCssValue(string propertyName)
{
- private readonly EventFiringWebDriver parentDriver;
+ string cssValue;
+ try
+ {
+ cssValue = this.WrappedElement.GetCssValue(propertyName);
+ }
+ catch (Exception ex)
+ {
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
+ }
+
+ return cssValue;
+ }
- ///
- /// Initializes a new instance of the class.
- ///
- /// The instance hosting this element.
- /// The to wrap for event firing.
- public EventFiringShadowRoot(EventFiringWebDriver driver, ISearchContext searchContext)
+ ///
+ /// Gets the representation of an element's shadow root for accessing the shadow DOM of a web component.
+ ///
+ /// Thrown when this element does not have a shadow root.
+ /// A shadow root representation.
+ public ISearchContext GetShadowRoot()
+ {
+ try
+ {
+ GetShadowRootEventArgs e = new GetShadowRootEventArgs(this.parentDriver.WrappedDriver, this.WrappedElement);
+ this.parentDriver.OnGettingShadowRoot(e);
+ ISearchContext shadowRoot = this.WrappedElement.GetShadowRoot();
+ this.parentDriver.OnGetShadowRootCompleted(e);
+ return new EventFiringShadowRoot(this.parentDriver, shadowRoot);
+ }
+ catch (Exception ex)
{
- this.WrappedSearchContext = searchContext ?? throw new ArgumentNullException(nameof(searchContext));
- this.parentDriver = driver;
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
}
+ }
- ///
- /// Gets the underlying wrapped .
- ///
- public ISearchContext WrappedSearchContext { get; }
+ ///
+ /// Finds the first element in the page that matches the object
+ ///
+ /// By mechanism to find the element
+ /// IWebElement object so that you can interaction that object
+ public IWebElement FindElement(By by)
+ {
+ IWebElement wrappedElement;
+ try
+ {
+ FindElementEventArgs e = new FindElementEventArgs(this.parentDriver.WrappedDriver, this.WrappedElement, by);
+ this.parentDriver.OnFindingElement(e);
+ IWebElement element = this.WrappedElement.FindElement(by);
+ this.parentDriver.OnFindElementCompleted(e);
+ wrappedElement = this.parentDriver.WrapElement(element);
+ }
+ catch (Exception ex)
+ {
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
+ }
- ///
- /// Gets the underlying parent wrapped
- ///
- public IWebDriver WrappedDriver => this.parentDriver;
+ return wrappedElement;
+ }
- ///
- /// Finds the first element in the page that matches the object
- ///
- /// By mechanism to find the element
- /// IWebElement object so that you can interaction that object
- public IWebElement FindElement(By by)
+ ///
+ /// Finds the elements on the page by using the object and returns a ReadOnlyCollection of the Elements on the page
+ ///
+ /// By mechanism to find the element
+ /// ReadOnlyCollection of IWebElement
+ public ReadOnlyCollection FindElements(By by)
+ {
+ try
{
- IWebElement wrappedElement;
- try
- {
- GetShadowRootEventArgs e = new GetShadowRootEventArgs(this.parentDriver.WrappedDriver, this.WrappedSearchContext);
- this.parentDriver.OnGettingShadowRoot(e);
- IWebElement element = this.WrappedSearchContext.FindElement(by);
- this.parentDriver.OnGetShadowRootCompleted(e);
- wrappedElement = new EventFiringWebElement(this.parentDriver, element);
- }
- catch (Exception ex)
+ FindElementEventArgs e = new FindElementEventArgs(this.parentDriver.WrappedDriver, this.WrappedElement, by);
+ this.parentDriver.OnFindingElement(e);
+ ReadOnlyCollection elements = this.WrappedElement.FindElements(by);
+ this.parentDriver.OnFindElementCompleted(e);
+
+ List wrappedElementList = new List(elements.Count);
+ foreach (IWebElement element in elements)
{
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
+ IWebElement wrappedElement = this.parentDriver.WrapElement(element);
+ wrappedElementList.Add(wrappedElement);
}
- return wrappedElement;
+ return wrappedElementList.AsReadOnly();
+ }
+ catch (Exception ex)
+ {
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
}
+ }
- ///
- /// Finds the elements on the page by using the object and returns a ReadOnlyCollection of the Elements on the page
- ///
- /// By mechanism to find the element
- /// ReadOnlyCollection of IWebElement
- public ReadOnlyCollection FindElements(By by)
+ ///
+ /// Gets a object representing the image of the page on the screen.
+ ///
+ /// A object containing the image.
+ public Screenshot GetScreenshot()
+ {
+ if (this.WrappedElement is not ITakesScreenshot screenshotDriver)
{
- try
- {
- GetShadowRootEventArgs e = new GetShadowRootEventArgs(this.parentDriver.WrappedDriver, this.WrappedSearchContext);
- this.parentDriver.OnGettingShadowRoot(e);
- ReadOnlyCollection elements = this.WrappedSearchContext.FindElements(by);
- this.parentDriver.OnGetShadowRootCompleted(e);
-
- List wrappedElementList = new List(elements.Count);
- foreach (IWebElement element in elements)
- {
- IWebElement wrappedElement = this.parentDriver.WrapElement(element);
- wrappedElementList.Add(wrappedElement);
- }
-
- return wrappedElementList.AsReadOnly();
- }
- catch (Exception ex)
- {
- this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
- throw;
- }
+ throw new NotSupportedException("Underlying element instance does not support taking screenshots");
+ }
+
+ return screenshotDriver.GetScreenshot();
+ }
+
+ ///
+ /// Determines whether the specified is equal to the current .
+ ///
+ /// The to compare to the current .
+ /// if the specified is equal to the current ; otherwise, .
+ public override bool Equals(object obj)
+ {
+ if (obj is not IWebElement other)
+ {
+ return false;
+ }
+
+ if (other is IWrapsElement otherWrapper)
+ {
+ other = otherWrapper.WrappedElement;
+ }
+
+ return WrappedElement.Equals(other);
+ }
+
+ ///
+ /// Return the hash code for this .
+ ///
+ /// A 32-bit signed integer hash code.
+ public override int GetHashCode()
+ {
+ return this.WrappedElement.GetHashCode();
+ }
+ }
+
+ ///
+ /// EventFiringShadowElement allows you to have access to specific shadow elements
+ ///
+ private class EventFiringShadowRoot : ISearchContext, IWrapsDriver
+ {
+ private readonly EventFiringWebDriver parentDriver;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The instance hosting this element.
+ /// The to wrap for event firing.
+ public EventFiringShadowRoot(EventFiringWebDriver driver, ISearchContext searchContext)
+ {
+ this.WrappedSearchContext = searchContext ?? throw new ArgumentNullException(nameof(searchContext));
+ this.parentDriver = driver;
+ }
+
+ ///
+ /// Gets the underlying wrapped .
+ ///
+ public ISearchContext WrappedSearchContext { get; }
+
+ ///
+ /// Gets the underlying parent wrapped
+ ///
+ public IWebDriver WrappedDriver => this.parentDriver;
+ ///
+ /// Finds the first element in the page that matches the object
+ ///
+ /// By mechanism to find the element
+ /// IWebElement object so that you can interaction that object
+ public IWebElement FindElement(By by)
+ {
+ IWebElement wrappedElement;
+ try
+ {
+ GetShadowRootEventArgs e = new GetShadowRootEventArgs(this.parentDriver.WrappedDriver, this.WrappedSearchContext);
+ this.parentDriver.OnGettingShadowRoot(e);
+ IWebElement element = this.WrappedSearchContext.FindElement(by);
+ this.parentDriver.OnGetShadowRootCompleted(e);
+ wrappedElement = new EventFiringWebElement(this.parentDriver, element);
+ }
+ catch (Exception ex)
+ {
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
}
- ///
- /// Determines whether the specified is equal to the current .
- ///
- /// The to compare to the current .
- /// if the specified is equal to the current ; otherwise, .
- public override bool Equals(object obj)
+ return wrappedElement;
+ }
+
+ ///
+ /// Finds the elements on the page by using the object and returns a ReadOnlyCollection of the Elements on the page
+ ///
+ /// By mechanism to find the element
+ /// ReadOnlyCollection of IWebElement
+ public ReadOnlyCollection FindElements(By by)
+ {
+ try
{
- if (obj is not ISearchContext other)
+ GetShadowRootEventArgs e = new GetShadowRootEventArgs(this.parentDriver.WrappedDriver, this.WrappedSearchContext);
+ this.parentDriver.OnGettingShadowRoot(e);
+ ReadOnlyCollection elements = this.WrappedSearchContext.FindElements(by);
+ this.parentDriver.OnGetShadowRootCompleted(e);
+
+ List wrappedElementList = new List(elements.Count);
+ foreach (IWebElement element in elements)
{
- return false;
+ IWebElement wrappedElement = this.parentDriver.WrapElement(element);
+ wrappedElementList.Add(wrappedElement);
}
- return WrappedSearchContext.Equals(other);
+ return wrappedElementList.AsReadOnly();
+ }
+ catch (Exception ex)
+ {
+ this.parentDriver.OnException(new WebDriverExceptionEventArgs(this.parentDriver, ex));
+ throw;
}
- ///
- /// Return the hash code for this .
- ///
- /// A 32-bit signed integer hash code.
- public override int GetHashCode()
+ }
+
+ ///
+ /// Determines whether the specified is equal to the current .
+ ///
+ /// The to compare to the current .
+ /// if the specified is equal to the current ; otherwise, .
+ public override bool Equals(object obj)
+ {
+ if (obj is not ISearchContext other)
{
- return this.WrappedSearchContext.GetHashCode();
+ return false;
}
+
+ return WrappedSearchContext.Equals(other);
+ }
+
+ ///
+ /// Return the hash code for this .
+ ///
+ /// A 32-bit signed integer hash code.
+ public override int GetHashCode()
+ {
+ return this.WrappedSearchContext.GetHashCode();
}
}
}
diff --git a/dotnet/src/support/Events/FindElementEventArgs.cs b/dotnet/src/support/Events/FindElementEventArgs.cs
index b89e4779acffe..c28ad02569d90 100644
--- a/dotnet/src/support/Events/FindElementEventArgs.cs
+++ b/dotnet/src/support/Events/FindElementEventArgs.cs
@@ -19,51 +19,50 @@
using System;
-namespace OpenQA.Selenium.Support.Events
+namespace OpenQA.Selenium.Support.Events;
+
+///
+/// Provides data for events related to finding elements.
+///
+public class FindElementEventArgs : EventArgs
{
///
- /// Provides data for events related to finding elements.
+ /// Initializes a new instance of the class.
///
- public class FindElementEventArgs : EventArgs
+ /// The WebDriver instance used in finding elements.
+ /// The object containing the method used to find elements.
+ /// If or are .
+ public FindElementEventArgs(IWebDriver driver, By method)
+ : this(driver, null, method)
{
- ///
- /// Initializes a new instance of the class.
- ///
- /// The WebDriver instance used in finding elements.
- /// The object containing the method used to find elements.
- /// If or are .
- public FindElementEventArgs(IWebDriver driver, By method)
- : this(driver, null, method)
- {
- }
+ }
- ///
- /// Initializes a new instance of the class.
- ///
- /// The WebDriver instance used in finding elements.
- /// The parent element used as the context for the search, or if none exists.
- /// The object containing the method used to find elements.
- /// If or are .
- public FindElementEventArgs(IWebDriver driver, IWebElement? element, By method)
- {
- this.Driver = driver ?? throw new ArgumentNullException(nameof(driver));
- this.Element = element;
- this.FindMethod = method ?? throw new ArgumentNullException(nameof(method));
- }
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The WebDriver instance used in finding elements.
+ /// The parent element used as the context for the search, or if none exists.
+ /// The object containing the method used to find elements.
+ /// If or are .
+ public FindElementEventArgs(IWebDriver driver, IWebElement? element, By method)
+ {
+ this.Driver = driver ?? throw new ArgumentNullException(nameof(driver));
+ this.Element = element;
+ this.FindMethod = method ?? throw new ArgumentNullException(nameof(method));
+ }
- ///
- /// Gets the WebDriver instance used in finding elements.
- ///
- public IWebDriver Driver { get; }
+ ///
+ /// Gets the WebDriver instance used in finding elements.
+ ///
+ public IWebDriver Driver { get; }
- ///
- /// Gets the parent element used as the context for the search, or if no element is associated.
- ///
- public IWebElement? Element { get; }
+ ///
+ /// Gets the parent element used as the context for the search, or if no element is associated.
+ ///
+ public IWebElement? Element { get; }
- ///
- /// Gets the object containing the method used to find elements.
- ///
- public By FindMethod { get; }
- }
+ ///
+ /// Gets the object containing the method used to find elements.
+ ///
+ public By FindMethod { get; }
}
diff --git a/dotnet/src/support/Events/GetShadowRootEventArgs.cs b/dotnet/src/support/Events/GetShadowRootEventArgs.cs
index 95c989ef0f7f2..a028f3c806125 100644
--- a/dotnet/src/support/Events/GetShadowRootEventArgs.cs
+++ b/dotnet/src/support/Events/GetShadowRootEventArgs.cs
@@ -19,33 +19,32 @@
using System;
-namespace OpenQA.Selenium.Support.Events
+namespace OpenQA.Selenium.Support.Events;
+
+///
+/// Provides data for events related to getting shadow root of the web element.
+///
+public class GetShadowRootEventArgs : EventArgs
{
///
- /// Provides data for events related to getting shadow root of the web element.
+ /// Initializes a new instance of the class.
///
- public class GetShadowRootEventArgs : EventArgs
+ /// The WebDriver instance used in the current context.
+ /// The parent searc context used as the context for getting shadow root.
+ /// If or are .
+ public GetShadowRootEventArgs(IWebDriver driver, ISearchContext searchContext)
{
- ///
- /// Initializes a new instance of the class.
- ///
- /// The WebDriver instance used in the current context.
- /// The parent searc context used as the context for getting shadow root.
- /// If or are .
- public GetShadowRootEventArgs(IWebDriver driver, ISearchContext searchContext)
- {
- this.Driver = driver ?? throw new ArgumentNullException(nameof(driver));
- this.SearchContext = searchContext ?? throw new ArgumentNullException(nameof(searchContext));
- }
+ this.Driver = driver ?? throw new ArgumentNullException(nameof(driver));
+ this.SearchContext = searchContext ?? throw new ArgumentNullException(nameof(searchContext));
+ }
- ///
- /// Gets the WebDriver instance used in the current context.
- ///
- public IWebDriver Driver { get; }
+ ///
+ /// Gets the WebDriver instance used in the current context.
+ ///
+ public IWebDriver Driver { get; }
- ///
- /// Gets the parent search context used as the context for getting shadow root.
- ///
- public ISearchContext SearchContext { get; }
- }
+ ///
+ /// Gets the parent search context used as the context for getting shadow root.
+ ///
+ public ISearchContext SearchContext { get; }
}
diff --git a/dotnet/src/support/Events/WebDriverExceptionEventArgs.cs b/dotnet/src/support/Events/WebDriverExceptionEventArgs.cs
index 75aa790caeaf5..03dcd5247f954 100644
--- a/dotnet/src/support/Events/WebDriverExceptionEventArgs.cs
+++ b/dotnet/src/support/Events/WebDriverExceptionEventArgs.cs
@@ -19,33 +19,32 @@
using System;
-namespace OpenQA.Selenium.Support.Events
+namespace OpenQA.Selenium.Support.Events;
+
+///
+/// Provides data for events relating to exception handling.
+///
+public class WebDriverExceptionEventArgs : EventArgs
{
///
- /// Provides data for events relating to exception handling.
+ /// Initializes a new instance of the class.
///
- public class WebDriverExceptionEventArgs : EventArgs
+ /// The WebDriver instance throwing the exception.
+ /// The exception thrown by the driver.
+ /// If or are .
+ public WebDriverExceptionEventArgs(IWebDriver driver, Exception thrownException)
{
- ///
- /// Initializes a new instance of the class.
- ///
- /// The WebDriver instance throwing the exception.
- /// The exception thrown by the driver.
- /// If or are .
- public WebDriverExceptionEventArgs(IWebDriver driver, Exception thrownException)
- {
- this.Driver = driver ?? throw new ArgumentNullException(nameof(driver));
- this.ThrownException = thrownException ?? throw new ArgumentNullException(nameof(thrownException));
- }
+ this.Driver = driver ?? throw new ArgumentNullException(nameof(driver));
+ this.ThrownException = thrownException ?? throw new ArgumentNullException(nameof(thrownException));
+ }
- ///
- /// Gets the exception thrown by the driver.
- ///
- public Exception ThrownException { get; }
+ ///
+ /// Gets the exception thrown by the driver.
+ ///
+ public Exception ThrownException { get; }
- ///
- /// Gets the WebDriver instance.
- ///
- public IWebDriver Driver { get; }
- }
+ ///
+ /// Gets the WebDriver instance.
+ ///
+ public IWebDriver Driver { get; }
}
diff --git a/dotnet/src/support/Events/WebDriverNavigationEventArgs.cs b/dotnet/src/support/Events/WebDriverNavigationEventArgs.cs
index ce6af33399f2b..4bd01d29cc1e0 100644
--- a/dotnet/src/support/Events/WebDriverNavigationEventArgs.cs
+++ b/dotnet/src/support/Events/WebDriverNavigationEventArgs.cs
@@ -19,43 +19,42 @@
using System;
-namespace OpenQA.Selenium.Support.Events
+namespace OpenQA.Selenium.Support.Events;
+
+///
+/// Provides data for events relating to navigation.
+///
+public class WebDriverNavigationEventArgs : EventArgs
{
///
- /// Provides data for events relating to navigation.
+ /// Initializes a new instance of the class.
///
- public class WebDriverNavigationEventArgs : EventArgs
+ /// The WebDriver instance used in navigation.
+ /// If is .
+ public WebDriverNavigationEventArgs(IWebDriver driver)
+ : this(driver, null)
{
- ///
- /// Initializes a new instance of the class.
- ///
- /// The WebDriver instance used in navigation.
- /// If is .
- public WebDriverNavigationEventArgs(IWebDriver driver)
- : this(driver, null)
- {
- }
+ }
- ///
- /// Initializes a new instance of the class.
- ///
- /// The WebDriver instance used in navigation.
- /// The URL navigated to by the driver, or if none exists.
- /// If is .
- public WebDriverNavigationEventArgs(IWebDriver driver, string? url)
- {
- this.Url = url;
- this.Driver = driver ?? throw new ArgumentNullException(nameof(driver));
- }
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The WebDriver instance used in navigation.
+ /// The URL navigated to by the driver, or if none exists.
+ /// If is .
+ public WebDriverNavigationEventArgs(IWebDriver driver, string? url)
+ {
+ this.Url = url;
+ this.Driver = driver ?? throw new ArgumentNullException(nameof(driver));
+ }
- ///
- /// Gets the URL navigated to by the driver, or if no URL could be determined.
- ///
- public string? Url { get; }
+ ///
+ /// Gets the URL navigated to by the driver, or if no URL could be determined.
+ ///
+ public string? Url { get; }
- ///
- /// Gets the WebDriver instance used in navigation.
- ///
- public IWebDriver Driver { get; }
- }
+ ///
+ /// Gets the WebDriver instance used in navigation.
+ ///
+ public IWebDriver Driver { get; }
}
diff --git a/dotnet/src/support/Events/WebDriverScriptEventArgs.cs b/dotnet/src/support/Events/WebDriverScriptEventArgs.cs
index 2251376293da3..be198ecf62945 100644
--- a/dotnet/src/support/Events/WebDriverScriptEventArgs.cs
+++ b/dotnet/src/support/Events/WebDriverScriptEventArgs.cs
@@ -19,33 +19,32 @@
using System;
-namespace OpenQA.Selenium.Support.Events
+namespace OpenQA.Selenium.Support.Events;
+
+///
+/// Provides data for events relating to executing JavaScript.
+///
+public class WebDriverScriptEventArgs : EventArgs
{
///
- /// Provides data for events relating to executing JavaScript.
+ /// Initializes a new instance of the class.
///
- public class WebDriverScriptEventArgs : EventArgs
+ /// The WebDriver instance used to execute the script.
+ /// The script executed by the driver.
+ /// If or are .
+ public WebDriverScriptEventArgs(IWebDriver driver, string script)
{
- ///
- /// Initializes a new instance of the class.
- ///
- /// The WebDriver instance used to execute the script.
- /// The script executed by the driver.
- /// If or are .
- public WebDriverScriptEventArgs(IWebDriver driver, string script)
- {
- this.Driver = driver ?? throw new ArgumentNullException(nameof(driver));
- this.Script = script ?? throw new ArgumentNullException(nameof(script));
- }
+ this.Driver = driver ?? throw new ArgumentNullException(nameof(driver));
+ this.Script = script ?? throw new ArgumentNullException(nameof(script));
+ }
- ///
- /// Gets the WebDriver instance used to execute the script.
- ///
- public IWebDriver Driver { get; }
+ ///
+ /// Gets the WebDriver instance used to execute the script.
+ ///
+ public IWebDriver Driver { get; }
- ///
- /// Gets the script executed by the driver.
- ///
- public string Script { get; }
- }
+ ///
+ /// Gets the script executed by the driver.
+ ///
+ public string Script { get; }
}
diff --git a/dotnet/src/support/Events/WebElementEventArgs.cs b/dotnet/src/support/Events/WebElementEventArgs.cs
index 383b3f593f5f3..6b427c1d231fd 100644
--- a/dotnet/src/support/Events/WebElementEventArgs.cs
+++ b/dotnet/src/support/Events/WebElementEventArgs.cs
@@ -19,33 +19,32 @@
using System;
-namespace OpenQA.Selenium.Support.Events
+namespace OpenQA.Selenium.Support.Events;
+
+///
+/// Provides data for events relating to elements.
+///
+public class WebElementEventArgs : EventArgs
{
///
- /// Provides data for events relating to elements.
+ /// Initializes a new instance of the class.
///
- public class WebElementEventArgs : EventArgs
+ /// The WebDriver instance used for the action.
+ /// The element used for the action.
+ /// If or are .
+ public WebElementEventArgs(IWebDriver driver, IWebElement element)
{
- ///
- /// Initializes a new instance of the class.
- ///
- /// The WebDriver instance used for the action.
- /// The element used for the action.
- /// If or are .
- public WebElementEventArgs(IWebDriver driver, IWebElement element)
- {
- this.Driver = driver ?? throw new ArgumentNullException(nameof(driver));
- this.Element = element ?? throw new ArgumentNullException(nameof(element));
- }
+ this.Driver = driver ?? throw new ArgumentNullException(nameof(driver));
+ this.Element = element ?? throw new ArgumentNullException(nameof(element));
+ }
- ///
- /// Gets the WebDriver instance used for the action.
- ///
- public IWebDriver Driver { get; }
+ ///
+ /// Gets the WebDriver instance used for the action.
+ ///
+ public IWebDriver Driver { get; }
- ///
- /// Gets the element used for the action.
- ///
- public IWebElement Element { get; }
- }
+ ///
+ /// Gets the element used for the action.
+ ///
+ public IWebElement Element { get; }
}
diff --git a/dotnet/src/support/Events/WebElementValueEventArgs.cs b/dotnet/src/support/Events/WebElementValueEventArgs.cs
index 76ef60e0f72d9..774aeea6725ce 100644
--- a/dotnet/src/support/Events/WebElementValueEventArgs.cs
+++ b/dotnet/src/support/Events/WebElementValueEventArgs.cs
@@ -19,29 +19,28 @@
using System;
-namespace OpenQA.Selenium.Support.Events
+namespace OpenQA.Selenium.Support.Events;
+
+///
+/// Provides data for events related to finding elements.
+///
+public class WebElementValueEventArgs : WebElementEventArgs
{
///
- /// Provides data for events related to finding elements.
+ /// Initializes a new instance of the class.
///
- public class WebElementValueEventArgs : WebElementEventArgs
+ /// The WebDriver instance used for the action.
+ /// The element used for the action.
+ /// The new value for the element.
+ /// If or are .
+ public WebElementValueEventArgs(IWebDriver driver, IWebElement element, string? value)
+ : base(driver, element)
{
- ///
- /// Initializes a new instance of the class.
- ///
- /// The WebDriver instance used for the action.
- /// The element used for the action.
- /// The new value for the element.
- /// If or are .
- public WebElementValueEventArgs(IWebDriver driver, IWebElement element, string? value)
- : base(driver, element)
- {
- this.Value = value;
- }
-
- ///
- /// Gets the Value that is written to the element.
- ///
- public string? Value { get; }
+ this.Value = value;
}
+
+ ///
+ /// Gets the Value that is written to the element.
+ ///
+ public string? Value { get; }
}
diff --git a/dotnet/src/support/Extensions/WebDriverExtensions.cs b/dotnet/src/support/Extensions/WebDriverExtensions.cs
index 9b0274b6afded..8ef995719dfda 100644
--- a/dotnet/src/support/Extensions/WebDriverExtensions.cs
+++ b/dotnet/src/support/Extensions/WebDriverExtensions.cs
@@ -20,127 +20,126 @@
using System;
using System.Reflection;
-namespace OpenQA.Selenium.Support.Extensions
+namespace OpenQA.Selenium.Support.Extensions;
+
+///
+/// Provides extension methods for convenience in using WebDriver.
+///
+public static class WebDriverExtensions
{
///
- /// Provides extension methods for convenience in using WebDriver.
+ /// Gets a object representing the image of the page on the screen.
///
- public static class WebDriverExtensions
+ /// The driver instance to extend.
+ /// A object containing the image.
+ /// Thrown if this instance
+ /// does not implement , or the capabilities of the driver
+ /// indicate that it cannot take screenshots.
+ public static Screenshot TakeScreenshot(this IWebDriver driver)
{
- ///
- /// Gets a object representing the image of the page on the screen.
- ///
- /// The driver instance to extend.
- /// A object containing the image.
- /// Thrown if this instance
- /// does not implement , or the capabilities of the driver
- /// indicate that it cannot take screenshots.
- public static Screenshot TakeScreenshot(this IWebDriver driver)
+ ITakesScreenshot? screenshotDriver = GetDriverAs(driver);
+ if (screenshotDriver is null)
{
- ITakesScreenshot? screenshotDriver = GetDriverAs(driver);
- if (screenshotDriver is null)
- {
- IHasCapabilities capabilitiesDriver = driver as IHasCapabilities
- ?? throw new WebDriverException("Driver does not implement ITakesScreenshot or IHasCapabilities");
-
- if (capabilitiesDriver.Capabilities.GetCapability(CapabilityType.TakesScreenshot) is not true)
- {
- throw new WebDriverException("Driver capabilities do not support taking screenshots");
- }
+ IHasCapabilities capabilitiesDriver = driver as IHasCapabilities
+ ?? throw new WebDriverException("Driver does not implement ITakesScreenshot or IHasCapabilities");
- MethodInfo executeMethod = driver.GetType().GetMethod("Execute", BindingFlags.Instance | BindingFlags.NonPublic)!;
+ if (capabilitiesDriver.Capabilities.GetCapability(CapabilityType.TakesScreenshot) is not true)
+ {
+ throw new WebDriverException("Driver capabilities do not support taking screenshots");
+ }
- object? responseObject = executeMethod.Invoke(driver, new object?[] { DriverCommand.Screenshot, null });
- if (responseObject is not Response screenshotResponse)
- {
- throw new WebDriverException($"Unexpected failure getting screenshot; response was not in the proper format: {responseObject}");
- }
+ MethodInfo executeMethod = driver.GetType().GetMethod("Execute", BindingFlags.Instance | BindingFlags.NonPublic)!;
- string screenshotResult = screenshotResponse.Value!.ToString();
- return new Screenshot(screenshotResult);
+ object? responseObject = executeMethod.Invoke(driver, new object?[] { DriverCommand.Screenshot, null });
+ if (responseObject is not Response screenshotResponse)
+ {
+ throw new WebDriverException($"Unexpected failure getting screenshot; response was not in the proper format: {responseObject}");
}
- return screenshotDriver.GetScreenshot();
+ string screenshotResult = screenshotResponse.Value!.ToString();
+ return new Screenshot(screenshotResult);
}
- ///
- /// Executes JavaScript in the context of the currently selected frame or window
- ///
- /// The driver instance to extend.
- /// The JavaScript code to execute.
- /// The arguments to the script.
- /// Thrown if this instance
- /// does not implement
- public static void ExecuteJavaScript(this IWebDriver driver, string script, params object?[] args)
- {
- ExecuteJavaScriptInternal(driver, script, args);
- }
-
- ///
- /// Executes JavaScript in the context of the currently selected frame or window
- ///
- /// Expected return type of the JavaScript execution.
- /// The driver instance to extend.
- /// The JavaScript code to execute.
- /// The arguments to the script.
- /// The value returned by the script.
- /// Thrown if this instance
- /// does not implement , or if the actual return type
- /// of the JavaScript execution does not match the expected type.
- public static T? ExecuteJavaScript(this IWebDriver driver, string script, params object?[] args)
- {
- var value = ExecuteJavaScriptInternal(driver, script, args);
- if (value == null)
- {
- if (default(T) != null)
- {
- throw new WebDriverException("Script returned null, but desired type is a non-nullable value type");
- }
+ return screenshotDriver.GetScreenshot();
+ }
- return default;
- }
+ ///
+ /// Executes JavaScript in the context of the currently selected frame or window
+ ///
+ /// The driver instance to extend.
+ /// The JavaScript code to execute.
+ /// The arguments to the script.
+ /// Thrown if this instance
+ /// does not implement
+ public static void ExecuteJavaScript(this IWebDriver driver, string script, params object?[] args)
+ {
+ ExecuteJavaScriptInternal(driver, script, args);
+ }
- if (value is T t)
+ ///
+ /// Executes JavaScript in the context of the currently selected frame or window
+ ///
+ /// Expected return type of the JavaScript execution.
+ /// The driver instance to extend.
+ /// The JavaScript code to execute.
+ /// The arguments to the script.
+ /// The value returned by the script.
+ /// Thrown if this instance
+ /// does not implement , or if the actual return type
+ /// of the JavaScript execution does not match the expected type.
+ public static T? ExecuteJavaScript(this IWebDriver driver, string script, params object?[] args)
+ {
+ var value = ExecuteJavaScriptInternal(driver, script, args);
+ if (value == null)
+ {
+ if (default(T) != null)
{
- return t;
+ throw new WebDriverException("Script returned null, but desired type is a non-nullable value type");
}
- try
- {
- return (T)Convert.ChangeType(value, typeof(T));
- }
- catch (Exception exp)
- {
- throw new WebDriverException("Script returned a value, but the result could not be cast to the desired type", exp);
- }
+ return default;
}
- private static object? ExecuteJavaScriptInternal(IWebDriver driver, string script, object?[] args)
+ if (value is T t)
{
- IJavaScriptExecutor? executor = GetDriverAs(driver)
- ?? throw new WebDriverException("Driver does not implement IJavaScriptExecutor");
+ return t;
+ }
- return executor.ExecuteScript(script, args);
+ try
+ {
+ return (T)Convert.ChangeType(value, typeof(T));
+ }
+ catch (Exception exp)
+ {
+ throw new WebDriverException("Script returned a value, but the result could not be cast to the desired type", exp);
}
+ }
- private static T? GetDriverAs(IWebDriver driver) where T : class
+ private static object? ExecuteJavaScriptInternal(IWebDriver driver, string script, object?[] args)
+ {
+ IJavaScriptExecutor? executor = GetDriverAs(driver)
+ ?? throw new WebDriverException("Driver does not implement IJavaScriptExecutor");
+
+ return executor.ExecuteScript(script, args);
+ }
+
+ private static T? GetDriverAs(IWebDriver driver) where T : class
+ {
+ T? convertedDriver = driver as T;
+ if (convertedDriver == null)
{
- T? convertedDriver = driver as T;
- if (convertedDriver == null)
+ // If the driver doesn't directly implement the desired interface, but does
+ // implement IWrapsDriver, walk up the hierarchy of wrapped drivers until
+ // either we find a class that does implement the desired interface, or is
+ // no longer wrapping a driver.
+ IWrapsDriver? driverWrapper = driver as IWrapsDriver;
+ while (convertedDriver == null && driverWrapper != null)
{
- // If the driver doesn't directly implement the desired interface, but does
- // implement IWrapsDriver, walk up the hierarchy of wrapped drivers until
- // either we find a class that does implement the desired interface, or is
- // no longer wrapping a driver.
- IWrapsDriver? driverWrapper = driver as IWrapsDriver;
- while (convertedDriver == null && driverWrapper != null)
- {
- convertedDriver = driverWrapper.WrappedDriver as T;
- driverWrapper = driverWrapper.WrappedDriver as IWrapsDriver;
- }
+ convertedDriver = driverWrapper.WrappedDriver as T;
+ driverWrapper = driverWrapper.WrappedDriver as IWrapsDriver;
}
-
- return convertedDriver;
}
+
+ return convertedDriver;
}
}
diff --git a/dotnet/src/support/UI/ILoadableComponent.cs b/dotnet/src/support/UI/ILoadableComponent.cs
index 4b86420c1ee17..e69f6f885b07c 100644
--- a/dotnet/src/support/UI/ILoadableComponent.cs
+++ b/dotnet/src/support/UI/ILoadableComponent.cs
@@ -17,31 +17,30 @@
// under the License.
//
-namespace OpenQA.Selenium.Support.UI
+namespace OpenQA.Selenium.Support.UI;
+
+///
+/// Interface allows for the component to be used in Nested Component scenarios such that the
+/// child component class does not have to declare the generic type of the parent explicitly.
+///
+///
+/// public class HypotheticalLoadableComponent : LoadableComponent<T> {
+/// ILoadableComponent parent;
+/// public HypotheticalLoadableComponent(ILoadableComponent parent) {
+/// this.parent = parent;
+/// }
+/// protected void EvaluateLoadedStatus() { //code to determine loaded state }
+/// protected void ExecuteLoad() {
+/// parent.Load(); //loads the parent
+/// //code to load this component
+/// }
+/// }
+///
+public interface ILoadableComponent
{
///
- /// Interface allows for the component to be used in Nested Component scenarios such that the
- /// child component class does not have to declare the generic type of the parent explicitly.
+ /// Loads the component.
///
- ///
- /// public class HypotheticalLoadableComponent : LoadableComponent<T> {
- /// ILoadableComponent parent;
- /// public HypotheticalLoadableComponent(ILoadableComponent parent) {
- /// this.parent = parent;
- /// }
- /// protected void EvaluateLoadedStatus() { //code to determine loaded state }
- /// protected void ExecuteLoad() {
- /// parent.Load(); //loads the parent
- /// //code to load this component
- /// }
- /// }
- ///
- public interface ILoadableComponent
- {
- ///
- /// Loads the component.
- ///
- /// A reference to this .
- ILoadableComponent Load();
- }
+ /// A reference to this .
+ ILoadableComponent Load();
}
diff --git a/dotnet/src/support/UI/LoadableComponentException.cs b/dotnet/src/support/UI/LoadableComponentException.cs
index 82bcef512a345..ad5d0fbe444c2 100644
--- a/dotnet/src/support/UI/LoadableComponentException.cs
+++ b/dotnet/src/support/UI/LoadableComponentException.cs
@@ -19,43 +19,42 @@
using System;
-namespace OpenQA.Selenium.Support.UI
+namespace OpenQA.Selenium.Support.UI;
+
+///
+/// This exception is thrown by to indicate that
+/// the component was not successfully loaded.
+///
+[Serializable]
+public class LoadableComponentException : WebDriverException
{
///
- /// This exception is thrown by to indicate that
- /// the component was not successfully loaded.
+ /// Initializes a new instance of the class.
///
- [Serializable]
- public class LoadableComponentException : WebDriverException
+ public LoadableComponentException()
{
- ///
- /// Initializes a new instance of the class.
- ///
- public LoadableComponentException()
- {
- }
+ }
- ///
- /// Initializes a new instance of the class with
- /// a specified error message.
- ///
- /// The message of the exception
- public LoadableComponentException(string? message)
- : base(message)
- {
- }
+ ///
+ /// Initializes a new instance of the class with
+ /// a specified error message.
+ ///
+ /// The message of the exception
+ public LoadableComponentException(string? message)
+ : base(message)
+ {
+ }
- ///
- /// Initializes a new instance of the class with
- /// a specified error message and a reference to the inner exception that is the
- /// cause of this exception.
- ///
- /// The error message that explains the reason for the exception.
- /// The exception that is the cause of the current exception,
- /// or if no inner exception is specified.
- public LoadableComponentException(string? message, Exception? innerException)
- : base(message, innerException)
- {
- }
+ ///
+ /// Initializes a new instance of the class with
+ /// a specified error message and a reference to the inner exception that is the
+ /// cause of this exception.
+ ///
+ /// The error message that explains the reason for the exception.
+ /// The exception that is the cause of the current exception,
+ /// or if no inner exception is specified.
+ public LoadableComponentException(string? message, Exception? innerException)
+ : base(message, innerException)
+ {
}
}
diff --git a/dotnet/src/support/UI/LoadableComponent{T}.cs b/dotnet/src/support/UI/LoadableComponent{T}.cs
index 14e66fc8b4293..2bf087b4699e9 100644
--- a/dotnet/src/support/UI/LoadableComponent{T}.cs
+++ b/dotnet/src/support/UI/LoadableComponent{T}.cs
@@ -17,126 +17,125 @@
// under the License.
//
-namespace OpenQA.Selenium.Support.UI
+namespace OpenQA.Selenium.Support.UI;
+
+///
+/// Represents any abstraction of something that can be loaded.
+/// This may be an entire web page, or simply a component within that page (such as a login box or menu) or even a service.
+///
+///
+/// // Example usage:
+/// new MyComponent().Load();
+///
+///
+///
+/// The type to be returned (normally the subclass' type)
+///
+/// After the method is called, the component will be loaded and ready for use.
+/// Overload the protected Load and IsLoaded members to both load a component and determine if the component is already loaded.
+///
+public abstract class LoadableComponent : ILoadableComponent
+ where T : LoadableComponent
{
///
- /// Represents any abstraction of something that can be loaded.
- /// This may be an entire web page, or simply a component within that page (such as a login box or menu) or even a service.
- ///
- ///
- /// // Example usage:
- /// new MyComponent().Load();
- ///
- ///
+ /// Gets or sets the message for the exception thrown when a component cannot be loaded
+ ///
+ public virtual string? UnableToLoadMessage { get; set; }
+
+ ///
+ /// Gets a value indicating whether the component is fully loaded.
///
- /// The type to be returned (normally the subclass' type)
///
- /// After the method is called, the component will be loaded and ready for use.
- /// Overload the protected Load and IsLoaded members to both load a component and determine if the component is already loaded.
+ /// When the component is loaded, this property will return true or false depending on
+ /// the execution of to indicate the not loaded state.
///
- public abstract class LoadableComponent : ILoadableComponent
- where T : LoadableComponent
+ protected bool IsLoaded
{
- ///
- /// Gets or sets the message for the exception thrown when a component cannot be loaded
- ///
- public virtual string? UnableToLoadMessage { get; set; }
-
- ///
- /// Gets a value indicating whether the component is fully loaded.
- ///
- ///
- /// When the component is loaded, this property will return true or false depending on
- /// the execution of to indicate the not loaded state.
- ///
- protected bool IsLoaded
+ get
{
- get
- {
- try
- {
- return this.EvaluateLoadedStatus();
- }
- catch (WebDriverException)
- {
- return false;
- }
- }
- }
-
- ///
- /// Ensure that the component is currently loaded.
- ///
- /// The loaded component.
- /// This is equivalent to the Get() method in Java version.
- public virtual T Load()
- {
- if (this.IsLoaded)
+ try
{
- return (T)this;
+ return this.EvaluateLoadedStatus();
}
- else
+ catch (WebDriverException)
{
- this.TryLoad();
- }
-
- if (!this.IsLoaded)
- {
- throw new LoadableComponentException(this.UnableToLoadMessage);
+ return false;
}
+ }
+ }
+ ///
+ /// Ensure that the component is currently loaded.
+ ///
+ /// The loaded component.
+ /// This is equivalent to the Get() method in Java version.
+ public virtual T Load()
+ {
+ if (this.IsLoaded)
+ {
return (T)this;
}
-
- ///
- /// Ensure that the component is currently loaded.
- ///
- /// The loaded instance.
- ILoadableComponent ILoadableComponent.Load()
+ else
{
- return (ILoadableComponent)this.Load();
+ this.TryLoad();
}
- ///
- /// HandleLoadError gives a subclass the opportunity to handle a that occurred
- /// during the execution of .
- ///
- /// The exception which occurs on load.
- protected virtual void HandleLoadError(WebDriverException ex)
+ if (!this.IsLoaded)
{
+ throw new LoadableComponentException(this.UnableToLoadMessage);
}
- ///
- /// When this method returns, the component modeled by the subclass should be fully loaded. This
- /// subclass is expected to navigate to an appropriate page or trigger loading the correct HTML
- /// should this be necessary.
- ///
- protected abstract void ExecuteLoad();
+ return (T)this;
+ }
+
+ ///
+ /// Ensure that the component is currently loaded.
+ ///
+ /// The loaded instance.
+ ILoadableComponent ILoadableComponent.Load()
+ {
+ return (ILoadableComponent)this.Load();
+ }
+
+ ///
+ /// HandleLoadError gives a subclass the opportunity to handle a that occurred
+ /// during the execution of .
+ ///
+ /// The exception which occurs on load.
+ protected virtual void HandleLoadError(WebDriverException ex)
+ {
+ }
- ///
- /// Determine whether or not the component is loaded. Subclasses are expected to provide the details
- /// to determine if the page or component is loaded.
- ///
- /// A boolean value indicating if the component is loaded.
- protected abstract bool EvaluateLoadedStatus();
+ ///
+ /// When this method returns, the component modeled by the subclass should be fully loaded. This
+ /// subclass is expected to navigate to an appropriate page or trigger loading the correct HTML
+ /// should this be necessary.
+ ///
+ protected abstract void ExecuteLoad();
- ///
- /// Attempts to load this component, providing an opportunity for the user to handle any errors encountered
- /// during the load process.
- ///
- /// A self-reference to this
- protected T TryLoad()
- {
- try
- {
- this.ExecuteLoad();
- }
- catch (WebDriverException e)
- {
- this.HandleLoadError(e);
- }
+ ///
+ /// Determine whether or not the component is loaded. Subclasses are expected to provide the details
+ /// to determine if the page or component is loaded.
+ ///
+ /// A boolean value indicating if the component is loaded.
+ protected abstract bool EvaluateLoadedStatus();
- return (T)this;
+ ///
+ /// Attempts to load this component, providing an opportunity for the user to handle any errors encountered
+ /// during the load process.
+ ///
+ /// A self-reference to this
+ protected T TryLoad()
+ {
+ try
+ {
+ this.ExecuteLoad();
}
+ catch (WebDriverException e)
+ {
+ this.HandleLoadError(e);
+ }
+
+ return (T)this;
}
}
diff --git a/dotnet/src/support/UI/PopupWindowFinder.cs b/dotnet/src/support/UI/PopupWindowFinder.cs
index 95e57a5ad0385..e7c65bb255e3c 100644
--- a/dotnet/src/support/UI/PopupWindowFinder.cs
+++ b/dotnet/src/support/UI/PopupWindowFinder.cs
@@ -21,123 +21,122 @@
using System.Collections.ObjectModel;
using System.Linq;
-namespace OpenQA.Selenium.Support.UI
+namespace OpenQA.Selenium.Support.UI;
+
+///
+/// Provides a mechanism by which the window handle of an invoked
+/// popup browser window may be determined.
+///
+///
+///
+/// // Store the current window handle so you can switch back to the
+/// // original window when you close the popup.
+/// string current = driver.CurrentWindowHandle;
+/// PopupWindowFinder finder = new PopupWindowFinder(driver);
+/// string newHandle = finder.Click(driver.FindElement(By.LinkText("Open new window")));
+/// driver.SwitchTo.Window(newHandle);
+///
+///
+public class PopupWindowFinder
{
+ private readonly IWebDriver driver;
+ private readonly TimeSpan timeout;
+ private readonly TimeSpan sleepInterval;
+
///
- /// Provides a mechanism by which the window handle of an invoked
- /// popup browser window may be determined.
+ /// Initializes a new instance of the class.
///
- ///
- ///
- /// // Store the current window handle so you can switch back to the
- /// // original window when you close the popup.
- /// string current = driver.CurrentWindowHandle;
- /// PopupWindowFinder finder = new PopupWindowFinder(driver);
- /// string newHandle = finder.Click(driver.FindElement(By.LinkText("Open new window")));
- /// driver.SwitchTo.Window(newHandle);
- ///
- ///
- public class PopupWindowFinder
+ /// The instance that is used
+ /// to manipulate the popup window.
+ /// When using this constructor overload, the timeout will be 5 seconds,
+ /// and the check for a new window will be performed every 250 milliseconds.
+ /// If is .
+ public PopupWindowFinder(IWebDriver driver)
+ : this(driver, DefaultTimeout, DefaultSleepInterval)
{
- private readonly IWebDriver driver;
- private readonly TimeSpan timeout;
- private readonly TimeSpan sleepInterval;
+ }
- ///
- /// Initializes a new instance of the class.
- ///
- /// The instance that is used
- /// to manipulate the popup window.
- /// When using this constructor overload, the timeout will be 5 seconds,
- /// and the check for a new window will be performed every 250 milliseconds.
- /// If is .
- public PopupWindowFinder(IWebDriver driver)
- : this(driver, DefaultTimeout, DefaultSleepInterval)
- {
- }
+ ///
+ /// Initializes a new instance of the class
+ /// with the specified timeout.
+ ///
+ /// The instance that is used
+ /// to manipulate the popup window.
+ /// The representing the amount of
+ /// time to wait for the popup window to appear.
+ /// When using this constructor overload, the check for a new window
+ /// will be performed every 250 milliseconds.
+ /// If is .
+ public PopupWindowFinder(IWebDriver driver, TimeSpan timeout)
+ : this(driver, timeout, DefaultSleepInterval)
+ {
+ }
- ///
- /// Initializes a new instance of the class
- /// with the specified timeout.
- ///
- /// The instance that is used
- /// to manipulate the popup window.
- /// The representing the amount of
- /// time to wait for the popup window to appear.
- /// When using this constructor overload, the check for a new window
- /// will be performed every 250 milliseconds.
- /// If is .
- public PopupWindowFinder(IWebDriver driver, TimeSpan timeout)
- : this(driver, timeout, DefaultSleepInterval)
- {
- }
+ ///
+ /// Initializes a new instance of the class
+ /// with the specified timeout and using the specified interval to check for
+ /// the existence of the new window.
+ ///
+ /// The instance that is used
+ /// to manipulate the popup window.
+ /// The representing the amount of
+ /// time to wait for the popup window to appear.
+ /// The representing the
+ /// amount of time to wait between checks of the available window handles.
+ /// If is .
+ public PopupWindowFinder(IWebDriver driver, TimeSpan timeout, TimeSpan sleepInterval)
+ {
+ this.driver = driver ?? throw new ArgumentNullException(nameof(driver));
+ this.timeout = timeout;
+ this.sleepInterval = sleepInterval;
+ }
+
+ private static TimeSpan DefaultTimeout => TimeSpan.FromSeconds(5);
- ///
- /// Initializes a new instance of the class
- /// with the specified timeout and using the specified interval to check for
- /// the existence of the new window.
- ///
- /// The instance that is used
- /// to manipulate the popup window.
- /// The representing the amount of
- /// time to wait for the popup window to appear.
- /// The representing the
- /// amount of time to wait between checks of the available window handles.
- /// If is .
- public PopupWindowFinder(IWebDriver driver, TimeSpan timeout, TimeSpan sleepInterval)
+ private static TimeSpan DefaultSleepInterval => TimeSpan.FromMilliseconds(250);
+
+ ///
+ /// Clicks on an element that is expected to trigger a popup browser window.
+ ///
+ /// The that, when clicked, invokes
+ /// the popup browser window.
+ /// The window handle of the popup browser window.
+ /// Thrown if no popup window appears within the specified timeout.
+ /// Thrown if the element to click is .
+ public string Click(IWebElement element)
+ {
+ if (element is null)
{
- this.driver = driver ?? throw new ArgumentNullException(nameof(driver));
- this.timeout = timeout;
- this.sleepInterval = sleepInterval;
+ throw new ArgumentNullException(nameof(element), "element cannot be null");
}
- private static TimeSpan DefaultTimeout => TimeSpan.FromSeconds(5);
-
- private static TimeSpan DefaultSleepInterval => TimeSpan.FromMilliseconds(250);
+ return this.Invoke(element.Click);
+ }
- ///
- /// Clicks on an element that is expected to trigger a popup browser window.
- ///
- /// The that, when clicked, invokes
- /// the popup browser window.
- /// The window handle of the popup browser window.
- /// Thrown if no popup window appears within the specified timeout.
- /// Thrown if the element to click is .
- public string Click(IWebElement element)
+ ///
+ /// Invokes a method that is expected to trigger a popup browser window.
+ ///
+ /// An that, when run, invokes
+ /// the popup browser window.
+ /// The window handle of the popup browser window.
+ /// Thrown if no popup window appears within the specified timeout.
+ /// Thrown if the action to invoke is .
+ public string Invoke(Action popupMethod)
+ {
+ if (popupMethod is null)
{
- if (element is null)
- {
- throw new ArgumentNullException(nameof(element), "element cannot be null");
- }
-
- return this.Invoke(element.Click);
+ throw new ArgumentNullException(nameof(popupMethod), "popupMethod cannot be null");
}
- ///
- /// Invokes a method that is expected to trigger a popup browser window.
- ///
- /// An that, when run, invokes
- /// the popup browser window.
- /// The window handle of the popup browser window.
- /// Thrown if no popup window appears within the specified timeout.
- /// Thrown if the action to invoke is .
- public string Invoke(Action popupMethod)
+ ReadOnlyCollection existingHandles = this.driver.WindowHandles;
+ popupMethod();
+ WebDriverWait wait = new WebDriverWait(SystemClock.Instance, this.driver, this.timeout, this.sleepInterval);
+ string popupHandle = wait.Until(driver =>
{
- if (popupMethod is null)
- {
- throw new ArgumentNullException(nameof(popupMethod), "popupMethod cannot be null");
- }
-
- ReadOnlyCollection existingHandles = this.driver.WindowHandles;
- popupMethod();
- WebDriverWait wait = new WebDriverWait(SystemClock.Instance, this.driver, this.timeout, this.sleepInterval);
- string popupHandle = wait.Until(driver =>
- {
- ReadOnlyCollection newHandles = driver.WindowHandles;
- return newHandles.Except(existingHandles, StringComparer.Ordinal).FirstOrDefault();
- });
+ ReadOnlyCollection newHandles = driver.WindowHandles;
+ return newHandles.Except(existingHandles, StringComparer.Ordinal).FirstOrDefault();
+ });
- return popupHandle;
- }
+ return popupHandle;
}
}
diff --git a/dotnet/src/support/UI/SelectElement.cs b/dotnet/src/support/UI/SelectElement.cs
index 070554d54192c..488d4b3d41e45 100644
--- a/dotnet/src/support/UI/SelectElement.cs
+++ b/dotnet/src/support/UI/SelectElement.cs
@@ -23,429 +23,428 @@
using System.Globalization;
using System.Text;
-namespace OpenQA.Selenium.Support.UI
+namespace OpenQA.Selenium.Support.UI;
+
+///
+/// Provides a convenience method for manipulating selections of options in an HTML select element.
+///
+public class SelectElement : IWrapsElement
{
///
- /// Provides a convenience method for manipulating selections of options in an HTML select element.
+ /// Initializes a new instance of the class.
///
- public class SelectElement : IWrapsElement
+ /// The element to be wrapped
+ /// Thrown when the object is
+ /// Thrown when the element wrapped is not a <select> element.
+ public SelectElement(IWebElement element)
{
- ///
- /// Initializes a new instance of the class.
- ///
- /// The element to be wrapped
- /// Thrown when the object is
- /// Thrown when the element wrapped is not a <select> element.
- public SelectElement(IWebElement element)
+ if (element is null)
{
- if (element is null)
- {
- throw new ArgumentNullException(nameof(element), "element cannot be null");
- }
+ throw new ArgumentNullException(nameof(element), "element cannot be null");
+ }
- string tagName = element.TagName;
+ string tagName = element.TagName;
- if (string.IsNullOrEmpty(tagName) || !string.Equals(tagName, "select", StringComparison.OrdinalIgnoreCase))
- {
- throw new UnexpectedTagNameException("select", tagName);
- }
+ if (string.IsNullOrEmpty(tagName) || !string.Equals(tagName, "select", StringComparison.OrdinalIgnoreCase))
+ {
+ throw new UnexpectedTagNameException("select", tagName);
+ }
- this.WrappedElement = element;
+ this.WrappedElement = element;
- // let check if it's a multiple
- string? attribute = element.GetAttribute("multiple");
- this.IsMultiple = attribute != null && !attribute.Equals("false", StringComparison.OrdinalIgnoreCase);
- }
+ // let check if it's a multiple
+ string? attribute = element.GetAttribute("multiple");
+ this.IsMultiple = attribute != null && !attribute.Equals("false", StringComparison.OrdinalIgnoreCase);
+ }
+
+ ///
+ /// Gets the wrapped by this object.
+ ///
+ public IWebElement WrappedElement { get; }
+
+ ///
+ /// Gets a value indicating whether the parent element supports multiple selections.
+ ///
+ public bool IsMultiple { get; }
+
+ ///
+ /// Gets the list of options for the select element.
+ ///
+ public IList Options => this.WrappedElement.FindElements(By.TagName("option"));
- ///
- /// Gets the wrapped by this object.
- ///
- public IWebElement WrappedElement { get; }
-
- ///
- /// Gets a value indicating whether the parent element supports multiple selections.
- ///
- public bool IsMultiple { get; }
-
- ///
- /// Gets the list of options for the select element.
- ///
- public IList Options => this.WrappedElement.FindElements(By.TagName("option"));
-
- ///
- /// Gets the selected item within the select element.
- ///
- /// If more than one item is selected this will return the first item.
- /// Thrown if no option is selected.
- public IWebElement SelectedOption
+ ///
+ /// Gets the selected item within the select element.
+ ///
+ /// If more than one item is selected this will return the first item.
+ /// Thrown if no option is selected.
+ public IWebElement SelectedOption
+ {
+ get
{
- get
+ foreach (IWebElement option in this.Options)
{
- foreach (IWebElement option in this.Options)
+ if (option.Selected)
{
- if (option.Selected)
- {
- return option;
- }
+ return option;
}
-
- throw new NoSuchElementException("No option is selected");
}
+
+ throw new NoSuchElementException("No option is selected");
}
+ }
- ///
- /// Gets all of the selected options within the select element.
- ///
- public IList AllSelectedOptions
+ ///
+ /// Gets all of the selected options within the select element.
+ ///
+ public IList AllSelectedOptions
+ {
+ get
{
- get
+ List returnValue = new List();
+ foreach (IWebElement option in this.Options)
{
- List returnValue = new List();
- foreach (IWebElement option in this.Options)
+ if (option.Selected)
{
- if (option.Selected)
- {
- returnValue.Add(option);
- }
+ returnValue.Add(option);
}
-
- return returnValue;
}
+
+ return returnValue;
+ }
+ }
+
+ ///
+ /// Select all options by the text displayed.
+ ///
+ /// The text of the option to be selected.
+ /// Default value is false. If true a partial match on the Options list will be performed, otherwise exact match.
+ /// When given "Bar" this method would select an option like:
+ ///
+ /// <option value="foo">Bar</option>
+ ///
+ ///
+ /// If is .
+ /// Thrown if there is no element with the given text present.
+ public void SelectByText(string text, bool partialMatch = false)
+ {
+ if (text is null)
+ {
+ throw new ArgumentNullException(nameof(text), "text must not be null");
+ }
+
+ bool matched = false;
+ ReadOnlyCollection options;
+
+ if (!partialMatch)
+ {
+ // try to find the option via XPATH ...
+ options = this.WrappedElement.FindElements(By.XPath(".//option[normalize-space(.) = " + EscapeQuotes(text) + "]"));
+ }
+ else
+ {
+ options = this.WrappedElement.FindElements(By.XPath(".//option[contains(normalize-space(.), " + EscapeQuotes(text) + ")]"));
}
- ///
- /// Select all options by the text displayed.
- ///
- /// The text of the option to be selected.
- /// Default value is false. If true a partial match on the Options list will be performed, otherwise exact match.
- /// When given "Bar" this method would select an option like:
- ///
- /// <option value="foo">Bar</option>
- ///
- ///
- /// If is .
- /// Thrown if there is no element with the given text present.
- public void SelectByText(string text, bool partialMatch = false)
+ foreach (IWebElement option in options)
{
- if (text is null)
+ SetSelected(option, true);
+ if (!this.IsMultiple)
{
- throw new ArgumentNullException(nameof(text), "text must not be null");
+ return;
}
- bool matched = false;
- ReadOnlyCollection options;
+ matched = true;
+ }
- if (!partialMatch)
+ if (options.Count == 0 && text.Contains(" "))
+ {
+ string substringWithoutSpace = GetLongestSubstringWithoutSpace(text);
+ IList candidates;
+ if (string.IsNullOrEmpty(substringWithoutSpace))
{
- // try to find the option via XPATH ...
- options = this.WrappedElement.FindElements(By.XPath(".//option[normalize-space(.) = " + EscapeQuotes(text) + "]"));
+ // hmm, text is either empty or contains only spaces - get all options ...
+ candidates = this.WrappedElement.FindElements(By.TagName("option"));
}
else
{
- options = this.WrappedElement.FindElements(By.XPath(".//option[contains(normalize-space(.), " + EscapeQuotes(text) + ")]"));
- }
-
- foreach (IWebElement option in options)
- {
- SetSelected(option, true);
- if (!this.IsMultiple)
- {
- return;
- }
-
- matched = true;
+ // get candidates via XPATH ...
+ candidates = this.WrappedElement.FindElements(By.XPath(".//option[contains(., " + EscapeQuotes(substringWithoutSpace) + ")]"));
}
- if (options.Count == 0 && text.Contains(" "))
+ foreach (IWebElement option in candidates)
{
- string substringWithoutSpace = GetLongestSubstringWithoutSpace(text);
- IList candidates;
- if (string.IsNullOrEmpty(substringWithoutSpace))
+ if (text == option.Text)
{
- // hmm, text is either empty or contains only spaces - get all options ...
- candidates = this.WrappedElement.FindElements(By.TagName("option"));
- }
- else
- {
- // get candidates via XPATH ...
- candidates = this.WrappedElement.FindElements(By.XPath(".//option[contains(., " + EscapeQuotes(substringWithoutSpace) + ")]"));
- }
-
- foreach (IWebElement option in candidates)
- {
- if (text == option.Text)
+ SetSelected(option, true);
+ if (!this.IsMultiple)
{
- SetSelected(option, true);
- if (!this.IsMultiple)
- {
- return;
- }
-
- matched = true;
+ return;
}
+
+ matched = true;
}
}
+ }
- if (!matched)
+ if (!matched)
+ {
+ throw new NoSuchElementException("Cannot locate element with text: " + text);
+ }
+ }
+
+ ///
+ /// Select an option by the value.
+ ///
+ /// The value of the option to be selected.
+ /// When given "foo" this method will select an option like:
+ ///
+ /// <option value="foo">Bar</option>
+ ///
+ ///
+ /// Thrown when no element with the specified value is found.
+ public void SelectByValue(string value)
+ {
+ StringBuilder builder = new StringBuilder(".//option[@value = ");
+ builder.Append(EscapeQuotes(value));
+ builder.Append("]");
+ IList options = this.WrappedElement.FindElements(By.XPath(builder.ToString()));
+
+ bool matched = false;
+ foreach (IWebElement option in options)
+ {
+ SetSelected(option, true);
+ if (!this.IsMultiple)
{
- throw new NoSuchElementException("Cannot locate element with text: " + text);
+ return;
}
+
+ matched = true;
}
- ///
- /// Select an option by the value.
- ///
- /// The value of the option to be selected.
- /// When given "foo" this method will select an option like:
- ///
- /// <option value="foo">Bar</option>
- ///
- ///
- /// Thrown when no element with the specified value is found.
- public void SelectByValue(string value)
+ if (!matched)
{
- StringBuilder builder = new StringBuilder(".//option[@value = ");
- builder.Append(EscapeQuotes(value));
- builder.Append("]");
- IList options = this.WrappedElement.FindElements(By.XPath(builder.ToString()));
-
- bool matched = false;
- foreach (IWebElement option in options)
- {
- SetSelected(option, true);
- if (!this.IsMultiple)
- {
- return;
- }
+ throw new NoSuchElementException("Cannot locate option with value: " + value);
+ }
+ }
- matched = true;
- }
+ ///
+ /// Select the option by the index, as determined by the "index" attribute of the element.
+ ///
+ /// The value of the index attribute of the option to be selected.
+ /// Thrown when no element exists with the specified index attribute.
+ public void SelectByIndex(int index)
+ {
+ string match = index.ToString(CultureInfo.InvariantCulture);
- if (!matched)
+ foreach (IWebElement option in this.Options)
+ {
+ if (option.GetAttribute("index") == match)
{
- throw new NoSuchElementException("Cannot locate option with value: " + value);
+ SetSelected(option, true);
+ return;
}
}
- ///
- /// Select the option by the index, as determined by the "index" attribute of the element.
- ///
- /// The value of the index attribute of the option to be selected.
- /// Thrown when no element exists with the specified index attribute.
- public void SelectByIndex(int index)
+ throw new NoSuchElementException("Cannot locate option with index: " + index);
+ }
+
+ ///
+ /// Clear all selected entries. This is only valid when the SELECT supports multiple selections.
+ ///
+ /// Thrown when attempting to deselect all options from a SELECT
+ /// that does not support multiple selections.
+ public void DeselectAll()
+ {
+ if (!this.IsMultiple)
{
- string match = index.ToString(CultureInfo.InvariantCulture);
+ throw new InvalidOperationException("You may only deselect all options if multi-select is supported");
+ }
- foreach (IWebElement option in this.Options)
- {
- if (option.GetAttribute("index") == match)
- {
- SetSelected(option, true);
- return;
- }
- }
+ foreach (IWebElement option in this.Options)
+ {
+ SetSelected(option, false);
+ }
+ }
- throw new NoSuchElementException("Cannot locate option with index: " + index);
+ ///
+ /// Deselect the option by the text displayed.
+ ///
+ /// Thrown when attempting to deselect option from a SELECT
+ /// that does not support multiple selections.
+ /// Thrown when no element exists with the specified test attribute.
+ /// The text of the option to be deselected.
+ /// When given "Bar" this method would deselect an option like:
+ ///
+ /// <option value="foo">Bar</option>
+ ///
+ ///
+ public void DeselectByText(string text)
+ {
+ if (!this.IsMultiple)
+ {
+ throw new InvalidOperationException("You may only deselect option if multi-select is supported");
}
- ///
- /// Clear all selected entries. This is only valid when the SELECT supports multiple selections.
- ///
- /// Thrown when attempting to deselect all options from a SELECT
- /// that does not support multiple selections.
- public void DeselectAll()
+ bool matched = false;
+ StringBuilder builder = new StringBuilder(".//option[normalize-space(.) = ");
+ builder.Append(EscapeQuotes(text));
+ builder.Append("]");
+ IList options = this.WrappedElement.FindElements(By.XPath(builder.ToString()));
+ foreach (IWebElement option in options)
{
- if (!this.IsMultiple)
- {
- throw new InvalidOperationException("You may only deselect all options if multi-select is supported");
- }
+ SetSelected(option, false);
+ matched = true;
+ }
- foreach (IWebElement option in this.Options)
- {
- SetSelected(option, false);
- }
+ if (!matched)
+ {
+ throw new NoSuchElementException("Cannot locate option with text: " + text);
}
+ }
- ///
- /// Deselect the option by the text displayed.
- ///
- /// Thrown when attempting to deselect option from a SELECT
- /// that does not support multiple selections.
- /// Thrown when no element exists with the specified test attribute.
- /// The text of the option to be deselected.
- /// When given "Bar" this method would deselect an option like:
- ///
- /// <option value="foo">Bar</option>
- ///
- ///
- public void DeselectByText(string text)
+ ///
+ /// Deselect the option having value matching the specified text.
+ ///
+ /// Thrown when attempting to deselect option from a SELECT
+ /// that does not support multiple selections.
+ /// Thrown when no element exists with the specified value attribute.
+ /// The value of the option to deselect.
+ /// When given "foo" this method will deselect an option like:
+ ///
+ /// <option value="foo">Bar</option>
+ ///
+ ///
+ public void DeselectByValue(string value)
+ {
+ if (!this.IsMultiple)
{
- if (!this.IsMultiple)
- {
- throw new InvalidOperationException("You may only deselect option if multi-select is supported");
- }
+ throw new InvalidOperationException("You may only deselect option if multi-select is supported");
+ }
- bool matched = false;
- StringBuilder builder = new StringBuilder(".//option[normalize-space(.) = ");
- builder.Append(EscapeQuotes(text));
- builder.Append("]");
- IList options = this.WrappedElement.FindElements(By.XPath(builder.ToString()));
- foreach (IWebElement option in options)
- {
- SetSelected(option, false);
- matched = true;
- }
+ bool matched = false;
+ StringBuilder builder = new StringBuilder(".//option[@value = ");
+ builder.Append(EscapeQuotes(value));
+ builder.Append("]");
+ IList options = this.WrappedElement.FindElements(By.XPath(builder.ToString()));
+ foreach (IWebElement option in options)
+ {
+ SetSelected(option, false);
+ matched = true;
+ }
- if (!matched)
- {
- throw new NoSuchElementException("Cannot locate option with text: " + text);
- }
+ if (!matched)
+ {
+ throw new NoSuchElementException("Cannot locate option with value: " + value);
}
+ }
- ///
- /// Deselect the option having value matching the specified text.
- ///
- /// Thrown when attempting to deselect option from a SELECT
- /// that does not support multiple selections.
- /// Thrown when no element exists with the specified value attribute.
- /// The value of the option to deselect.
- /// When given "foo" this method will deselect an option like:
- ///
- /// <option value="foo">Bar</option>
- ///
- ///
- public void DeselectByValue(string value)
+ ///
+ /// Deselect the option by the index, as determined by the "index" attribute of the element.
+ ///
+ /// Thrown when attempting to deselect option from a SELECT
+ /// that does not support multiple selections.
+ /// Thrown when no element exists with the specified index attribute.
+ /// The value of the index attribute of the option to deselect.
+ public void DeselectByIndex(int index)
+ {
+ if (!this.IsMultiple)
{
- if (!this.IsMultiple)
- {
- throw new InvalidOperationException("You may only deselect option if multi-select is supported");
- }
+ throw new InvalidOperationException("You may only deselect option if multi-select is supported");
+ }
- bool matched = false;
- StringBuilder builder = new StringBuilder(".//option[@value = ");
- builder.Append(EscapeQuotes(value));
- builder.Append("]");
- IList options = this.WrappedElement.FindElements(By.XPath(builder.ToString()));
- foreach (IWebElement option in options)
+ string match = index.ToString(CultureInfo.InvariantCulture);
+ foreach (IWebElement option in this.Options)
+ {
+ if (match == option.GetAttribute("index"))
{
SetSelected(option, false);
- matched = true;
- }
-
- if (!matched)
- {
- throw new NoSuchElementException("Cannot locate option with value: " + value);
+ return;
}
}
- ///
- /// Deselect the option by the index, as determined by the "index" attribute of the element.
- ///
- /// Thrown when attempting to deselect option from a SELECT
- /// that does not support multiple selections.
- /// Thrown when no element exists with the specified index attribute.
- /// The value of the index attribute of the option to deselect.
- public void DeselectByIndex(int index)
+ throw new NoSuchElementException("Cannot locate option with index: " + index);
+ }
+
+ private static string EscapeQuotes(string toEscape)
+ {
+ // Convert strings with both quotes and ticks into: foo'"bar -> concat("foo'", '"', "bar")
+ if (toEscape.IndexOf("\"", StringComparison.OrdinalIgnoreCase) > -1 && toEscape.IndexOf("'", StringComparison.OrdinalIgnoreCase) > -1)
{
- if (!this.IsMultiple)
+ bool quoteIsLast = false;
+ if (toEscape.LastIndexOf("\"", StringComparison.OrdinalIgnoreCase) == toEscape.Length - 1)
{
- throw new InvalidOperationException("You may only deselect option if multi-select is supported");
+ quoteIsLast = true;
}
- string match = index.ToString(CultureInfo.InvariantCulture);
- foreach (IWebElement option in this.Options)
+ List substrings = new List(toEscape.Split('\"'));
+ if (quoteIsLast && string.IsNullOrEmpty(substrings[substrings.Count - 1]))
{
- if (match == option.GetAttribute("index"))
- {
- SetSelected(option, false);
- return;
- }
+ // If the last character is a quote ('"'), we end up with an empty entry
+ // at the end of the list, which is unnecessary. We don't want to split
+ // ignoring *all* empty entries, since that might mask legitimate empty
+ // strings. Instead, just remove the empty ending entry.
+ substrings.RemoveAt(substrings.Count - 1);
}
- throw new NoSuchElementException("Cannot locate option with index: " + index);
- }
-
- private static string EscapeQuotes(string toEscape)
- {
- // Convert strings with both quotes and ticks into: foo'"bar -> concat("foo'", '"', "bar")
- if (toEscape.IndexOf("\"", StringComparison.OrdinalIgnoreCase) > -1 && toEscape.IndexOf("'", StringComparison.OrdinalIgnoreCase) > -1)
+ StringBuilder quoted = new StringBuilder("concat(");
+ for (int i = 0; i < substrings.Count; i++)
{
- bool quoteIsLast = false;
- if (toEscape.LastIndexOf("\"", StringComparison.OrdinalIgnoreCase) == toEscape.Length - 1)
- {
- quoteIsLast = true;
- }
-
- List substrings = new List(toEscape.Split('\"'));
- if (quoteIsLast && string.IsNullOrEmpty(substrings[substrings.Count - 1]))
- {
- // If the last character is a quote ('"'), we end up with an empty entry
- // at the end of the list, which is unnecessary. We don't want to split
- // ignoring *all* empty entries, since that might mask legitimate empty
- // strings. Instead, just remove the empty ending entry.
- substrings.RemoveAt(substrings.Count - 1);
- }
-
- StringBuilder quoted = new StringBuilder("concat(");
- for (int i = 0; i < substrings.Count; i++)
+ quoted.Append("\"").Append(substrings[i]).Append("\"");
+ if (i == substrings.Count - 1)
{
- quoted.Append("\"").Append(substrings[i]).Append("\"");
- if (i == substrings.Count - 1)
+ if (quoteIsLast)
{
- if (quoteIsLast)
- {
- quoted.Append(", '\"')");
- }
- else
- {
- quoted.Append(")");
- }
+ quoted.Append(", '\"')");
}
else
{
- quoted.Append(", '\"', ");
+ quoted.Append(")");
}
}
-
- return quoted.ToString();
+ else
+ {
+ quoted.Append(", '\"', ");
+ }
}
- // Escape string with just a quote into being single quoted: f"oo -> 'f"oo'
- if (toEscape.IndexOf("\"", StringComparison.OrdinalIgnoreCase) > -1)
- {
- return string.Format(CultureInfo.InvariantCulture, "'{0}'", toEscape);
- }
+ return quoted.ToString();
+ }
- // Otherwise return the quoted string
- return string.Format(CultureInfo.InvariantCulture, "\"{0}\"", toEscape);
+ // Escape string with just a quote into being single quoted: f"oo -> 'f"oo'
+ if (toEscape.IndexOf("\"", StringComparison.OrdinalIgnoreCase) > -1)
+ {
+ return string.Format(CultureInfo.InvariantCulture, "'{0}'", toEscape);
}
- private static string GetLongestSubstringWithoutSpace(string s)
+ // Otherwise return the quoted string
+ return string.Format(CultureInfo.InvariantCulture, "\"{0}\"", toEscape);
+ }
+
+ private static string GetLongestSubstringWithoutSpace(string s)
+ {
+ string result = string.Empty;
+ foreach (string substring in s.Split(' '))
{
- string result = string.Empty;
- foreach (string substring in s.Split(' '))
+ if (substring.Length > result.Length)
{
- if (substring.Length > result.Length)
- {
- result = substring;
- }
+ result = substring;
}
-
- return result;
}
- private static void SetSelected(IWebElement option, bool select)
+ return result;
+ }
+
+ private static void SetSelected(IWebElement option, bool select)
+ {
+ if (select && !option.Enabled)
{
- if (select && !option.Enabled)
- {
- throw new InvalidOperationException("You may not select a disabled option");
- }
+ throw new InvalidOperationException("You may not select a disabled option");
+ }
- bool isSelected = option.Selected;
- if ((!isSelected && select) || (isSelected && !select))
- {
- option.Click();
- }
+ bool isSelected = option.Selected;
+ if ((!isSelected && select) || (isSelected && !select))
+ {
+ option.Click();
}
}
}
diff --git a/dotnet/src/support/UI/SlowLoadableComponent{T}.cs b/dotnet/src/support/UI/SlowLoadableComponent{T}.cs
index 900e162b28c04..868204995af2f 100644
--- a/dotnet/src/support/UI/SlowLoadableComponent{T}.cs
+++ b/dotnet/src/support/UI/SlowLoadableComponent{T}.cs
@@ -21,121 +21,120 @@
using System.Globalization;
using System.Threading;
-namespace OpenQA.Selenium.Support.UI
+namespace OpenQA.Selenium.Support.UI;
+
+///
+/// A which might not have finished loading when Load() returns.
+/// After a call to Load(), the IsLoaded property should continue to return false until the component has fully loaded.
+///
+///
+/// // Example usage:
+/// new MySlowComponent().Load();
+///
+///
+///
+/// Override the HandleErrors() method to check for error conditions which caused to fail.
+/// The type to be returned (normally the subclass' type)
+public abstract class SlowLoadableComponent : LoadableComponent
+ where T : SlowLoadableComponent
{
///
- /// A which might not have finished loading when Load() returns.
- /// After a call to Load(), the IsLoaded property should continue to return false until the component has fully loaded.
- ///
- ///
- /// // Example usage:
- /// new MySlowComponent().Load();
- ///
- ///
+ /// Initializes a new instance of the class.
///
- /// Override the HandleErrors() method to check for error conditions which caused to fail.
- /// The type to be returned (normally the subclass' type)
- public abstract class SlowLoadableComponent : LoadableComponent
- where T : SlowLoadableComponent
+ /// The within which the component should be loaded.
+ protected SlowLoadableComponent(TimeSpan timeout)
+ : this(timeout, SystemClock.Instance)
{
- ///
- /// Initializes a new instance of the class.
- ///
- /// The within which the component should be loaded.
- protected SlowLoadableComponent(TimeSpan timeout)
- : this(timeout, SystemClock.Instance)
- {
- }
+ }
- ///
- /// Initializes a new instance of the class.
- ///
- /// The within which the component should be loaded.
- /// The to use when measuring the timeout.
- /// If is .
- protected SlowLoadableComponent(TimeSpan timeout, IClock clock)
- {
- this.Clock = clock ?? throw new ArgumentNullException(nameof(clock));
- this.Timeout = timeout;
- }
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The within which the component should be loaded.
+ /// The to use when measuring the timeout.
+ /// If is .
+ protected SlowLoadableComponent(TimeSpan timeout, IClock clock)
+ {
+ this.Clock = clock ?? throw new ArgumentNullException(nameof(clock));
+ this.Timeout = timeout;
+ }
- ///
- /// Gets or sets the time to sleep between each check of the load status of the component.
- ///
- public TimeSpan SleepInterval { get; set; } = TimeSpan.FromMilliseconds(200);
+ ///
+ /// Gets or sets the time to sleep between each check of the load status of the component.
+ ///
+ public TimeSpan SleepInterval { get; set; } = TimeSpan.FromMilliseconds(200);
- ///
- /// Gets the timeout interval before which this component must be considered loaded.
- ///
- protected TimeSpan Timeout { get; }
+ ///
+ /// Gets the timeout interval before which this component must be considered loaded.
+ ///
+ protected TimeSpan Timeout { get; }
- ///
- /// Gets the clock object providing timing for monitoring the load status of this component.
- ///
- protected IClock Clock { get; }
+ ///
+ /// Gets the clock object providing timing for monitoring the load status of this component.
+ ///
+ protected IClock Clock { get; }
- ///
- /// Ensures that the component is currently loaded.
- ///
- /// The loaded component.
- /// This is equivalent to the Get() method in Java version.
- public override T Load()
+ ///
+ /// Ensures that the component is currently loaded.
+ ///
+ /// The loaded component.
+ /// This is equivalent to the Get() method in Java version.
+ public override T Load()
+ {
+ if (this.IsLoaded)
{
- if (this.IsLoaded)
- {
- return (T)this;
- }
- else
- {
- this.TryLoad();
- }
-
- DateTime end = this.Clock.LaterBy(this.Timeout);
-
- while (this.Clock.IsNowBefore(end))
- {
- if (this.IsLoaded)
- {
- return (T)this;
- }
+ return (T)this;
+ }
+ else
+ {
+ this.TryLoad();
+ }
- this.HandleErrors();
- this.Wait();
- }
+ DateTime end = this.Clock.LaterBy(this.Timeout);
+ while (this.Clock.IsNowBefore(end))
+ {
if (this.IsLoaded)
{
return (T)this;
}
- else
- {
- if (string.IsNullOrEmpty(UnableToLoadMessage))
- {
- this.UnableToLoadMessage = string.Format(CultureInfo.InvariantCulture, "Timed out after {0} seconds.", this.Timeout.TotalSeconds);
- }
- throw new WebDriverTimeoutException(this.UnableToLoadMessage);
- }
+ this.HandleErrors();
+ this.Wait();
}
- ///
- /// Checks for well known error cases, which would mean that loading has finished, but an error
- /// condition was seen.
- ///
- ///
- /// This method should be overridden so that expected errors can be automatically handled.
- ///
- protected virtual void HandleErrors()
+ if (this.IsLoaded)
{
- // no-op by default
+ return (T)this;
}
-
- ///
- /// Waits between polls of the load status of this component.
- ///
- protected virtual void Wait()
+ else
{
- Thread.Sleep(this.SleepInterval);
+ if (string.IsNullOrEmpty(UnableToLoadMessage))
+ {
+ this.UnableToLoadMessage = string.Format(CultureInfo.InvariantCulture, "Timed out after {0} seconds.", this.Timeout.TotalSeconds);
+ }
+
+ throw new WebDriverTimeoutException(this.UnableToLoadMessage);
}
}
+
+ ///
+ /// Checks for well known error cases, which would mean that loading has finished, but an error
+ /// condition was seen.
+ ///
+ ///
+ /// This method should be overridden so that expected errors can be automatically handled.
+ ///
+ protected virtual void HandleErrors()
+ {
+ // no-op by default
+ }
+
+ ///
+ /// Waits between polls of the load status of this component.
+ ///
+ protected virtual void Wait()
+ {
+ Thread.Sleep(this.SleepInterval);
+ }
}
diff --git a/dotnet/src/support/UI/UnexpectedTagNameException.cs b/dotnet/src/support/UI/UnexpectedTagNameException.cs
index b9df3207fc4bc..9bc5672fd1a32 100644
--- a/dotnet/src/support/UI/UnexpectedTagNameException.cs
+++ b/dotnet/src/support/UI/UnexpectedTagNameException.cs
@@ -20,54 +20,53 @@
using System;
using System.Globalization;
-namespace OpenQA.Selenium.Support.UI
+namespace OpenQA.Selenium.Support.UI;
+
+///
+/// The exception thrown when using the Select class on a tag that
+/// does not support the HTML select element's selection semantics.
+///
+[Serializable]
+public class UnexpectedTagNameException : WebDriverException
{
///
- /// The exception thrown when using the Select class on a tag that
- /// does not support the HTML select element's selection semantics.
+ /// Initializes a new instance of the class with
+ /// the expected tag name and the actual tag name.
///
- [Serializable]
- public class UnexpectedTagNameException : WebDriverException
+ /// The tag name that was expected.
+ /// The actual tag name of the element.
+ public UnexpectedTagNameException(string expected, string actual)
+ : base(string.Format(CultureInfo.InvariantCulture, "Element should have been {0} but was {1}", expected, actual))
{
- ///
- /// Initializes a new instance of the class with
- /// the expected tag name and the actual tag name.
- ///
- /// The tag name that was expected.
- /// The actual tag name of the element.
- public UnexpectedTagNameException(string expected, string actual)
- : base(string.Format(CultureInfo.InvariantCulture, "Element should have been {0} but was {1}", expected, actual))
- {
- }
+ }
- ///
- /// Initializes a new instance of the class.
- ///
- public UnexpectedTagNameException()
- {
- }
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public UnexpectedTagNameException()
+ {
+ }
- ///
- /// Initializes a new instance of the class with
- /// a specified error message.
- ///
- /// The message of the exception
- public UnexpectedTagNameException(string? message)
- : base(message)
- {
- }
+ ///
+ /// Initializes a new instance of the class with
+ /// a specified error message.
+ ///
+ /// The message of the exception
+ public UnexpectedTagNameException(string? message)
+ : base(message)
+ {
+ }
- ///
- /// Initializes a new instance of the class with
- /// a specified error message and a reference to the inner exception that is the
- /// cause of this exception.
- ///
- /// The error message that explains the reason for the exception.
- /// The exception that is the cause of the current exception,
- /// or if no inner exception is specified.
- public UnexpectedTagNameException(string? message, Exception? innerException)
- : base(message, innerException)
- {
- }
+ ///
+ /// Initializes a new instance of the class with
+ /// a specified error message and a reference to the inner exception that is the
+ /// cause of this exception.
+ ///
+ /// The error message that explains the reason for the exception.
+ /// The exception that is the cause of the current exception,
+ /// or if no inner exception is specified.
+ public UnexpectedTagNameException(string? message, Exception? innerException)
+ : base(message, innerException)
+ {
}
}
diff --git a/dotnet/src/webdriver/Alert.cs b/dotnet/src/webdriver/Alert.cs
index fb32d3e0fb0c4..3f7e671a18e53 100644
--- a/dotnet/src/webdriver/Alert.cs
+++ b/dotnet/src/webdriver/Alert.cs
@@ -20,68 +20,67 @@
using System;
using System.Collections.Generic;
-namespace OpenQA.Selenium
+namespace OpenQA.Selenium;
+
+///
+/// Defines the interface through which the user can manipulate JavaScript alerts.
+///
+internal class Alert : IAlert
{
+ private readonly WebDriver driver;
+
///
- /// Defines the interface through which the user can manipulate JavaScript alerts.
+ /// Initializes a new instance of the class.
///
- internal class Alert : IAlert
+ /// The for which the alerts will be managed.
+ public Alert(WebDriver driver)
{
- private readonly WebDriver driver;
+ this.driver = driver;
+ }
- ///
- /// Initializes a new instance of the class.
- ///
- /// The for which the alerts will be managed.
- public Alert(WebDriver driver)
+ ///
+ /// Gets the text of the alert.
+ ///
+ public string? Text
+ {
+ get
{
- this.driver = driver;
+ Response commandResponse = this.driver.Execute(DriverCommand.GetAlertText, null);
+ return (string?)commandResponse.Value;
}
+ }
- ///
- /// Gets the text of the alert.
- ///
- public string? Text
- {
- get
- {
- Response commandResponse = this.driver.Execute(DriverCommand.GetAlertText, null);
- return (string?)commandResponse.Value;
- }
- }
+ ///
+ /// Dismisses the alert.
+ ///
+ public void Dismiss()
+ {
+ this.driver.Execute(DriverCommand.DismissAlert, null);
+ }
- ///
- /// Dismisses the alert.
- ///
- public void Dismiss()
- {
- this.driver.Execute(DriverCommand.DismissAlert, null);
- }
+ ///
+ /// Accepts the alert.
+ ///
+ public void Accept()
+ {
+ this.driver.Execute(DriverCommand.AcceptAlert, null);
+ }
- ///
- /// Accepts the alert.
- ///
- public void Accept()
+ ///
+ /// Sends keys to the alert.
+ ///
+ /// The keystrokes to send.
+ /// If is .
+ public void SendKeys(string keysToSend)
+ {
+ if (keysToSend is null)
{
- this.driver.Execute(DriverCommand.AcceptAlert, null);
+ throw new ArgumentNullException(nameof(keysToSend), "Keys to send must not be null.");
}
- ///
- /// Sends keys to the alert.
- ///
- /// The keystrokes to send.
- /// If is .
- public void SendKeys(string keysToSend)
- {
- if (keysToSend is null)
- {
- throw new ArgumentNullException(nameof(keysToSend), "Keys to send must not be null.");
- }
-
- Dictionary parameters = new Dictionary();
- parameters.Add("text", keysToSend);
+ Dictionary parameters = new Dictionary();
+ parameters.Add("text", keysToSend);
- this.driver.Execute(DriverCommand.SetAlertValue, parameters);
- }
+ this.driver.Execute(DriverCommand.SetAlertValue, parameters);
}
}
diff --git a/dotnet/src/webdriver/By.cs b/dotnet/src/webdriver/By.cs
index b538a727d7265..b280d54589493 100644
--- a/dotnet/src/webdriver/By.cs
+++ b/dotnet/src/webdriver/By.cs
@@ -24,384 +24,383 @@
using System.Globalization;
using System.Text.RegularExpressions;
-namespace OpenQA.Selenium
+namespace OpenQA.Selenium;
+
+///
+/// Provides a mechanism by which to find elements within a document.
+///
+/// It is possible to create your own locating mechanisms for finding documents.
+/// In order to do this,subclass this class and override the protected methods. However,
+/// it is expected that that all subclasses rely on the basic finding mechanisms provided
+/// through static methods of this class. An example of this can be found in OpenQA.Support.ByIdOrName
+///
+[Serializable]
+public class By
{
+ private const string CssSelectorMechanism = "css selector";
+ private const string XPathSelectorMechanism = "xpath";
+ private const string TagNameMechanism = "tag name";
+ private const string LinkTextMechanism = "link text";
+ private const string PartialLinkTextMechanism = "partial link text";
+
///
- /// Provides a mechanism by which to find elements within a document.
+ /// Initializes a new instance of the class.
///
- /// It is possible to create your own locating mechanisms for finding documents.
- /// In order to do this,subclass this class and override the protected methods. However,
- /// it is expected that that all subclasses rely on the basic finding mechanisms provided
- /// through static methods of this class. An example of this can be found in OpenQA.Support.ByIdOrName
+ protected By()
+ {
+ }
+
+ ///
+ /// Initializes a new instance of the class using the specified mechanism and criteria for finding elements.
+ ///
+ /// The mechanism to use in finding elements.
+ /// The criteria to use in finding elements.
+ ///
+ /// Customizing nothing else, instances using this constructor will attempt to find elements
+ /// using the method, taking string arguments.
///
- [Serializable]
- public class By
+ protected By(string mechanism, string criteria)
{
- private const string CssSelectorMechanism = "css selector";
- private const string XPathSelectorMechanism = "xpath";
- private const string TagNameMechanism = "tag name";
- private const string LinkTextMechanism = "link text";
- private const string PartialLinkTextMechanism = "partial link text";
-
- ///
- /// Initializes a new instance of the class.
- ///
- protected By()
- {
- }
+ this.Mechanism = mechanism;
+ this.Criteria = criteria;
+ this.FindElementMethod = (ISearchContext context) => ((IFindsElement)context).FindElement(this.Mechanism, this.Criteria);
+ this.FindElementsMethod = (ISearchContext context) => ((IFindsElement)context).FindElements(this.Mechanism, this.Criteria);
+ }
+
+ ///
+ /// Initializes a new instance of the class using the given functions to find elements.
+ ///
+ /// A function that takes an object implementing
+ /// and returns the found .
+ /// A function that takes an object implementing
+ /// and returns a of the foundIWebElements .
+ /// IWebElements />.
+ protected By(Func findElementMethod, Func> findElementsMethod)
+ {
+ this.FindElementMethod = findElementMethod;
+ this.FindElementsMethod = findElementsMethod;
+ }
- ///
- /// Initializes a new instance of the class using the specified mechanism and criteria for finding elements.
- ///
- /// The mechanism to use in finding elements.
- /// The criteria to use in finding elements.
- ///
- /// Customizing nothing else, instances using this constructor will attempt to find elements
- /// using the method, taking string arguments.
- ///
- protected By(string mechanism, string criteria)
+ ///
+ /// Gets the value of the mechanism for this class instance.
+ ///
+ public string Mechanism { get; } = string.Empty;
+
+ ///
+ /// Gets the value of the criteria for this class instance.
+ ///
+ public string Criteria { get; } = string.Empty;
+
+ ///
+ /// Gets or sets the value of the description for this class instance.
+ ///
+ protected string Description { get; set; } = "OpenQA.Selenium.By";
+
+ ///
+ /// Gets or sets the method used to find a single element matching specified criteria, or throws if no element is found.
+ ///
+ protected Func? FindElementMethod { get; set; }
+
+ ///
+ /// Gets or sets the method used to find all elements matching specified criteria.
+ ///
+ protected Func>? FindElementsMethod { get; set; }
+
+ ///
+ /// Determines if two instances are equal.
+ ///
+ /// One instance to compare.
+ /// The other instance to compare.
+ /// if the two instances are equal; otherwise, .
+ public static bool operator ==(By? one, By? two)
+ {
+ // If both are null, or both are same instance, return true.
+ if (ReferenceEquals(one, two))
{
- this.Mechanism = mechanism;
- this.Criteria = criteria;
- this.FindElementMethod = (ISearchContext context) => ((IFindsElement)context).FindElement(this.Mechanism, this.Criteria);
- this.FindElementsMethod = (ISearchContext context) => ((IFindsElement)context).FindElements(this.Mechanism, this.Criteria);
+ return true;
}
- ///
- /// Initializes a new instance of the class using the given functions to find elements.
- ///
- /// A function that takes an object implementing
- /// and returns the found .
- /// A function that takes an object implementing
- /// and returns a of the foundIWebElements .
- /// IWebElements />.
- protected By(Func findElementMethod, Func> findElementsMethod)
+ // If one is null, but not both, return false.
+ if ((one is null) || (two is null))
{
- this.FindElementMethod = findElementMethod;
- this.FindElementsMethod = findElementsMethod;
+ return false;
}
- ///
- /// Gets the value of the mechanism for this class instance.
- ///
- public string Mechanism { get; } = string.Empty;
-
- ///
- /// Gets the value of the criteria for this class instance.
- ///
- public string Criteria { get; } = string.Empty;
-
- ///
- /// Gets or sets the value of the description for this class instance.
- ///
- protected string Description { get; set; } = "OpenQA.Selenium.By";
-
- ///
- /// Gets or sets the method used to find a single element matching specified criteria, or throws if no element is found.
- ///
- protected Func? FindElementMethod { get; set; }
-
- ///
- /// Gets or sets the method used to find all elements matching specified criteria.
- ///
- protected Func>? FindElementsMethod { get; set; }
-
- ///
- /// Determines if two instances are equal.
- ///
- /// One instance to compare.
- /// The other instance to compare.
- /// if the two instances are equal; otherwise, .
- public static bool operator ==(By? one, By? two)
+ return one.Equals(two);
+ }
+
+ ///
+ /// Determines if two instances are unequal.
+ /// s
+ /// One instance to compare.
+ /// The other instance to compare.
+ /// if the two instances are not equal; otherwise, .
+ public static bool operator !=(By? one, By? two)
+ {
+ return !(one == two);
+ }
+
+ ///
+ /// Gets a mechanism to find elements by their ID.
+ ///
+ /// The ID to find.
+ /// A object the driver can use to find the elements.
+ /// If is .
+ public static By Id(string idToFind)
+ {
+ if (idToFind == null)
{
- // If both are null, or both are same instance, return true.
- if (ReferenceEquals(one, two))
- {
- return true;
- }
-
- // If one is null, but not both, return false.
- if ((one is null) || (two is null))
- {
- return false;
- }
-
- return one.Equals(two);
+ throw new ArgumentNullException(nameof(idToFind), "Cannot find elements with a null id attribute.");
}
- ///
- /// Determines if two instances are unequal.
- /// s
- /// One instance to compare.
- /// The other instance to compare.
- /// if the two instances are not equal; otherwise, .
- public static bool operator !=(By? one, By? two)
+ string selector = EscapeCssSelector(idToFind);
+ By by = new By(CssSelectorMechanism, "#" + selector);
+ by.Description = "By.Id: " + idToFind;
+ if (string.IsNullOrEmpty(selector))
{
- return !(one == two);
+ // Finding multiple elements with an empty ID will return
+ // an empty list. However, finding by a CSS selector of '#'
+ // throws an exception, even in the multiple elements case,
+ // which means we need to short-circuit that behavior.
+ by.FindElementsMethod = (ISearchContext context) => new List().AsReadOnly();
}
- ///
- /// Gets a mechanism to find elements by their ID.
- ///
- /// The ID to find.
- /// A object the driver can use to find the elements.
- /// If is .
- public static By Id(string idToFind)
+ return by;
+ }
+
+ ///
+ /// Gets a mechanism to find elements by their link text.
+ ///
+ /// The link text to find.
+ /// A object the driver can use to find the elements.
+ /// If is null.
+ public static By LinkText(string linkTextToFind)
+ {
+ if (linkTextToFind == null)
{
- if (idToFind == null)
- {
- throw new ArgumentNullException(nameof(idToFind), "Cannot find elements with a null id attribute.");
- }
-
- string selector = EscapeCssSelector(idToFind);
- By by = new By(CssSelectorMechanism, "#" + selector);
- by.Description = "By.Id: " + idToFind;
- if (string.IsNullOrEmpty(selector))
- {
- // Finding multiple elements with an empty ID will return
- // an empty list. However, finding by a CSS selector of '#'
- // throws an exception, even in the multiple elements case,
- // which means we need to short-circuit that behavior.
- by.FindElementsMethod = (ISearchContext context) => new List().AsReadOnly();
- }
-
- return by;
+ throw new ArgumentNullException(nameof(linkTextToFind), "Cannot find elements when link text is null.");
}
- ///
- /// Gets a mechanism to find elements by their link text.
- ///
- /// The link text to find.
- /// A object the driver can use to find the elements.
- /// If is null.
- public static By LinkText(string linkTextToFind)
+ return new By(LinkTextMechanism, linkTextToFind)
{
- if (linkTextToFind == null)
- {
- throw new ArgumentNullException(nameof(linkTextToFind), "Cannot find elements when link text is null.");
- }
-
- return new By(LinkTextMechanism, linkTextToFind)
- {
- Description = "By.LinkText: " + linkTextToFind
- };
- }
+ Description = "By.LinkText: " + linkTextToFind
+ };
+ }
- ///
- /// Gets a mechanism to find elements by their name.
- ///
- /// The name to find.
- /// A object the driver can use to find the elements.
- /// If is null.
- public static By Name(string nameToFind)
+ ///
+ /// Gets a mechanism to find elements by their name.
+ ///
+ /// The name to find.
+ /// A object the driver can use to find the elements.
+ /// If is null.
+ public static By Name(string nameToFind)
+ {
+ if (nameToFind == null)
{
- if (nameToFind == null)
- {
- throw new ArgumentNullException(nameof(nameToFind), "Cannot find elements when name text is null.");
- }
-
- return new By(CssSelectorMechanism, $"*[name =\"{EscapeCssSelector(nameToFind)}\"]")
- {
- Description = "By.Name: " + nameToFind
- };
+ throw new ArgumentNullException(nameof(nameToFind), "Cannot find elements when name text is null.");
}
- ///
- /// Gets a mechanism to find elements by an XPath query.
- /// When searching within a WebElement using xpath be aware that WebDriver follows standard conventions:
- /// a search prefixed with "//" will search the entire document, not just the children of this current node.
- /// Use ".//" to limit your search to the children of this WebElement.
- ///
- /// The XPath query to use.
- /// A object the driver can use to find the elements.
- /// If is null.
- public static By XPath(string xpathToFind)
+ return new By(CssSelectorMechanism, $"*[name =\"{EscapeCssSelector(nameToFind)}\"]")
{
- if (xpathToFind == null)
- {
- throw new ArgumentNullException(nameof(xpathToFind), "Cannot find elements when the XPath expression is null.");
- }
-
- return new By(XPathSelectorMechanism, xpathToFind)
- {
- Description = "By.XPath: " + xpathToFind
- };
- }
+ Description = "By.Name: " + nameToFind
+ };
+ }
- ///
- /// Gets a mechanism to find elements by their CSS class.
- ///
- /// The CSS class to find.
- /// A object the driver can use to find the elements.
- /// If an element has many classes then this will match against each of them.
- /// For example if the value is "one two onone", then the following values for the
- /// className parameter will match: "one" and "two".
- /// If is null.
- public static By ClassName(string classNameToFind)
+ ///
+ /// Gets a mechanism to find elements by an XPath query.
+ /// When searching within a WebElement using xpath be aware that WebDriver follows standard conventions:
+ /// a search prefixed with "//" will search the entire document, not just the children of this current node.
+ /// Use ".//" to limit your search to the children of this WebElement.
+ ///
+ /// The XPath query to use.
+ /// A object the driver can use to find the elements.
+ /// If is null.
+ public static By XPath(string xpathToFind)
+ {
+ if (xpathToFind == null)
{
- if (classNameToFind == null)
- {
- throw new ArgumentNullException(nameof(classNameToFind), "Cannot find elements when the class name expression is null.");
- }
-
- string selector = "." + EscapeCssSelector(classNameToFind);
- if (selector.Contains(" "))
- {
- // Finding elements by class name with whitespace is not allowed.
- // However, converting the single class name to a valid CSS selector
- // by prepending a '.' may result in a still-valid, but incorrect
- // selector. Thus, we short-circuit that behavior here.
- throw new InvalidSelectorException("Compound class names not allowed. Cannot have whitespace in class name. Use CSS selectors instead.");
- }
-
- return new By(CssSelectorMechanism, selector)
- {
- Description = "By.ClassName[Contains]: " + classNameToFind
- };
+ throw new ArgumentNullException(nameof(xpathToFind), "Cannot find elements when the XPath expression is null.");
}
- ///
- /// Gets a mechanism to find elements by a partial match on their link text.
- ///
- /// The partial link text to find.
- /// A object the driver can use to find the elements.
- /// If is null.
- public static By PartialLinkText(string partialLinkTextToFind)
+ return new By(XPathSelectorMechanism, xpathToFind)
{
- if (partialLinkTextToFind == null)
- {
- throw new ArgumentNullException(nameof(partialLinkTextToFind), "Cannot find elements when partial link text is null.");
- }
-
- return new By(PartialLinkTextMechanism, partialLinkTextToFind)
- {
- Description = "By.PartialLinkText: " + partialLinkTextToFind
- };
- }
+ Description = "By.XPath: " + xpathToFind
+ };
+ }
- ///
- /// Gets a mechanism to find elements by their tag name.
- ///
- /// The tag name to find.
- /// A object the driver can use to find the elements.
- /// If is null.
- public static By TagName(string tagNameToFind)
+ ///
+ /// Gets a mechanism to find elements by their CSS class.
+ ///
+ /// The CSS class to find.
+ /// A object the driver can use to find the elements.
+ /// If an element has many classes then this will match against each of them.
+ /// For example if the value is "one two onone", then the following values for the
+ /// className parameter will match: "one" and "two".
+ /// If is null.
+ public static By ClassName(string classNameToFind)
+ {
+ if (classNameToFind == null)
{
- if (tagNameToFind == null)
- {
- throw new ArgumentNullException(nameof(tagNameToFind), "Cannot find elements when name tag name is null.");
- }
-
- return new By(TagNameMechanism, tagNameToFind)
- {
- Description = "By.TagName: " + tagNameToFind
- };
+ throw new ArgumentNullException(nameof(classNameToFind), "Cannot find elements when the class name expression is null.");
}
- ///
- /// Gets a mechanism to find elements by their cascading style sheet (CSS) selector.
- ///
- /// The CSS selector to find.
- /// A object the driver can use to find the elements.
- /// If is null.
- public static By CssSelector(string cssSelectorToFind)
+ string selector = "." + EscapeCssSelector(classNameToFind);
+ if (selector.Contains(" "))
{
- if (cssSelectorToFind == null)
- {
- throw new ArgumentNullException(nameof(cssSelectorToFind), "Cannot find elements when name CSS selector is null.");
- }
-
- return new By(CssSelectorMechanism, cssSelectorToFind)
- {
- Description = "By.CssSelector: " + cssSelectorToFind
- };
+ // Finding elements by class name with whitespace is not allowed.
+ // However, converting the single class name to a valid CSS selector
+ // by prepending a '.' may result in a still-valid, but incorrect
+ // selector. Thus, we short-circuit that behavior here.
+ throw new InvalidSelectorException("Compound class names not allowed. Cannot have whitespace in class name. Use CSS selectors instead.");
}
- ///
- /// Finds the first element matching the criteria.
- ///
- /// An object to use to search for the elements.
- /// The first matching on the current context.
- /// If no element matches the criteria.
- public virtual IWebElement FindElement(ISearchContext context)
+ return new By(CssSelectorMechanism, selector)
{
- if (this.FindElementMethod is not { } findElementMethod)
- {
- throw new InvalidOperationException("FindElement method not set. Override the By.FindElement method, set the By.FindElementMethod property, or use a constructor that sets a query mechanism.");
- }
+ Description = "By.ClassName[Contains]: " + classNameToFind
+ };
+ }
- return findElementMethod(context);
+ ///
+ /// Gets a mechanism to find elements by a partial match on their link text.
+ ///
+ /// The partial link text to find.
+ /// A object the driver can use to find the elements.
+ /// If is null.
+ public static By PartialLinkText(string partialLinkTextToFind)
+ {
+ if (partialLinkTextToFind == null)
+ {
+ throw new ArgumentNullException(nameof(partialLinkTextToFind), "Cannot find elements when partial link text is null.");
}
- ///
- /// Finds all elements matching the criteria.
- ///
- /// An object to use to search for the elements.
- /// A of all WebElements
- /// matching the current criteria, or an empty list if nothing matches.
- public virtual ReadOnlyCollection FindElements(ISearchContext context)
+ return new By(PartialLinkTextMechanism, partialLinkTextToFind)
{
- if (this.FindElementsMethod is not { } findElementsMethod)
- {
- throw new InvalidOperationException("FindElements method not set. Override the By.FindElements method, set the By.FindElementsMethod property, or use a constructor that sets a query mechanism.");
- }
+ Description = "By.PartialLinkText: " + partialLinkTextToFind
+ };
+ }
- return findElementsMethod(context);
+ ///
+ /// Gets a mechanism to find elements by their tag name.
+ ///
+ /// The tag name to find.
+ /// A object the driver can use to find the elements.
+ /// If is null.
+ public static By TagName(string tagNameToFind)
+ {
+ if (tagNameToFind == null)
+ {
+ throw new ArgumentNullException(nameof(tagNameToFind), "Cannot find elements when name tag name is null.");
}
- ///
- /// Gets a string representation of the finder.
- ///
- /// The string displaying the finder content.
- public override string ToString()
+ return new By(TagNameMechanism, tagNameToFind)
+ {
+ Description = "By.TagName: " + tagNameToFind
+ };
+ }
+
+ ///
+ /// Gets a mechanism to find elements by their cascading style sheet (CSS) selector.
+ ///
+ /// The CSS selector to find.
+ /// A object the driver can use to find the elements.
+ /// If is null.
+ public static By CssSelector(string cssSelectorToFind)
+ {
+ if (cssSelectorToFind == null)
{
- return this.Description;
+ throw new ArgumentNullException(nameof(cssSelectorToFind), "Cannot find elements when name CSS selector is null.");
}
- ///
- /// Determines whether the specified Object is equal
- /// to the current Object .
- ///
- /// The Object to compare with the
- /// current Object .
- /// if the specified Object
- /// is equal to the current Object ; otherwise,
- /// .
- public override bool Equals(object? obj)
+ return new By(CssSelectorMechanism, cssSelectorToFind)
{
- var other = obj as By;
+ Description = "By.CssSelector: " + cssSelectorToFind
+ };
+ }
- // TODO(dawagner): This isn't ideal
- return other != null && this.Description.Equals(other.Description);
+ ///
+ /// Finds the first element matching the criteria.
+ ///
+ /// An object to use to search for the elements.
+ /// The first matching on the current context.
+ /// If no element matches the criteria.
+ public virtual IWebElement FindElement(ISearchContext context)
+ {
+ if (this.FindElementMethod is not { } findElementMethod)
+ {
+ throw new InvalidOperationException("FindElement method not set. Override the By.FindElement method, set the By.FindElementMethod property, or use a constructor that sets a query mechanism.");
}
- ///
- /// Serves as a hash function for a particular type.
- ///
- /// A hash code for the current Object .
- public override int GetHashCode()
+ return findElementMethod(context);
+ }
+
+ ///
+ /// Finds all elements matching the criteria.
+ ///
+ /// An object to use to search for the elements.
+ /// A of all WebElements
+ /// matching the current criteria, or an empty list if nothing matches.
+ public virtual ReadOnlyCollection FindElements(ISearchContext context)
+ {
+ if (this.FindElementsMethod is not { } findElementsMethod)
{
- return this.Description.GetHashCode();
+ throw new InvalidOperationException("FindElements method not set. Override the By.FindElements method, set the By.FindElementsMethod property, or use a constructor that sets a query mechanism.");
}
- ///
- /// Escapes invalid characters in a CSS selector.
- ///
- /// The selector to escape.
- /// The selector with invalid characters escaped.
- internal static string EscapeCssSelector(string selector)
- {
- string escaped = InvalidCharsRegex.Replace(selector, @"\$1");
- if (selector.Length > 0 && char.IsDigit(selector[0]))
- {
- int digitCode = 30 + int.Parse(selector.Substring(0, 1), CultureInfo.InvariantCulture);
+ return findElementsMethod(context);
+ }
+
+ ///
+ /// Gets a string representation of the finder.
+ ///
+ /// The string displaying the finder content.
+ public override string ToString()
+ {
+ return this.Description;
+ }
- escaped = $"\\{digitCode.ToString(CultureInfo.InvariantCulture)} {selector.Substring(1)}";
- }
+ ///
+ /// Determines whether the specified Object is equal
+ /// to the current Object .
+ ///
+ /// The Object to compare with the
+ /// current Object .
+ /// if the specified Object
+ /// is equal to the current Object ; otherwise,
+ /// .
+ public override bool Equals(object? obj)
+ {
+ var other = obj as By;
- return escaped;
+ // TODO(dawagner): This isn't ideal
+ return other != null && this.Description.Equals(other.Description);
+ }
+
+ ///
+ /// Serves as a hash function for a particular type.
+ ///
+ /// A hash code for the current Object .
+ public override int GetHashCode()
+ {
+ return this.Description.GetHashCode();
+ }
+
+ ///
+ /// Escapes invalid characters in a CSS selector.
+ ///
+ /// The selector to escape.
+ /// The selector with invalid characters escaped.
+ internal static string EscapeCssSelector(string selector)
+ {
+ string escaped = InvalidCharsRegex.Replace(selector, @"\$1");
+ if (selector.Length > 0 && char.IsDigit(selector[0]))
+ {
+ int digitCode = 30 + int.Parse(selector.Substring(0, 1), CultureInfo.InvariantCulture);
+
+ escaped = $"\\{digitCode.ToString(CultureInfo.InvariantCulture)} {selector.Substring(1)}";
}
- private static readonly Regex InvalidCharsRegex = new Regex(@"([ '""\\#.:;,!?+<>=~*^$|%&@`{}\-/\[\]\(\)])", RegexOptions.Compiled);
+ return escaped;
}
+
+ private static readonly Regex InvalidCharsRegex = new Regex(@"([ '""\\#.:;,!?+<>=~*^$|%&@`{}\-/\[\]\(\)])", RegexOptions.Compiled);
}
diff --git a/dotnet/src/webdriver/CapabilityType.cs b/dotnet/src/webdriver/CapabilityType.cs
index 4ee0f04884cbb..1d35063c63f69 100644
--- a/dotnet/src/webdriver/CapabilityType.cs
+++ b/dotnet/src/webdriver/CapabilityType.cs
@@ -20,189 +20,188 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
-namespace OpenQA.Selenium
+namespace OpenQA.Selenium;
+
+///
+/// Provides types of capabilities for the DesiredCapabilities object.
+///
+public static class CapabilityType
{
///
- /// Provides types of capabilities for the DesiredCapabilities object.
+ /// Capability name used for the browser name.
///
- public static class CapabilityType
- {
- ///
- /// Capability name used for the browser name.
- ///
- public static readonly string BrowserName = "browserName";
-
- ///
- /// Capability name used for the browser version.
- ///
- public static readonly string BrowserVersion = "browserVersion";
-
- ///
- /// Capability name used for the platform name.
- ///
- public static readonly string PlatformName = "platformName";
-
- ///
- /// Capability name used for the browser platform.
- ///
- public static readonly string Platform = "platform";
-
- ///
- /// Capability name used for the browser version.
- ///
- public static readonly string Version = "version";
-
- ///
- /// Capability name used to indicate whether JavaScript is enabled for the browser.
- ///
- public static readonly string IsJavaScriptEnabled = "javascriptEnabled";
-
- ///
- /// Capability name used to indicate whether the browser can take screenshots.
- ///
- public static readonly string TakesScreenshot = "takesScreenshot";
-
- ///
- /// Capability name used to indicate whether the browser can handle alerts.
- ///
- public static readonly string HandlesAlerts = "handlesAlerts";
-
- ///
- /// Capability name used to indicate whether the browser can find elements via CSS selectors.
- ///
- public static readonly string SupportsFindingByCss = "cssSelectorsEnabled";
-
- ///
- /// Capability name used for the browser proxy.
- ///
- public static readonly string Proxy = "proxy";
-
- ///
- /// Capability name used to indicate whether the browser supports rotation.
- ///
- public static readonly string Rotatable = "rotatable";
-
- ///
- /// Capability name used to indicate whether the browser accepts SSL certificates.
- ///
- public static readonly string AcceptSslCertificates = "acceptSslCerts";
-
- ///
- /// Capability name used to indicate whether the browser accepts SSL certificates on W3C Endpoints
- ///
- public static readonly string AcceptInsecureCertificates = "acceptInsecureCerts";
-
- ///
- /// Capability name used to indicate whether the browser uses native events.
- ///
- public static readonly string HasNativeEvents = "nativeEvents";
-
- ///
- /// Capability name used to indicate how the browser handles unexpected alerts.
- ///
- public static readonly string UnexpectedAlertBehavior = "unexpectedAlertBehaviour";
-
- ///
- /// Capability name used to indicate how the browser handles unhandled user prompts.
- ///
- public static readonly string UnhandledPromptBehavior = "unhandledPromptBehavior";
-
- ///
- /// Capability name used to indicate the page load strategy for the browser.
- ///
- public static readonly string PageLoadStrategy = "pageLoadStrategy";
-
- ///
- /// Capability name used to indicate the logging preferences for the session.
- ///
- public static readonly string LoggingPreferences = "loggingPrefs";
-
- ///
- /// Capability name used to disable the check for overlapping elements.
- ///
- public static readonly string DisableOverlappedElementCheck = "overlappingCheckDisabled";
-
- ///
- /// Capability name used to enable the profiling log for the session.
- ///
- public static readonly string EnableProfiling = "webdriver.logging.profiler.enabled";
-
- ///
- /// Capability name used to indicate whether the driver supports geolocation context.
- ///
- public static readonly string SupportsLocationContext = "locationContextEnabled";
-
- ///
- /// Capability name used to indicate whether the driver supports application cache.
- ///
- public static readonly string SupportsApplicationCache = "applicationCacheEnabled";
-
- ///
- /// Capability name used to indicate whether the driver supports web storage.
- ///
- public static readonly string SupportsWebStorage = "webStorageEnabled";
-
- ///
- /// Capability name used to indicate whether the driver supports setting the browser window's size and position.
- ///
- public static readonly string SetWindowRect = "setWindowRect";
-
- ///
- /// Capability name used to get or set timeout values when creating a session.
- ///
- public static readonly string Timeouts = "timeouts";
-
- ///
- /// Capability name used to get or set whether <input type='file'/> elements must be visible to upload files.
- ///
- public static readonly string UseStrictFileInteractability = "strictFileInteractability";
-
- ///
- /// Capability name used to get a value indicating whether to request URL of a WebSocket
- /// connection for bidirectional communication with a driver.
- ///
- public static readonly string WebSocketUrl = "webSocketUrl";
-
- ///
- /// Capability name used to get a value indicating whether files may be downloaded from remote end.
- ///
- public static readonly string EnableDownloads = "se:downloadsEnabled";
-
- private static readonly HashSet KnownSpecCompliantCapabilityNames = new HashSet()
- {
- BrowserName,
- BrowserVersion,
- PlatformName,
- AcceptInsecureCertificates,
- PageLoadStrategy,
- Proxy,
- SetWindowRect,
- Timeouts,
- UnhandledPromptBehavior,
- UseStrictFileInteractability,
- WebSocketUrl
- };
-
- ///
- /// Gets a value indicating whether a given capability name is compliant with the
- /// W3C WebDriver Specification.
- ///
- /// The name of the capability to check for compliance.
- /// if the capability name is valid according to the rules
- /// of the specification; otherwise, .
- public static bool IsSpecCompliantCapabilityName([NotNullWhen(true)] string? capabilityName)
- {
- if (capabilityName is null)
- {
- return false;
- }
+ public static readonly string BrowserName = "browserName";
+
+ ///
+ /// Capability name used for the browser version.
+ ///
+ public static readonly string BrowserVersion = "browserVersion";
+
+ ///
+ /// Capability name used for the platform name.
+ ///
+ public static readonly string PlatformName = "platformName";
+
+ ///
+ /// Capability name used for the browser platform.
+ ///
+ public static readonly string Platform = "platform";
+
+ ///
+ /// Capability name used for the browser version.
+ ///
+ public static readonly string Version = "version";
+
+ ///
+ /// Capability name used to indicate whether JavaScript is enabled for the browser.
+ ///
+ public static readonly string IsJavaScriptEnabled = "javascriptEnabled";
+
+ ///
+ /// Capability name used to indicate whether the browser can take screenshots.
+ ///
+ public static readonly string TakesScreenshot = "takesScreenshot";
+
+ ///
+ /// Capability name used to indicate whether the browser can handle alerts.
+ ///
+ public static readonly string HandlesAlerts = "handlesAlerts";
+
+ ///
+ /// Capability name used to indicate whether the browser can find elements via CSS selectors.
+ ///
+ public static readonly string SupportsFindingByCss = "cssSelectorsEnabled";
+
+ ///
+ /// Capability name used for the browser proxy.
+ ///
+ public static readonly string Proxy = "proxy";
+
+ ///
+ /// Capability name used to indicate whether the browser supports rotation.
+ ///
+ public static readonly string Rotatable = "rotatable";
+
+ ///
+ /// Capability name used to indicate whether the browser accepts SSL certificates.
+ ///
+ public static readonly string AcceptSslCertificates = "acceptSslCerts";
+
+ ///
+ /// Capability name used to indicate whether the browser accepts SSL certificates on W3C Endpoints
+ ///
+ public static readonly string AcceptInsecureCertificates = "acceptInsecureCerts";
+
+ ///
+ /// Capability name used to indicate whether the browser uses native events.
+ ///
+ public static readonly string HasNativeEvents = "nativeEvents";
+
+ ///
+ /// Capability name used to indicate how the browser handles unexpected alerts.
+ ///
+ public static readonly string UnexpectedAlertBehavior = "unexpectedAlertBehaviour";
+
+ ///
+ /// Capability name used to indicate how the browser handles unhandled user prompts.
+ ///
+ public static readonly string UnhandledPromptBehavior = "unhandledPromptBehavior";
+
+ ///
+ /// Capability name used to indicate the page load strategy for the browser.
+ ///
+ public static readonly string PageLoadStrategy = "pageLoadStrategy";
+
+ ///
+ /// Capability name used to indicate the logging preferences for the session.
+ ///
+ public static readonly string LoggingPreferences = "loggingPrefs";
+
+ ///
+ /// Capability name used to disable the check for overlapping elements.
+ ///
+ public static readonly string DisableOverlappedElementCheck = "overlappingCheckDisabled";
+
+ ///
+ /// Capability name used to enable the profiling log for the session.
+ ///
+ public static readonly string EnableProfiling = "webdriver.logging.profiler.enabled";
+
+ ///
+ /// Capability name used to indicate whether the driver supports geolocation context.
+ ///
+ public static readonly string SupportsLocationContext = "locationContextEnabled";
+
+ ///
+ /// Capability name used to indicate whether the driver supports application cache.
+ ///
+ public static readonly string SupportsApplicationCache = "applicationCacheEnabled";
- if (KnownSpecCompliantCapabilityNames.Contains(capabilityName) || capabilityName.Contains(":"))
- {
- return true;
- }
+ ///
+ /// Capability name used to indicate whether the driver supports web storage.
+ ///
+ public static readonly string SupportsWebStorage = "webStorageEnabled";
+ ///
+ /// Capability name used to indicate whether the driver supports setting the browser window's size and position.
+ ///
+ public static readonly string SetWindowRect = "setWindowRect";
+
+ ///
+ /// Capability name used to get or set timeout values when creating a session.
+ ///
+ public static readonly string Timeouts = "timeouts";
+
+ ///
+ /// Capability name used to get or set whether <input type='file'/> elements must be visible to upload files.
+ ///
+ public static readonly string UseStrictFileInteractability = "strictFileInteractability";
+
+ ///
+ /// Capability name used to get a value indicating whether to request URL of a WebSocket
+ /// connection for bidirectional communication with a driver.
+ ///
+ public static readonly string WebSocketUrl = "webSocketUrl";
+
+ ///
+ /// Capability name used to get a value indicating whether files may be downloaded from remote end.
+ ///
+ public static readonly string EnableDownloads = "se:downloadsEnabled";
+
+ private static readonly HashSet KnownSpecCompliantCapabilityNames = new HashSet()
+ {
+ BrowserName,
+ BrowserVersion,
+ PlatformName,
+ AcceptInsecureCertificates,
+ PageLoadStrategy,
+ Proxy,
+ SetWindowRect,
+ Timeouts,
+ UnhandledPromptBehavior,
+ UseStrictFileInteractability,
+ WebSocketUrl
+ };
+
+ ///
+ /// Gets a value indicating whether a given capability name is compliant with the
+ /// W3C WebDriver Specification.
+ ///
+ /// The name of the capability to check for compliance.
+ /// if the capability name is valid according to the rules
+ /// of the specification; otherwise, .
+ public static bool IsSpecCompliantCapabilityName([NotNullWhen(true)] string? capabilityName)
+ {
+ if (capabilityName is null)
+ {
return false;
}
+
+ if (KnownSpecCompliantCapabilityNames.Contains(capabilityName) || capabilityName.Contains(":"))
+ {
+ return true;
+ }
+
+ return false;
}
}
diff --git a/dotnet/src/webdriver/Chrome/ChromeDriver.cs b/dotnet/src/webdriver/Chrome/ChromeDriver.cs
index b39f7cf72453f..419fb8bb70cc3 100644
--- a/dotnet/src/webdriver/Chrome/ChromeDriver.cs
+++ b/dotnet/src/webdriver/Chrome/ChromeDriver.cs
@@ -23,172 +23,171 @@
using System.Collections.Generic;
using System.Collections.ObjectModel;
-namespace OpenQA.Selenium.Chrome
+namespace OpenQA.Selenium.Chrome;
+
+///
+/// Provides a mechanism to write tests against Chrome
+///
+///
+///
+/// [TestFixture]
+/// public class Testing
+/// {
+/// private IWebDriver driver;
+///
+/// [SetUp]
+/// public void SetUp()
+/// {
+/// driver = new ChromeDriver();
+/// }
+///
+/// [Test]
+/// public void TestGoogle()
+/// {
+/// driver.Navigate().GoToUrl("http://www.google.co.uk/");
+/// /*
+/// * Rest of the test
+/// */
+/// }
+///
+/// [TearDown]
+/// public void TearDown()
+/// {
+/// driver.Quit();
+/// }
+/// }
+///
+///
+public class ChromeDriver : ChromiumDriver
{
+ private static readonly Dictionary chromeCustomCommands = new Dictionary()
+ {
+ { ExecuteCdp, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/goog/cdp/execute") },
+ { GetCastSinksCommand, new HttpCommandInfo(HttpCommandInfo.GetCommand, "/session/{sessionId}/goog/cast/get_sinks") },
+ { SelectCastSinkCommand, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/goog/cast/set_sink_to_use") },
+ { StartCastTabMirroringCommand, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/goog/cast/start_tab_mirroring") },
+ { StartCastDesktopMirroringCommand, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/goog/cast/start_desktop_mirroring") },
+ { GetCastIssueMessageCommand, new HttpCommandInfo(HttpCommandInfo.GetCommand, "/session/{sessionId}/goog/cast/get_issue_message") },
+ { StopCastingCommand, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/goog/cast/stop_casting") }
+ };
+
///
- /// Provides a mechanism to write tests against Chrome
+ /// Initializes a new instance of the class.
///
- ///
- ///
- /// [TestFixture]
- /// public class Testing
- /// {
- /// private IWebDriver driver;
- ///
- /// [SetUp]
- /// public void SetUp()
- /// {
- /// driver = new ChromeDriver();
- /// }
- ///
- /// [Test]
- /// public void TestGoogle()
- /// {
- /// driver.Navigate().GoToUrl("http://www.google.co.uk/");
- /// /*
- /// * Rest of the test
- /// */
- /// }
- ///
- /// [TearDown]
- /// public void TearDown()
- /// {
- /// driver.Quit();
- /// }
- /// }
- ///
- ///
- public class ChromeDriver : ChromiumDriver
+ public ChromeDriver()
+ : this(new ChromeOptions())
{
- private static readonly Dictionary chromeCustomCommands = new Dictionary()
- {
- { ExecuteCdp, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/goog/cdp/execute") },
- { GetCastSinksCommand, new HttpCommandInfo(HttpCommandInfo.GetCommand, "/session/{sessionId}/goog/cast/get_sinks") },
- { SelectCastSinkCommand, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/goog/cast/set_sink_to_use") },
- { StartCastTabMirroringCommand, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/goog/cast/start_tab_mirroring") },
- { StartCastDesktopMirroringCommand, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/goog/cast/start_desktop_mirroring") },
- { GetCastIssueMessageCommand, new HttpCommandInfo(HttpCommandInfo.GetCommand, "/session/{sessionId}/goog/cast/get_issue_message") },
- { StopCastingCommand, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/goog/cast/stop_casting") }
- };
-
- ///
- /// Initializes a new instance of the class.
- ///
- public ChromeDriver()
- : this(new ChromeOptions())
- {
- }
+ }
- ///
- /// Initializes a new instance of the class using the specified options.
- ///
- /// The to be used with the Chrome driver.
- /// If is .
- public ChromeDriver(ChromeOptions options)
- : this(ChromeDriverService.CreateDefaultService(), options, RemoteWebDriver.DefaultCommandTimeout)
- {
- }
+ ///
+ /// Initializes a new instance of the class using the specified options.
+ ///
+ /// The to be used with the Chrome driver.
+ /// If is .
+ public ChromeDriver(ChromeOptions options)
+ : this(ChromeDriverService.CreateDefaultService(), options, RemoteWebDriver.DefaultCommandTimeout)
+ {
+ }
- ///
- /// Initializes a new instance of the class using the specified driver service.
- ///
- /// The used to initialize the driver.
- /// If is .
- public ChromeDriver(ChromeDriverService service)
- : this(service, new ChromeOptions())
- {
- }
+ ///
+ /// Initializes a new instance of the class using the specified driver service.
+ ///
+ /// The used to initialize the driver.
+ /// If is .
+ public ChromeDriver(ChromeDriverService service)
+ : this(service, new ChromeOptions())
+ {
+ }
- ///
- /// Initializes a new instance of the class using the specified path
- /// to the directory containing ChromeDriver.exe.
- ///
- /// The full path to the directory containing ChromeDriver.exe.
- public ChromeDriver(string chromeDriverDirectory)
- : this(chromeDriverDirectory, new ChromeOptions())
- {
- }
+ ///
+ /// Initializes a new instance of the class using the specified path
+ /// to the directory containing ChromeDriver.exe.
+ ///
+ /// The full path to the directory containing ChromeDriver.exe.
+ public ChromeDriver(string chromeDriverDirectory)
+ : this(chromeDriverDirectory, new ChromeOptions())
+ {
+ }
- ///
- /// Initializes a new instance of the class using the specified path
- /// to the directory containing ChromeDriver.exe and options.
- ///
- /// The full path to the directory containing ChromeDriver.exe.
- /// The to be used with the Chrome driver.
- /// If is .
- public ChromeDriver(string chromeDriverDirectory, ChromeOptions options)
- : this(chromeDriverDirectory, options, RemoteWebDriver.DefaultCommandTimeout)
- {
- }
+ ///
+ /// Initializes a new instance of the class using the specified path
+ /// to the directory containing ChromeDriver.exe and options.
+ ///
+ /// The full path to the directory containing ChromeDriver.exe.
+ /// The to be used with the Chrome driver.
+ /// If is .
+ public ChromeDriver(string chromeDriverDirectory, ChromeOptions options)
+ : this(chromeDriverDirectory, options, RemoteWebDriver.DefaultCommandTimeout)
+ {
+ }
- ///
- /// Initializes a new instance of the class using the specified path
- /// to the directory containing ChromeDriver.exe, options, and command timeout.
- ///
- /// The full path to the directory containing ChromeDriver.exe.
- /// The to be used with the Chrome driver.
- /// The maximum amount of time to wait for each command.
- /// If is .
- public ChromeDriver(string chromeDriverDirectory, ChromeOptions options, TimeSpan commandTimeout)
- : this(ChromeDriverService.CreateDefaultService(chromeDriverDirectory), options, commandTimeout)
- {
- }
+ ///
+ /// Initializes a new instance of the class using the specified path
+ /// to the directory containing ChromeDriver.exe, options, and command timeout.
+ ///
+ /// The full path to the directory containing ChromeDriver.exe.
+ /// The to be used with the Chrome driver.
+ /// The maximum amount of time to wait for each command.
+ /// If is .
+ public ChromeDriver(string chromeDriverDirectory, ChromeOptions options, TimeSpan commandTimeout)
+ : this(ChromeDriverService.CreateDefaultService(chromeDriverDirectory), options, commandTimeout)
+ {
+ }
- ///
- /// Initializes a new instance of the class using the specified
- /// and options.
- ///
- /// The to use.
- /// The used to initialize the driver.
- /// If or are .
- public ChromeDriver(ChromeDriverService service, ChromeOptions options)
- : this(service, options, RemoteWebDriver.DefaultCommandTimeout)
- {
- }
+ ///
+ /// Initializes a new instance of the class using the specified
+ /// and options.
+ ///
+ /// The to use.
+ /// The used to initialize the driver.
+ /// If or are .
+ public ChromeDriver(ChromeDriverService service, ChromeOptions options)
+ : this(service, options, RemoteWebDriver.DefaultCommandTimeout)
+ {
+ }
- ///
- /// Initializes a new instance of the class using the specified .
- ///
- /// The to use.
- /// The to be used with the Chrome driver.
- /// The maximum amount of time to wait for each command.
- /// If or are .
- public ChromeDriver(ChromeDriverService service, ChromeOptions options, TimeSpan commandTimeout)
- : base(service, options, commandTimeout)
- {
- this.AddCustomChromeCommands();
- }
+ ///
+ /// Initializes a new instance of the class using the specified .
+ ///
+ /// The to use.
+ /// The to be used with the Chrome driver.
+ /// The maximum amount of time to wait for each command.
+ /// If or are .
+ public ChromeDriver(ChromeDriverService service, ChromeOptions options, TimeSpan commandTimeout)
+ : base(service, options, commandTimeout)
+ {
+ this.AddCustomChromeCommands();
+ }
- ///
- /// Gets a read-only dictionary of the custom WebDriver commands defined for ChromeDriver.
- /// The keys of the dictionary are the names assigned to the command; the values are the
- /// objects describing the command behavior.
- ///
- public static IReadOnlyDictionary CustomCommandDefinitions
+ ///
+ /// Gets a read-only dictionary of the custom WebDriver commands defined for ChromeDriver.
+ /// The keys of the dictionary are the names assigned to the command; the values are the
+ /// objects describing the command behavior.
+ ///
+ public static IReadOnlyDictionary CustomCommandDefinitions
+ {
+ get
{
- get
+ Dictionary customCommands = new Dictionary();
+ foreach (KeyValuePair entry in ChromiumCustomCommands)
{
- Dictionary customCommands = new Dictionary();
- foreach (KeyValuePair entry in ChromiumCustomCommands)
- {
- customCommands[entry.Key] = entry.Value;
- }
-
- foreach (KeyValuePair entry in chromeCustomCommands)
- {
- customCommands[entry.Key] = entry.Value;
- }
+ customCommands[entry.Key] = entry.Value;
+ }
- return new ReadOnlyDictionary(customCommands);
+ foreach (KeyValuePair entry in chromeCustomCommands)
+ {
+ customCommands[entry.Key] = entry.Value;
}
+
+ return new ReadOnlyDictionary(customCommands);
}
+ }
- private void AddCustomChromeCommands()
+ private void AddCustomChromeCommands()
+ {
+ foreach (KeyValuePair entry in CustomCommandDefinitions)
{
- foreach (KeyValuePair entry in CustomCommandDefinitions)
- {
- this.RegisterInternalDriverCommand(entry.Key, entry.Value);
- }
+ this.RegisterInternalDriverCommand(entry.Key, entry.Value);
}
}
}
diff --git a/dotnet/src/webdriver/Chrome/ChromeDriverService.cs b/dotnet/src/webdriver/Chrome/ChromeDriverService.cs
index a294c72fd3097..4b701ceed1598 100644
--- a/dotnet/src/webdriver/Chrome/ChromeDriverService.cs
+++ b/dotnet/src/webdriver/Chrome/ChromeDriverService.cs
@@ -21,74 +21,73 @@
using OpenQA.Selenium.Internal;
using System.IO;
-namespace OpenQA.Selenium.Chrome
+namespace OpenQA.Selenium.Chrome;
+
+///
+/// Exposes the service provided by the native ChromeDriver executable.
+///
+public sealed class ChromeDriverService : ChromiumDriverService
{
+ private const string DefaultChromeDriverServiceExecutableName = "chromedriver";
+
///
- /// Exposes the service provided by the native ChromeDriver executable.
+ /// Initializes a new instance of the class.
///
- public sealed class ChromeDriverService : ChromiumDriverService
+ /// The full path to the ChromeDriver executable.
+ /// The file name of the ChromeDriver executable.
+ /// The port on which the ChromeDriver executable should listen.
+ private ChromeDriverService(string? executablePath, string? executableFileName, int port)
+ : base(executablePath, executableFileName, port)
{
- private const string DefaultChromeDriverServiceExecutableName = "chromedriver";
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The full path to the ChromeDriver executable.
- /// The file name of the ChromeDriver executable.
- /// The port on which the ChromeDriver executable should listen.
- private ChromeDriverService(string? executablePath, string? executableFileName, int port)
- : base(executablePath, executableFileName, port)
- {
- }
+ }
- ///
- protected override DriverOptions GetDefaultDriverOptions()
- {
- return new ChromeOptions();
- }
+ ///
+ protected override DriverOptions GetDefaultDriverOptions()
+ {
+ return new ChromeOptions();
+ }
- ///
- /// Creates a default instance of the ChromeDriverService.
- ///
- /// A ChromeDriverService that implements default settings.
- public static ChromeDriverService CreateDefaultService()
- {
- return new ChromeDriverService(null, null, PortUtilities.FindFreePort());
- }
+ ///
+ /// Creates a default instance of the ChromeDriverService.
+ ///
+ /// A ChromeDriverService that implements default settings.
+ public static ChromeDriverService CreateDefaultService()
+ {
+ return new ChromeDriverService(null, null, PortUtilities.FindFreePort());
+ }
- ///
- /// Creates a default instance of the ChromeDriverService using a specified path to the ChromeDriver executable.
- ///
- /// The path to the executable or the directory containing the ChromeDriver executable.
- /// A ChromeDriverService using a random port.
- public static ChromeDriverService CreateDefaultService(string? driverPath)
+ ///
+ /// Creates a default instance of the ChromeDriverService using a specified path to the ChromeDriver executable.
+ ///
+ /// The path to the executable or the directory containing the ChromeDriver executable.
+ /// A ChromeDriverService using a random port.
+ public static ChromeDriverService CreateDefaultService(string? driverPath)
+ {
+ if (File.Exists(driverPath))
{
- if (File.Exists(driverPath))
- {
- string fileName = Path.GetFileName(driverPath);
- string driverFolder = Path.GetDirectoryName(driverPath)!;
-
- return CreateDefaultService(driverFolder, fileName);
- }
- else
- {
- string fileName = ChromiumDriverServiceFileName(DefaultChromeDriverServiceExecutableName);
- string? driverFolder = driverPath;
+ string fileName = Path.GetFileName(driverPath);
+ string driverFolder = Path.GetDirectoryName(driverPath)!;
- return CreateDefaultService(driverFolder, fileName);
- }
+ return CreateDefaultService(driverFolder, fileName);
}
-
- ///
- /// Creates a default instance of the ChromeDriverService using a specified path to the ChromeDriver executable with the given name.
- ///
- /// The directory containing the ChromeDriver executable.
- /// The name of the ChromeDriver executable file.
- /// A ChromeDriverService using a random port.
- public static ChromeDriverService CreateDefaultService(string? driverPath, string? driverExecutableFileName)
+ else
{
- return new ChromeDriverService(driverPath, driverExecutableFileName, PortUtilities.FindFreePort());
+ string fileName = ChromiumDriverServiceFileName(DefaultChromeDriverServiceExecutableName);
+ string? driverFolder = driverPath;
+
+ return CreateDefaultService(driverFolder, fileName);
}
+ }
+ ///
+ /// Creates a default instance of the ChromeDriverService using a specified path to the ChromeDriver executable with the given name.
+ ///
+ /// The directory containing the ChromeDriver executable.
+ /// The name of the ChromeDriver executable file.
+ /// A ChromeDriverService using a random port.
+ public static ChromeDriverService CreateDefaultService(string? driverPath, string? driverExecutableFileName)
+ {
+ return new ChromeDriverService(driverPath, driverExecutableFileName, PortUtilities.FindFreePort());
}
+
}
diff --git a/dotnet/src/webdriver/Chrome/ChromeOptions.cs b/dotnet/src/webdriver/Chrome/ChromeOptions.cs
index cf47856dc5ac3..85b0c287e8b82 100644
--- a/dotnet/src/webdriver/Chrome/ChromeOptions.cs
+++ b/dotnet/src/webdriver/Chrome/ChromeOptions.cs
@@ -21,75 +21,74 @@
using System;
using System.Globalization;
-namespace OpenQA.Selenium.Chrome
+namespace OpenQA.Selenium.Chrome;
+
+///
+/// Class to manage options specific to
+///
+///
+/// Used with ChromeDriver.exe v17.0.963.0 and higher.
+///
+///
+///
+/// ChromeOptions options = new ChromeOptions();
+/// options.AddExtensions("\path\to\extension.crx");
+/// options.BinaryLocation = "\path\to\chrome";
+///
+///
+/// For use with ChromeDriver:
+///
+///
+/// ChromeDriver driver = new ChromeDriver(options);
+///
+///
+/// For use with RemoteWebDriver:
+///
+///
+/// RemoteWebDriver driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), options.ToCapabilities());
+///
+///
+public class ChromeOptions : ChromiumOptions
{
+ private const string ChromeOptionsCapabilityName = "chromeOptions";
+ private const string BrowserNameValue = "chrome";
+
///
- /// Class to manage options specific to
+ /// Initializes a new instance of the class.
///
- ///
- /// Used with ChromeDriver.exe v17.0.963.0 and higher.
- ///
- ///
- ///
- /// ChromeOptions options = new ChromeOptions();
- /// options.AddExtensions("\path\to\extension.crx");
- /// options.BinaryLocation = "\path\to\chrome";
- ///
- ///
- /// For use with ChromeDriver:
- ///
- ///
- /// ChromeDriver driver = new ChromeDriver(options);
- ///
- ///
- /// For use with RemoteWebDriver:
- ///
- ///
- /// RemoteWebDriver driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), options.ToCapabilities());
- ///
- ///
- public class ChromeOptions : ChromiumOptions
+ public ChromeOptions() : base()
{
- private const string ChromeOptionsCapabilityName = "chromeOptions";
- private const string BrowserNameValue = "chrome";
-
- ///
- /// Initializes a new instance of the class.
- ///
- public ChromeOptions() : base()
- {
- this.BrowserName = BrowserNameValue;
- }
+ this.BrowserName = BrowserNameValue;
+ }
- ///
- /// Gets the vendor prefix to apply to Chromium-specific capability names.
- ///
- protected override string VendorPrefix => "goog";
+ ///
+ /// Gets the vendor prefix to apply to Chromium-specific capability names.
+ ///
+ protected override string VendorPrefix => "goog";
- ///
- /// Gets the name of the capability used to store Chromium options in
- /// an object.
- ///
- public override string CapabilityName => string.Format(CultureInfo.InvariantCulture, "{0}:{1}", this.VendorPrefix, ChromeOptionsCapabilityName);
+ ///
+ /// Gets the name of the capability used to store Chromium options in
+ /// an object.
+ ///
+ public override string CapabilityName => string.Format(CultureInfo.InvariantCulture, "{0}:{1}", this.VendorPrefix, ChromeOptionsCapabilityName);
- ///
- /// Provides a means to add additional capabilities not yet added as type safe options
- /// for the Chrome driver.
- ///
- /// The name of the capability to add.
- /// The value of the capability to add.
- ///
- /// thrown when attempting to add a capability for which there is already a type safe option, or
- /// when is or the empty string.
- ///
- /// Calling
- /// where has already been added will overwrite the
- /// existing value with the new value in .
- /// Calling this method adds capabilities to the Chrome-specific options object passed to
- /// WebDriver executable (property name 'goog:chromeOptions').
- public void AddAdditionalChromeOption(string optionName, object optionValue)
- {
- this.AddAdditionalChromiumOption(optionName, optionValue);
- }
+ ///
+ /// Provides a means to add additional capabilities not yet added as type safe options
+ /// for the Chrome driver.
+ ///
+ /// The name of the capability to add.
+ /// The value of the capability to add.
+ ///
+ /// thrown when attempting to add a capability for which there is already a type safe option, or
+ /// when is or the empty string.
+ ///
+ /// Calling
+ /// where has already been added will overwrite the
+ /// existing value with the new value in .
+ /// Calling this method adds capabilities to the Chrome-specific options object passed to
+ /// WebDriver executable (property name 'goog:chromeOptions').
+ public void AddAdditionalChromeOption(string optionName, object optionValue)
+ {
+ this.AddAdditionalChromiumOption(optionName, optionValue);
}
}
diff --git a/dotnet/src/webdriver/Chromium/ChromiumAndroidOptions.cs b/dotnet/src/webdriver/Chromium/ChromiumAndroidOptions.cs
index 329fa887fbdbb..4ef773e171ca8 100644
--- a/dotnet/src/webdriver/Chromium/ChromiumAndroidOptions.cs
+++ b/dotnet/src/webdriver/Chromium/ChromiumAndroidOptions.cs
@@ -19,29 +19,28 @@
using OpenQA.Selenium.Internal;
-namespace OpenQA.Selenium.Chromium
+namespace OpenQA.Selenium.Chromium;
+
+///
+/// Generates the capabilities for automating Chromium applications on Android
+///
+public class ChromiumAndroidOptions : AndroidOptions
{
///
- /// Generates the capabilities for automating Chromium applications on Android
+ /// Initializes a new instance of the class.
///
- public class ChromiumAndroidOptions : AndroidOptions
+ ///
+ public ChromiumAndroidOptions(string androidPackage) : base(androidPackage)
{
- ///
- /// Initializes a new instance of the class.
- ///
- ///
- public ChromiumAndroidOptions(string androidPackage) : base(androidPackage)
- {
- }
+ }
- ///
- /// Gets or sets a value indicating whether to use an already running app.
- ///
- public bool UseRunningApp { get; set; }
+ ///
+ /// Gets or sets a value indicating whether to use an already running app.
+ ///
+ public bool UseRunningApp { get; set; }
- ///
- /// Gets or sets the process name of the Activity hosting the app.
- ///
- public string? AndroidProcess { get; set; }
- }
+ ///
+ /// Gets or sets the process name of the Activity hosting the app.
+ ///
+ public string? AndroidProcess { get; set; }
}
diff --git a/dotnet/src/webdriver/Chromium/ChromiumDriver.cs b/dotnet/src/webdriver/Chromium/ChromiumDriver.cs
index afe3d1b551fc3..a53c848c851fb 100644
--- a/dotnet/src/webdriver/Chromium/ChromiumDriver.cs
+++ b/dotnet/src/webdriver/Chromium/ChromiumDriver.cs
@@ -26,486 +26,485 @@
using System.IO;
using System.Threading.Tasks;
-namespace OpenQA.Selenium.Chromium
+namespace OpenQA.Selenium.Chromium;
+
+///
+/// Provides an abstract way to access Chromium-based browsers to run tests.
+///
+public class ChromiumDriver : WebDriver, ISupportsLogs, IDevTools
{
///
- /// Provides an abstract way to access Chromium-based browsers to run tests.
+ /// Accept untrusted SSL Certificates
+ ///
+ public static readonly bool AcceptUntrustedCertificates = true;
+
+ ///
+ /// Command for executing a Chrome DevTools Protocol command in a driver for a Chromium-based browser.
+ ///
+ public static readonly string ExecuteCdp = "executeCdpCommand";
+
+ ///
+ /// Command for getting cast sinks in a driver for a Chromium-based browser.
+ ///
+ public static readonly string GetCastSinksCommand = "getCastSinks";
+
+ ///
+ /// Command for selecting a cast sink in a driver for a Chromium-based browser.
+ ///
+ public static readonly string SelectCastSinkCommand = "selectCastSink";
+
+ ///
+ /// Command for starting cast tab mirroring in a driver for a Chromium-based browser.
+ ///
+ public static readonly string StartCastTabMirroringCommand = "startCastTabMirroring";
+
+ ///
+ /// Command for starting cast desktop mirroring in a driver for a Chromium-based browser.
+ ///
+ public static readonly string StartCastDesktopMirroringCommand = "startCastDesktopMirroring";
+
+ ///
+ /// Command for getting a cast issued message in a driver for a Chromium-based browser.
+ ///
+ public static readonly string GetCastIssueMessageCommand = "getCastIssueMessage";
+
+ ///
+ /// Command for stopping casting in a driver for a Chromium-based browser.
+ ///
+ public static readonly string StopCastingCommand = "stopCasting";
+
+ ///
+ /// Command for getting the simulated network conditions in a driver for a Chromium-based browser.
+ ///
+ public static readonly string GetNetworkConditionsCommand = "getNetworkConditions";
+
+ ///
+ /// Command for setting the simulated network conditions in a driver for a Chromium-based browser.
///
- public class ChromiumDriver : WebDriver, ISupportsLogs, IDevTools
+ public static readonly string SetNetworkConditionsCommand = "setNetworkConditions";
+
+ ///
+ /// Command for deleting the simulated network conditions in a driver for a Chromium-based browser.
+ ///
+ public static readonly string DeleteNetworkConditionsCommand = "deleteNetworkConditions";
+
+ ///
+ /// Command for executing a Chrome DevTools Protocol command in a driver for a Chromium-based browser.
+ ///
+ public static readonly string SendChromeCommand = "sendChromeCommand";
+
+ ///
+ /// Command for executing a Chrome DevTools Protocol command that returns a result in a driver for a Chromium-based browser.
+ ///
+ public static readonly string SendChromeCommandWithResult = "sendChromeCommandWithResult";
+
+ ///
+ /// Command for launching an app in a driver for a Chromium-based browser.
+ ///
+ public static readonly string LaunchAppCommand = "launchAppCommand";
+
+ ///
+ /// Command for setting permissions in a driver for a Chromium-based browser.
+ ///
+ public static readonly string SetPermissionCommand = "setPermission";
+
+ private readonly string optionsCapabilityName;
+ private DevToolsSession? devToolsSession;
+
+ private static readonly Dictionary chromiumCustomCommands = new Dictionary()
{
- ///
- /// Accept untrusted SSL Certificates
- ///
- public static readonly bool AcceptUntrustedCertificates = true;
-
- ///
- /// Command for executing a Chrome DevTools Protocol command in a driver for a Chromium-based browser.
- ///
- public static readonly string ExecuteCdp = "executeCdpCommand";
-
- ///
- /// Command for getting cast sinks in a driver for a Chromium-based browser.
- ///
- public static readonly string GetCastSinksCommand = "getCastSinks";
-
- ///
- /// Command for selecting a cast sink in a driver for a Chromium-based browser.
- ///
- public static readonly string SelectCastSinkCommand = "selectCastSink";
-
- ///
- /// Command for starting cast tab mirroring in a driver for a Chromium-based browser.
- ///
- public static readonly string StartCastTabMirroringCommand = "startCastTabMirroring";
-
- ///
- /// Command for starting cast desktop mirroring in a driver for a Chromium-based browser.
- ///
- public static readonly string StartCastDesktopMirroringCommand = "startCastDesktopMirroring";
-
- ///
- /// Command for getting a cast issued message in a driver for a Chromium-based browser.
- ///
- public static readonly string GetCastIssueMessageCommand = "getCastIssueMessage";
-
- ///
- /// Command for stopping casting in a driver for a Chromium-based browser.
- ///
- public static readonly string StopCastingCommand = "stopCasting";
-
- ///
- /// Command for getting the simulated network conditions in a driver for a Chromium-based browser.
- ///
- public static readonly string GetNetworkConditionsCommand = "getNetworkConditions";
-
- ///
- /// Command for setting the simulated network conditions in a driver for a Chromium-based browser.
- ///
- public static readonly string SetNetworkConditionsCommand = "setNetworkConditions";
-
- ///
- /// Command for deleting the simulated network conditions in a driver for a Chromium-based browser.
- ///
- public static readonly string DeleteNetworkConditionsCommand = "deleteNetworkConditions";
-
- ///
- /// Command for executing a Chrome DevTools Protocol command in a driver for a Chromium-based browser.
- ///
- public static readonly string SendChromeCommand = "sendChromeCommand";
-
- ///
- /// Command for executing a Chrome DevTools Protocol command that returns a result in a driver for a Chromium-based browser.
- ///
- public static readonly string SendChromeCommandWithResult = "sendChromeCommandWithResult";
-
- ///
- /// Command for launching an app in a driver for a Chromium-based browser.
- ///
- public static readonly string LaunchAppCommand = "launchAppCommand";
-
- ///
- /// Command for setting permissions in a driver for a Chromium-based browser.
- ///
- public static readonly string SetPermissionCommand = "setPermission";
-
- private readonly string optionsCapabilityName;
- private DevToolsSession? devToolsSession;
-
- private static readonly Dictionary chromiumCustomCommands = new Dictionary()
- {
- { GetNetworkConditionsCommand, new HttpCommandInfo(HttpCommandInfo.GetCommand, "/session/{sessionId}/chromium/network_conditions") },
- { SetNetworkConditionsCommand, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/chromium/network_conditions") },
- { DeleteNetworkConditionsCommand, new HttpCommandInfo(HttpCommandInfo.DeleteCommand, "/session/{sessionId}/chromium/network_conditions") },
- { SendChromeCommand, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/chromium/send_command") },
- { SendChromeCommandWithResult, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/chromium/send_command_and_get_result") },
- { LaunchAppCommand, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/chromium/launch_app") },
- { SetPermissionCommand, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/permissions") }
- };
-
- ///
- /// Initializes a new instance of the class using the specified .
- ///
- /// The to use.
- /// The to be used with the ChromiumDriver.
- /// The maximum amount of time to wait for each command.
- /// If or are .
- /// If the Chromium options capability name is .
- protected ChromiumDriver(ChromiumDriverService service, ChromiumOptions options, TimeSpan commandTimeout)
- : base(GenerateDriverServiceCommandExecutor(service, options, commandTimeout), ConvertOptionsToCapabilities(options))
- {
- this.optionsCapabilityName = options.CapabilityName ?? throw new ArgumentException("No chromium options capability name specified", nameof(options));
- }
+ { GetNetworkConditionsCommand, new HttpCommandInfo(HttpCommandInfo.GetCommand, "/session/{sessionId}/chromium/network_conditions") },
+ { SetNetworkConditionsCommand, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/chromium/network_conditions") },
+ { DeleteNetworkConditionsCommand, new HttpCommandInfo(HttpCommandInfo.DeleteCommand, "/session/{sessionId}/chromium/network_conditions") },
+ { SendChromeCommand, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/chromium/send_command") },
+ { SendChromeCommandWithResult, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/chromium/send_command_and_get_result") },
+ { LaunchAppCommand, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/chromium/launch_app") },
+ { SetPermissionCommand, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/permissions") }
+ };
- ///
- /// Gets the dictionary of custom Chromium commands registered with the driver.
- ///
- protected static IReadOnlyDictionary ChromiumCustomCommands => new ReadOnlyDictionary(chromiumCustomCommands);
-
- ///
- /// Uses DriverFinder to set Service attributes if necessary when creating the command executor
- ///
- ///
- ///
- ///
- ///
- private static ICommandExecutor GenerateDriverServiceCommandExecutor(DriverService service, DriverOptions options, TimeSpan commandTimeout)
- {
- if (service is null)
- {
- throw new ArgumentNullException(nameof(service));
- }
+ ///
+ /// Initializes a new instance of the class using the specified .
+ ///
+ /// The to use.
+ /// The to be used with the ChromiumDriver.
+ /// The maximum amount of time to wait for each command.
+ /// If or are .
+ /// If the Chromium options capability name is .
+ protected ChromiumDriver(ChromiumDriverService service, ChromiumOptions options, TimeSpan commandTimeout)
+ : base(GenerateDriverServiceCommandExecutor(service, options, commandTimeout), ConvertOptionsToCapabilities(options))
+ {
+ this.optionsCapabilityName = options.CapabilityName ?? throw new ArgumentException("No chromium options capability name specified", nameof(options));
+ }
- if (options is null)
- {
- throw new ArgumentNullException(nameof(options));
- }
+ ///
+ /// Gets the dictionary of custom Chromium commands registered with the driver.
+ ///
+ protected static IReadOnlyDictionary ChromiumCustomCommands => new ReadOnlyDictionary(chromiumCustomCommands);
- if (service.DriverServicePath == null)
- {
- DriverFinder finder = new DriverFinder(options);
- string fullServicePath = finder.GetDriverPath();
- service.DriverServicePath = Path.GetDirectoryName(fullServicePath);
- service.DriverServiceExecutableName = Path.GetFileName(fullServicePath);
- if (finder.TryGetBrowserPath(out string? browserPath))
- {
- options.BinaryLocation = browserPath;
- options.BrowserVersion = null;
- }
- }
- return new DriverServiceCommandExecutor(service, commandTimeout);
+ ///
+ /// Uses DriverFinder to set Service attributes if necessary when creating the command executor
+ ///
+ ///
+ ///
+ ///
+ ///
+ private static ICommandExecutor GenerateDriverServiceCommandExecutor(DriverService service, DriverOptions options, TimeSpan commandTimeout)
+ {
+ if (service is null)
+ {
+ throw new ArgumentNullException(nameof(service));
}
- ///
- /// Gets or sets the responsible for detecting
- /// sequences of keystrokes representing file paths and names.
- ///
- /// The Chromium driver does not allow a file detector to be set,
- /// as the server component of the Chromium driver only
- /// allows uploads from the local computer environment. Attempting to set
- /// this property has no effect, but does not throw an exception. If you
- /// are attempting to run the Chromium driver remotely, use
- /// in conjunction with a standalone WebDriver server.
- public override IFileDetector FileDetector
+ if (options is null)
{
- get => base.FileDetector;
- set { }
+ throw new ArgumentNullException(nameof(options));
}
- ///
- /// Gets a value indicating whether a DevTools session is active.
- ///
- [MemberNotNullWhen(true, nameof(devToolsSession))]
- public bool HasActiveDevToolsSession => this.devToolsSession != null;
-
- ///
- /// Gets or sets the network condition emulation for Chromium.
- ///
- /// If the value is set to .
- public ChromiumNetworkConditions NetworkConditions
+ if (service.DriverServicePath == null)
{
- get
+ DriverFinder finder = new DriverFinder(options);
+ string fullServicePath = finder.GetDriverPath();
+ service.DriverServicePath = Path.GetDirectoryName(fullServicePath);
+ service.DriverServiceExecutableName = Path.GetFileName(fullServicePath);
+ if (finder.TryGetBrowserPath(out string? browserPath))
{
- Response response = this.Execute(GetNetworkConditionsCommand, null);
- if (response.Value is not Dictionary responseDictionary)
- {
- throw new WebDriverException($"GetNetworkConditions command returned successfully, but data was not an object: {response.Value}");
- }
-
- return ChromiumNetworkConditions.FromDictionary(responseDictionary);
+ options.BinaryLocation = browserPath;
+ options.BrowserVersion = null;
}
+ }
+ return new DriverServiceCommandExecutor(service, commandTimeout);
+ }
- set
- {
- if (value == null)
- {
- throw new ArgumentNullException(nameof(value), "value must not be null");
- }
+ ///
+ /// Gets or sets the responsible for detecting
+ /// sequences of keystrokes representing file paths and names.
+ ///
+ /// The Chromium driver does not allow a file detector to be set,
+ /// as the server component of the Chromium driver only
+ /// allows uploads from the local computer environment. Attempting to set
+ /// this property has no effect, but does not throw an exception. If you
+ /// are attempting to run the Chromium driver remotely, use
+ /// in conjunction with a standalone WebDriver server.
+ public override IFileDetector FileDetector
+ {
+ get => base.FileDetector;
+ set { }
+ }
- Dictionary parameters = new Dictionary();
- parameters["network_conditions"] = value;
+ ///
+ /// Gets a value indicating whether a DevTools session is active.
+ ///
+ [MemberNotNullWhen(true, nameof(devToolsSession))]
+ public bool HasActiveDevToolsSession => this.devToolsSession != null;
- this.Execute(SetNetworkConditionsCommand, parameters);
+ ///
+ /// Gets or sets the network condition emulation for Chromium.
+ ///
+ /// If the value is set to .
+ public ChromiumNetworkConditions NetworkConditions
+ {
+ get
+ {
+ Response response = this.Execute(GetNetworkConditionsCommand, null);
+ if (response.Value is not Dictionary responseDictionary)
+ {
+ throw new WebDriverException($"GetNetworkConditions command returned successfully, but data was not an object: {response.Value}");
}
+
+ return ChromiumNetworkConditions.FromDictionary(responseDictionary);
}
- ///
- /// Launches a Chromium based application.
- ///
- /// ID of the chromium app to launch.
- /// If is .
- public void LaunchApp(string id)
+ set
{
- if (id == null)
+ if (value == null)
{
- throw new ArgumentNullException(nameof(id), "id must not be null");
+ throw new ArgumentNullException(nameof(value), "value must not be null");
}
Dictionary parameters = new Dictionary();
- parameters["id"] = id;
+ parameters["network_conditions"] = value;
- this.Execute(LaunchAppCommand, parameters);
+ this.Execute(SetNetworkConditionsCommand, parameters);
}
+ }
- ///
- /// Set supported permission on browser.
- ///
- /// Name of item to set the permission on.
- /// Value to set the permission to.
- /// If or are .
- public void SetPermission(string permissionName, string permissionValue)
+ ///
+ /// Launches a Chromium based application.
+ ///
+ /// ID of the chromium app to launch.
+ /// If is .
+ public void LaunchApp(string id)
+ {
+ if (id == null)
{
- if (permissionName == null)
- {
- throw new ArgumentNullException(nameof(permissionName), "name must not be null");
- }
+ throw new ArgumentNullException(nameof(id), "id must not be null");
+ }
- if (permissionValue == null)
- {
- throw new ArgumentNullException(nameof(permissionValue), "value must not be null");
- }
+ Dictionary parameters = new Dictionary();
+ parameters["id"] = id;
- Dictionary nameParameter = new Dictionary();
- nameParameter["name"] = permissionName;
- Dictionary parameters = new Dictionary();
- parameters["descriptor"] = nameParameter;
- parameters["state"] = permissionValue;
- this.Execute(SetPermissionCommand, parameters);
- }
+ this.Execute(LaunchAppCommand, parameters);
+ }
- ///
- /// Executes a custom Chrome Dev Tools Protocol Command.
- ///
- /// Name of the command to execute.
- /// Parameters of the command to execute.
- /// An object representing the result of the command, if applicable.
- /// If is .
- public object? ExecuteCdpCommand(string commandName, Dictionary commandParameters)
+ ///
+ /// Set supported permission on browser.
+ ///
+ /// Name of item to set the permission on.
+ /// Value to set the permission to.
+ /// If or are .
+ public void SetPermission(string permissionName, string permissionValue)
+ {
+ if (permissionName == null)
{
- if (commandName == null)
- {
- throw new ArgumentNullException(nameof(commandName), "commandName must not be null");
- }
-
- Dictionary parameters = new Dictionary();
- parameters["cmd"] = commandName;
- parameters["params"] = commandParameters;
- Response response = this.Execute(ExecuteCdp, parameters);
- return response.Value;
+ throw new ArgumentNullException(nameof(permissionName), "name must not be null");
}
- ///
- /// Creates a session to communicate with a browser using the Chromium Developer Tools debugging protocol.
- ///
- /// The active session to use to communicate with the Chromium Developer Tools debugging protocol.
- [RequiresUnreferencedCode(DevToolsSession.CDP_AOTIncompatibilityMessage)]
- [RequiresDynamicCode(DevToolsSession.CDP_AOTIncompatibilityMessage)]
- public DevToolsSession GetDevToolsSession()
+ if (permissionValue == null)
{
- return GetDevToolsSession(new DevToolsOptions() { ProtocolVersion = DevToolsSession.AutoDetectDevToolsProtocolVersion });
+ throw new ArgumentNullException(nameof(permissionValue), "value must not be null");
}
- ///
- /// Creates a session to communicate with a browser using the Chromium Developer Tools debugging protocol.
- ///
- /// The active session to use to communicate with the Chromium Developer Tools debugging protocol.
- [RequiresUnreferencedCode(DevToolsSession.CDP_AOTIncompatibilityMessage)]
- [RequiresDynamicCode(DevToolsSession.CDP_AOTIncompatibilityMessage)]
- public DevToolsSession GetDevToolsSession(DevToolsOptions options)
+ Dictionary nameParameter = new Dictionary();
+ nameParameter["name"] = permissionName;
+ Dictionary parameters = new Dictionary();
+ parameters["descriptor"] = nameParameter;
+ parameters["state"] = permissionValue;
+ this.Execute(SetPermissionCommand, parameters);
+ }
+
+ ///
+ /// Executes a custom Chrome Dev Tools Protocol Command.
+ ///
+ /// Name of the command to execute.
+ /// Parameters of the command to execute.
+ /// An object representing the result of the command, if applicable.
+ /// If is .
+ public object? ExecuteCdpCommand(string commandName, Dictionary commandParameters)
+ {
+ if (commandName == null)
{
- if (this.devToolsSession == null)
- {
- if (!this.Capabilities.HasCapability(this.optionsCapabilityName))
- {
- throw new WebDriverException("Cannot find " + this.optionsCapabilityName + " capability for driver");
- }
+ throw new ArgumentNullException(nameof(commandName), "commandName must not be null");
+ }
- object? optionsCapabilityObject = this.Capabilities.GetCapability(this.optionsCapabilityName);
- if (optionsCapabilityObject is not Dictionary optionsCapability)
- {
- throw new WebDriverException($"Found {this.optionsCapabilityName} capability, but is not an object: {optionsCapabilityObject}");
- }
+ Dictionary parameters = new Dictionary();
+ parameters["cmd"] = commandName;
+ parameters["params"] = commandParameters;
+ Response response = this.Execute(ExecuteCdp, parameters);
+ return response.Value;
+ }
- if (!optionsCapability.TryGetValue("debuggerAddress", out object? debuggerAddress))
- {
- throw new WebDriverException("Did not find debuggerAddress capability in " + this.optionsCapabilityName);
- }
+ ///
+ /// Creates a session to communicate with a browser using the Chromium Developer Tools debugging protocol.
+ ///
+ /// The active session to use to communicate with the Chromium Developer Tools debugging protocol.
+ [RequiresUnreferencedCode(DevToolsSession.CDP_AOTIncompatibilityMessage)]
+ [RequiresDynamicCode(DevToolsSession.CDP_AOTIncompatibilityMessage)]
+ public DevToolsSession GetDevToolsSession()
+ {
+ return GetDevToolsSession(new DevToolsOptions() { ProtocolVersion = DevToolsSession.AutoDetectDevToolsProtocolVersion });
+ }
- try
- {
- DevToolsSession session = new DevToolsSession(debuggerAddress?.ToString()!, options);
- Task.Run(async () => await session.StartSession()).GetAwaiter().GetResult();
- this.devToolsSession = session;
- }
- catch (Exception e)
- {
- throw new WebDriverException("Unexpected error creating WebSocket DevTools session.", e);
- }
+ ///
+ /// Creates a session to communicate with a browser using the Chromium Developer Tools debugging protocol.
+ ///
+ /// The active session to use to communicate with the Chromium Developer Tools debugging protocol.
+ [RequiresUnreferencedCode(DevToolsSession.CDP_AOTIncompatibilityMessage)]
+ [RequiresDynamicCode(DevToolsSession.CDP_AOTIncompatibilityMessage)]
+ public DevToolsSession GetDevToolsSession(DevToolsOptions options)
+ {
+ if (this.devToolsSession == null)
+ {
+ if (!this.Capabilities.HasCapability(this.optionsCapabilityName))
+ {
+ throw new WebDriverException("Cannot find " + this.optionsCapabilityName + " capability for driver");
}
- return this.devToolsSession;
- }
+ object? optionsCapabilityObject = this.Capabilities.GetCapability(this.optionsCapabilityName);
+ if (optionsCapabilityObject is not Dictionary optionsCapability)
+ {
+ throw new WebDriverException($"Found {this.optionsCapabilityName} capability, but is not an object: {optionsCapabilityObject}");
+ }
- ///
- /// Creates a session to communicate with a browser using the Chromium Developer Tools debugging protocol.
- ///
- /// The version of the Chromium Developer Tools protocol to use. Defaults to autodetect the protocol version.
- /// The active session to use to communicate with the Chromium Developer Tools debugging protocol.
- [Obsolete("Use GetDevToolsSession(DevToolsOptions options)")]
- [RequiresUnreferencedCode(DevToolsSession.CDP_AOTIncompatibilityMessage)]
- [RequiresDynamicCode(DevToolsSession.CDP_AOTIncompatibilityMessage)]
- public DevToolsSession GetDevToolsSession(int devToolsProtocolVersion)
- {
- return GetDevToolsSession(new DevToolsOptions() { ProtocolVersion = devToolsProtocolVersion });
- }
+ if (!optionsCapability.TryGetValue("debuggerAddress", out object? debuggerAddress))
+ {
+ throw new WebDriverException("Did not find debuggerAddress capability in " + this.optionsCapabilityName);
+ }
- ///
- /// Closes a DevTools session.
- ///
- [RequiresUnreferencedCode(DevToolsSession.CDP_AOTIncompatibilityMessage)]
- [RequiresDynamicCode(DevToolsSession.CDP_AOTIncompatibilityMessage)]
- public void CloseDevToolsSession()
- {
- if (this.devToolsSession != null)
+ try
{
- Task.Run(async () => await this.devToolsSession.StopSession(manualDetach: true)).GetAwaiter().GetResult();
+ DevToolsSession session = new DevToolsSession(debuggerAddress?.ToString()!, options);
+ Task.Run(async () => await session.StartSession()).GetAwaiter().GetResult();
+ this.devToolsSession = session;
+ }
+ catch (Exception e)
+ {
+ throw new WebDriverException("Unexpected error creating WebSocket DevTools session.", e);
}
}
- ///
- /// Clears simulated network conditions.
- ///
- public void ClearNetworkConditions()
+ return this.devToolsSession;
+ }
+
+ ///
+ /// Creates a session to communicate with a browser using the Chromium Developer Tools debugging protocol.
+ ///
+ /// The version of the Chromium Developer Tools protocol to use. Defaults to autodetect the protocol version.
+ /// The active session to use to communicate with the Chromium Developer Tools debugging protocol.
+ [Obsolete("Use GetDevToolsSession(DevToolsOptions options)")]
+ [RequiresUnreferencedCode(DevToolsSession.CDP_AOTIncompatibilityMessage)]
+ [RequiresDynamicCode(DevToolsSession.CDP_AOTIncompatibilityMessage)]
+ public DevToolsSession GetDevToolsSession(int devToolsProtocolVersion)
+ {
+ return GetDevToolsSession(new DevToolsOptions() { ProtocolVersion = devToolsProtocolVersion });
+ }
+
+ ///
+ /// Closes a DevTools session.
+ ///
+ [RequiresUnreferencedCode(DevToolsSession.CDP_AOTIncompatibilityMessage)]
+ [RequiresDynamicCode(DevToolsSession.CDP_AOTIncompatibilityMessage)]
+ public void CloseDevToolsSession()
+ {
+ if (this.devToolsSession != null)
{
- this.Execute(DeleteNetworkConditionsCommand, null);
+ Task.Run(async () => await this.devToolsSession.StopSession(manualDetach: true)).GetAwaiter().GetResult();
}
+ }
+
+ ///
+ /// Clears simulated network conditions.
+ ///
+ public void ClearNetworkConditions()
+ {
+ this.Execute(DeleteNetworkConditionsCommand, null);
+ }
- ///
- /// Returns the list of cast sinks (Cast devices) available to the Chrome media router.
- ///
- /// The list of available sinks.
- public List> GetCastSinks()
+ ///
+ /// Returns the list of cast sinks (Cast devices) available to the Chrome media router.
+ ///
+ /// The list of available sinks.
+ public List> GetCastSinks()
+ {
+ List> returnValue = new List>();
+ Response response = this.Execute(GetCastSinksCommand, null);
+ if (response.Value is object?[] responseValue)
{
- List> returnValue = new List>();
- Response response = this.Execute(GetCastSinksCommand, null);
- if (response.Value is object?[] responseValue)
+ foreach (object? entry in responseValue)
{
- foreach (object? entry in responseValue)
+ if (entry is Dictionary entryValue)
{
- if (entry is Dictionary entryValue)
+ Dictionary sink = new Dictionary();
+ foreach (KeyValuePair pair in entryValue)
{
- Dictionary sink = new Dictionary();
- foreach (KeyValuePair pair in entryValue)
- {
- sink[pair.Key] = pair.Value!.ToString()!;
- }
-
- returnValue.Add(sink);
+ sink[pair.Key] = pair.Value!.ToString()!;
}
+
+ returnValue.Add(sink);
}
}
- return returnValue;
}
+ return returnValue;
+ }
- ///
- /// Selects a cast sink (Cast device) as the recipient of media router intents (connect or play).
- ///
- /// Name of the target sink (device).
- public void SelectCastSink(string deviceName)
+ ///
+ /// Selects a cast sink (Cast device) as the recipient of media router intents (connect or play).
+ ///
+ /// Name of the target sink (device).
+ public void SelectCastSink(string deviceName)
+ {
+ if (deviceName == null)
{
- if (deviceName == null)
- {
- throw new ArgumentNullException(nameof(deviceName), "deviceName must not be null");
- }
-
- Dictionary parameters = new Dictionary();
- parameters["sinkName"] = deviceName;
- this.Execute(SelectCastSinkCommand, parameters);
+ throw new ArgumentNullException(nameof(deviceName), "deviceName must not be null");
}
- ///
- /// Initiates tab mirroring for the current browser tab on the specified device.
- ///
- /// Name of the target sink (device).
- public void StartTabMirroring(string deviceName)
- {
- if (deviceName == null)
- {
- throw new ArgumentNullException(nameof(deviceName), "deviceName must not be null");
- }
-
- Dictionary parameters = new Dictionary();
- parameters["sinkName"] = deviceName;
- this.Execute(StartCastTabMirroringCommand, parameters);
- }
+ Dictionary parameters = new Dictionary();
+ parameters["sinkName"] = deviceName;
+ this.Execute(SelectCastSinkCommand, parameters);
+ }
- ///
- /// Initiates mirroring of the desktop on the specified device.
- ///
- /// Name of the target sink (device).
- public void StartDesktopMirroring(string deviceName)
+ ///
+ /// Initiates tab mirroring for the current browser tab on the specified device.
+ ///
+ /// Name of the target sink (device).
+ public void StartTabMirroring(string deviceName)
+ {
+ if (deviceName == null)
{
- if (deviceName == null)
- {
- throw new ArgumentNullException(nameof(deviceName), "deviceName must not be null");
- }
-
- Dictionary parameters = new Dictionary();
- parameters["sinkName"] = deviceName;
- this.Execute(StartCastDesktopMirroringCommand, parameters);
+ throw new ArgumentNullException(nameof(deviceName), "deviceName must not be null");
}
- ///
- /// Returns the error message if there is any issue in a Cast session.
- ///
- /// An error message.
- public string? GetCastIssueMessage()
+ Dictionary parameters = new Dictionary();
+ parameters["sinkName"] = deviceName;
+ this.Execute(StartCastTabMirroringCommand, parameters);
+ }
+
+ ///
+ /// Initiates mirroring of the desktop on the specified device.
+ ///
+ /// Name of the target sink (device).
+ public void StartDesktopMirroring(string deviceName)
+ {
+ if (deviceName == null)
{
- Response response = this.Execute(GetCastIssueMessageCommand, null);
- return (string?)response.Value;
+ throw new ArgumentNullException(nameof(deviceName), "deviceName must not be null");
}
- ///
- /// Stops casting from media router to the specified device, if connected.
- ///
- /// Name of the target sink (device).
- public void StopCasting(string deviceName)
- {
- if (deviceName == null)
- {
- throw new ArgumentNullException(nameof(deviceName), "deviceName must not be null");
- }
+ Dictionary parameters = new Dictionary();
+ parameters["sinkName"] = deviceName;
+ this.Execute(StartCastDesktopMirroringCommand, parameters);
+ }
- Dictionary parameters = new Dictionary();
- parameters["sinkName"] = deviceName;
- this.Execute(StopCastingCommand, parameters);
- }
+ ///
+ /// Returns the error message if there is any issue in a Cast session.
+ ///
+ /// An error message.
+ public string? GetCastIssueMessage()
+ {
+ Response response = this.Execute(GetCastIssueMessageCommand, null);
+ return (string?)response.Value;
+ }
- ///
- /// Stops the driver from running
- ///
- /// if its in the process of disposing
- protected override void Dispose(bool disposing)
+ ///
+ /// Stops casting from media router to the specified device, if connected.
+ ///
+ /// Name of the target sink (device).
+ public void StopCasting(string deviceName)
+ {
+ if (deviceName == null)
{
- if (disposing)
- {
- if (this.devToolsSession != null)
- {
- this.devToolsSession.Dispose();
- this.devToolsSession = null;
- }
- }
-
- base.Dispose(disposing);
+ throw new ArgumentNullException(nameof(deviceName), "deviceName must not be null");
}
- private static ICapabilities ConvertOptionsToCapabilities(ChromiumOptions options)
+ Dictionary parameters = new Dictionary();
+ parameters["sinkName"] = deviceName;
+ this.Execute(StopCastingCommand, parameters);
+ }
+
+ ///
+ /// Stops the driver from running
+ ///
+ /// if its in the process of disposing
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
{
- if (options == null)
+ if (this.devToolsSession != null)
{
- throw new ArgumentNullException(nameof(options), "options must not be null");
+ this.devToolsSession.Dispose();
+ this.devToolsSession = null;
}
+ }
+
+ base.Dispose(disposing);
+ }
- return options.ToCapabilities();
+ private static ICapabilities ConvertOptionsToCapabilities(ChromiumOptions options)
+ {
+ if (options == null)
+ {
+ throw new ArgumentNullException(nameof(options), "options must not be null");
}
+
+ return options.ToCapabilities();
}
}
diff --git a/dotnet/src/webdriver/Chromium/ChromiumDriverService.cs b/dotnet/src/webdriver/Chromium/ChromiumDriverService.cs
index e9fbf0f7f7218..9c10e635d8df8 100644
--- a/dotnet/src/webdriver/Chromium/ChromiumDriverService.cs
+++ b/dotnet/src/webdriver/Chromium/ChromiumDriverService.cs
@@ -21,179 +21,178 @@
using System.Globalization;
using System.Text;
-namespace OpenQA.Selenium.Chromium
+namespace OpenQA.Selenium.Chromium;
+
+///
+/// Exposes the service provided by the native ChromiumDriver executable.
+///
+public abstract class ChromiumDriverService : DriverService
{
+ private const string DefaultChromeDriverServiceExecutableName = "chromedriver";
+
///
- /// Exposes the service provided by the native ChromiumDriver executable.
+ /// Initializes a new instance of the class.
///
- public abstract class ChromiumDriverService : DriverService
+ /// The full path to the ChromeDriver executable.
+ /// The file name of the ChromeDriver executable.
+ /// The port on which the ChromeDriver executable should listen.
+ protected ChromiumDriverService(string? executablePath, string? executableFileName, int port)
+ : base(executablePath, port, executableFileName)
{
- private const string DefaultChromeDriverServiceExecutableName = "chromedriver";
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The full path to the ChromeDriver executable.
- /// The file name of the ChromeDriver executable.
- /// The port on which the ChromeDriver executable should listen.
- protected ChromiumDriverService(string? executablePath, string? executableFileName, int port)
- : base(executablePath, port, executableFileName)
- {
- }
+ }
- ///
- /// Gets or sets the location of the log file written to by the ChromeDriver executable.
- /// or signify no log path.
- ///
- public string? LogPath { get; set; }
-
- ///
- /// Gets or sets the base URL path prefix for commands (e.g., "wd/url").
- /// or signify no prefix.
- ///
- public string? UrlPathPrefix { get; set; }
-
- ///
- /// Gets or sets the address of a server to contact for reserving a port.
- /// or signify no port server.
- ///
- public string? PortServerAddress { get; set; }
-
- ///
- /// Gets or sets the port on which the Android Debug Bridge is listening for commands.
- /// A value less than or equal to 0, or , indicates no Android Debug Bridge specified.
- ///
- public int? AndroidDebugBridgePort { get; set; }
-
- ///
- /// Gets or sets a value indicating whether to skip version compatibility check
- /// between the driver and the browser.
- /// Defaults to .
- ///
- public bool DisableBuildCheck { get; set; }
-
- ///
- /// Gets or sets a value indicating whether to enable verbose logging for the ChromeDriver executable.
- /// Defaults to .
- ///
- public bool EnableVerboseLogging { get; set; }
-
- ///
- /// Gets or sets a value indicating whether to enable appending to an existing ChromeDriver log file.
- /// Defaults to .
- ///
- public bool EnableAppendLog { get; set; }
-
- ///
- /// Gets or sets the comma-delimited list of IP addresses that are approved to connect to this instance of the Chrome driver.
- /// A value of or means only the local loopback address can connect.
- ///
- [Obsolete($"Use {nameof(AllowedIPAddresses)}")]
- public string? WhitelistedIPAddresses
- {
- get => this.AllowedIPAddresses;
- set => this.AllowedIPAddresses = value;
- }
+ ///
+ /// Gets or sets the location of the log file written to by the ChromeDriver executable.
+ /// or signify no log path.
+ ///
+ public string? LogPath { get; set; }
+
+ ///
+ /// Gets or sets the base URL path prefix for commands (e.g., "wd/url").
+ /// or signify no prefix.
+ ///
+ public string? UrlPathPrefix { get; set; }
+
+ ///
+ /// Gets or sets the address of a server to contact for reserving a port.
+ /// or signify no port server.
+ ///
+ public string? PortServerAddress { get; set; }
+
+ ///
+ /// Gets or sets the port on which the Android Debug Bridge is listening for commands.
+ /// A value less than or equal to 0, or , indicates no Android Debug Bridge specified.
+ ///
+ public int? AndroidDebugBridgePort { get; set; }
- ///
- /// Gets or sets the comma-delimited list of IP addresses that are approved to connect to this instance of the Chrome driver.
- /// A value of or means only the local loopback address can connect.
- ///
- public string? AllowedIPAddresses { get; set; }
+ ///
+ /// Gets or sets a value indicating whether to skip version compatibility check
+ /// between the driver and the browser.
+ /// Defaults to .
+ ///
+ public bool DisableBuildCheck { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether to enable verbose logging for the ChromeDriver executable.
+ /// Defaults to .
+ ///
+ public bool EnableVerboseLogging { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether to enable appending to an existing ChromeDriver log file.
+ /// Defaults to .
+ ///
+ public bool EnableAppendLog { get; set; }
+
+ ///
+ /// Gets or sets the comma-delimited list of IP addresses that are approved to connect to this instance of the Chrome driver.
+ /// A value of or means only the local loopback address can connect.
+ ///
+ [Obsolete($"Use {nameof(AllowedIPAddresses)}")]
+ public string? WhitelistedIPAddresses
+ {
+ get => this.AllowedIPAddresses;
+ set => this.AllowedIPAddresses = value;
+ }
+
+ ///
+ /// Gets or sets the comma-delimited list of IP addresses that are approved to connect to this instance of the Chrome driver.
+ /// A value of or means only the local loopback address can connect.
+ ///
+ public string? AllowedIPAddresses { get; set; }
- ///
- /// Gets the command-line arguments for the driver service.
- ///
- protected override string CommandLineArguments
+ ///
+ /// Gets the command-line arguments for the driver service.
+ ///
+ protected override string CommandLineArguments
+ {
+ get
{
- get
+ StringBuilder argsBuilder = new StringBuilder(base.CommandLineArguments);
+ if (this.AndroidDebugBridgePort is int adb && adb > 0)
{
- StringBuilder argsBuilder = new StringBuilder(base.CommandLineArguments);
- if (this.AndroidDebugBridgePort is int adb && adb > 0)
- {
- argsBuilder.AppendFormat(CultureInfo.InvariantCulture, " --adb-port={0}", adb);
- }
-
- if (this.SuppressInitialDiagnosticInformation)
- {
- argsBuilder.Append(" --silent");
- }
-
- if (this.DisableBuildCheck)
- {
- argsBuilder.Append(" --disable-build-check");
- }
-
- if (this.EnableVerboseLogging)
- {
- argsBuilder.Append(" --verbose");
- }
-
- if (this.EnableAppendLog)
- {
- argsBuilder.Append(" --append-log");
- }
-
- if (!string.IsNullOrEmpty(this.LogPath))
- {
- argsBuilder.AppendFormat(CultureInfo.InvariantCulture, " --log-path=\"{0}\"", this.LogPath);
- }
-
- if (!string.IsNullOrEmpty(this.UrlPathPrefix))
- {
- argsBuilder.AppendFormat(CultureInfo.InvariantCulture, " --url-base={0}", this.UrlPathPrefix);
- }
-
- if (!string.IsNullOrEmpty(this.PortServerAddress))
- {
- argsBuilder.AppendFormat(CultureInfo.InvariantCulture, " --port-server={0}", this.PortServerAddress);
- }
-
- if (!string.IsNullOrEmpty(this.AllowedIPAddresses))
- {
- argsBuilder.Append(string.Format(CultureInfo.InvariantCulture, " -allowed-ips={0}", this.AllowedIPAddresses));
- }
-
- return argsBuilder.ToString();
+ argsBuilder.AppendFormat(CultureInfo.InvariantCulture, " --adb-port={0}", adb);
}
- }
- ///
- /// Returns the Chromium driver filename for the currently running platform
- ///
- /// The name of the Chromium executable. Default is "chromedriver".
- /// The file name of the Chromium driver service executable.
- protected static string ChromiumDriverServiceFileName(string fileName = DefaultChromeDriverServiceExecutableName)
- {
- // Unfortunately, detecting the currently running platform isn't as
- // straightforward as you might hope.
- // See: http://mono.wikia.com/wiki/Detecting_the_execution_platform
- // and https://msdn.microsoft.com/en-us/library/3a8hyw88(v=vs.110).aspx
- const PlatformID PlatformIDMonoUnix = (PlatformID)128;
+ if (this.SuppressInitialDiagnosticInformation)
+ {
+ argsBuilder.Append(" --silent");
+ }
+
+ if (this.DisableBuildCheck)
+ {
+ argsBuilder.Append(" --disable-build-check");
+ }
+
+ if (this.EnableVerboseLogging)
+ {
+ argsBuilder.Append(" --verbose");
+ }
+
+ if (this.EnableAppendLog)
+ {
+ argsBuilder.Append(" --append-log");
+ }
+
+ if (!string.IsNullOrEmpty(this.LogPath))
+ {
+ argsBuilder.AppendFormat(CultureInfo.InvariantCulture, " --log-path=\"{0}\"", this.LogPath);
+ }
+
+ if (!string.IsNullOrEmpty(this.UrlPathPrefix))
+ {
+ argsBuilder.AppendFormat(CultureInfo.InvariantCulture, " --url-base={0}", this.UrlPathPrefix);
+ }
- switch (Environment.OSVersion.Platform)
+ if (!string.IsNullOrEmpty(this.PortServerAddress))
{
- case PlatformID.Win32NT:
- case PlatformID.Win32S:
- case PlatformID.Win32Windows:
- case PlatformID.WinCE:
- fileName += ".exe";
- break;
-
- case PlatformID.MacOSX:
- case PlatformID.Unix:
- case PlatformIDMonoUnix:
- break;
-
- // Don't handle the Xbox case. Let default handle it.
- // case PlatformID.Xbox:
- // break;
-
- default:
- throw new WebDriverException("Unsupported platform: " + Environment.OSVersion.Platform);
+ argsBuilder.AppendFormat(CultureInfo.InvariantCulture, " --port-server={0}", this.PortServerAddress);
}
- return fileName;
+ if (!string.IsNullOrEmpty(this.AllowedIPAddresses))
+ {
+ argsBuilder.Append(string.Format(CultureInfo.InvariantCulture, " -allowed-ips={0}", this.AllowedIPAddresses));
+ }
+
+ return argsBuilder.ToString();
}
}
+
+ ///
+ /// Returns the Chromium driver filename for the currently running platform
+ ///
+ /// The name of the Chromium executable. Default is "chromedriver".
+ /// The file name of the Chromium driver service executable.
+ protected static string ChromiumDriverServiceFileName(string fileName = DefaultChromeDriverServiceExecutableName)
+ {
+ // Unfortunately, detecting the currently running platform isn't as
+ // straightforward as you might hope.
+ // See: http://mono.wikia.com/wiki/Detecting_the_execution_platform
+ // and https://msdn.microsoft.com/en-us/library/3a8hyw88(v=vs.110).aspx
+ const PlatformID PlatformIDMonoUnix = (PlatformID)128;
+
+ switch (Environment.OSVersion.Platform)
+ {
+ case PlatformID.Win32NT:
+ case PlatformID.Win32S:
+ case PlatformID.Win32Windows:
+ case PlatformID.WinCE:
+ fileName += ".exe";
+ break;
+
+ case PlatformID.MacOSX:
+ case PlatformID.Unix:
+ case PlatformIDMonoUnix:
+ break;
+
+ // Don't handle the Xbox case. Let default handle it.
+ // case PlatformID.Xbox:
+ // break;
+
+ default:
+ throw new WebDriverException("Unsupported platform: " + Environment.OSVersion.Platform);
+ }
+
+ return fileName;
+ }
}
diff --git a/dotnet/src/webdriver/Chromium/ChromiumMobileEmulationDeviceSettings.cs b/dotnet/src/webdriver/Chromium/ChromiumMobileEmulationDeviceSettings.cs
index 6ee6b182cde9e..b2f1780fca573 100644
--- a/dotnet/src/webdriver/Chromium/ChromiumMobileEmulationDeviceSettings.cs
+++ b/dotnet/src/webdriver/Chromium/ChromiumMobileEmulationDeviceSettings.cs
@@ -17,59 +17,58 @@
// under the License.
//
-namespace OpenQA.Selenium.Chromium
+namespace OpenQA.Selenium.Chromium;
+
+///
+/// Represents the type-safe options for setting settings for emulating a
+/// mobile device in the Chromium browser.
+///
+public class ChromiumMobileEmulationDeviceSettings
{
///
- /// Represents the type-safe options for setting settings for emulating a
- /// mobile device in the Chromium browser.
+ /// Initializes a new instance of the class.
///
- public class ChromiumMobileEmulationDeviceSettings
+ public ChromiumMobileEmulationDeviceSettings()
{
- ///
- /// Initializes a new instance of the class.
- ///
- public ChromiumMobileEmulationDeviceSettings()
- {
- }
+ }
- ///
- /// Initializes a new instance of the class.
- ///
- /// The user agent string to be used by the browser when emulating
- /// a mobile device.
- public ChromiumMobileEmulationDeviceSettings(string? userAgent)
- {
- this.UserAgent = userAgent;
- }
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The user agent string to be used by the browser when emulating
+ /// a mobile device.
+ public ChromiumMobileEmulationDeviceSettings(string? userAgent)
+ {
+ this.UserAgent = userAgent;
+ }
- ///
- /// Gets or sets the user agent string to be used by the browser when emulating
- /// a mobile device.
- ///
- public string? UserAgent { get; set; }
+ ///
+ /// Gets or sets the user agent string to be used by the browser when emulating
+ /// a mobile device.
+ ///
+ public string? UserAgent { get; set; }
- ///
- /// Gets or sets the width in pixels to be used by the browser when emulating
- /// a mobile device.
- ///
- public long Width { get; set; }
+ ///
+ /// Gets or sets the width in pixels to be used by the browser when emulating
+ /// a mobile device.
+ ///
+ public long Width { get; set; }
- ///
- /// Gets or sets the height in pixels to be used by the browser when emulating
- /// a mobile device.
- ///
- public long Height { get; set; }
+ ///
+ /// Gets or sets the height in pixels to be used by the browser when emulating
+ /// a mobile device.
+ ///
+ public long Height { get; set; }
- ///
- /// Gets or sets the pixel ratio to be used by the browser when emulating
- /// a mobile device.
- ///
- public double PixelRatio { get; set; }
+ ///
+ /// Gets or sets the pixel ratio to be used by the browser when emulating
+ /// a mobile device.
+ ///
+ public double PixelRatio { get; set; }
- ///
- /// Gets or sets a value indicating whether touch events should be enabled by
- /// the browser when emulating a mobile device. Defaults to .
- ///
- public bool EnableTouchEvents { get; set; } = true;
- }
+ ///
+ /// Gets or sets a value indicating whether touch events should be enabled by
+ /// the browser when emulating a mobile device. Defaults to .
+ ///
+ public bool EnableTouchEvents { get; set; } = true;
}
diff --git a/dotnet/src/webdriver/Chromium/ChromiumNetworkConditions.cs b/dotnet/src/webdriver/Chromium/ChromiumNetworkConditions.cs
index 78a69b7516aee..ba118635732e0 100644
--- a/dotnet/src/webdriver/Chromium/ChromiumNetworkConditions.cs
+++ b/dotnet/src/webdriver/Chromium/ChromiumNetworkConditions.cs
@@ -21,114 +21,113 @@
using System.Collections.Generic;
using System.Text.Json.Serialization;
-namespace OpenQA.Selenium.Chromium
+namespace OpenQA.Selenium.Chromium;
+
+///
+/// Provides manipulation of getting and setting network conditions from Chromium.
+///
+public class ChromiumNetworkConditions
{
+ private long downloadThroughput = 0;
+ private long uploadThroughput = 0;
+
///
- /// Provides manipulation of getting and setting network conditions from Chromium.
+ /// Gets or sets a value indicating whether the network is offline. Defaults to .
///
- public class ChromiumNetworkConditions
- {
- private long downloadThroughput = 0;
- private long uploadThroughput = 0;
-
- ///
- /// Gets or sets a value indicating whether the network is offline. Defaults to .
- ///
- [JsonPropertyName("offline")]
- public bool IsOffline { get; set; }
-
- ///
- /// Gets or sets the simulated latency of the connection. Typically given in milliseconds.
- ///
- [JsonIgnore]
- public TimeSpan Latency { get; set; } = TimeSpan.Zero;
-
- ///
- /// Gets or sets the throughput of the network connection in bytes/second for downloading.
- ///
- [JsonPropertyName("download_throughput")]
- public long DownloadThroughput
- {
- get => this.downloadThroughput;
- set
- {
- if (value < 0)
- {
- throw new WebDriverException("Download throughput cannot be negative.");
- }
+ [JsonPropertyName("offline")]
+ public bool IsOffline { get; set; }
- this.downloadThroughput = value;
- }
- }
+ ///
+ /// Gets or sets the simulated latency of the connection. Typically given in milliseconds.
+ ///
+ [JsonIgnore]
+ public TimeSpan Latency { get; set; } = TimeSpan.Zero;
- ///
- /// Gets or sets the throughput of the network connection in bytes/second for uploading.
- ///
- [JsonPropertyName("upload_throughput")]
- public long UploadThroughput
+ ///
+ /// Gets or sets the throughput of the network connection in bytes/second for downloading.
+ ///
+ [JsonPropertyName("download_throughput")]
+ public long DownloadThroughput
+ {
+ get => this.downloadThroughput;
+ set
{
- get => this.uploadThroughput;
- set
+ if (value < 0)
{
- if (value < 0)
- {
- throw new WebDriverException("Upload throughput cannot be negative.");
- }
-
- this.uploadThroughput = value;
+ throw new WebDriverException("Download throughput cannot be negative.");
}
+
+ this.downloadThroughput = value;
}
+ }
- [JsonPropertyName("latency")]
- [JsonInclude]
- [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
- internal long? SerializableLatency => Convert.ToInt64(this.Latency.TotalMilliseconds);
-
- ///
- /// Creates a ChromiumNetworkConditions object from a dictionary of key-value pairs.
- ///
- /// The dictionary to use to create the object.
- /// The ChromiumNetworkConditions object created from the dictionary.
- public static ChromiumNetworkConditions FromDictionary(Dictionary dictionary)
+ ///
+ /// Gets or sets the throughput of the network connection in bytes/second for uploading.
+ ///
+ [JsonPropertyName("upload_throughput")]
+ public long UploadThroughput
+ {
+ get => this.uploadThroughput;
+ set
{
- ChromiumNetworkConditions conditions = new ChromiumNetworkConditions();
- if (dictionary.TryGetValue("offline", out object? offline))
+ if (value < 0)
{
- conditions.IsOffline = (bool)offline!;
+ throw new WebDriverException("Upload throughput cannot be negative.");
}
- if (dictionary.TryGetValue("latency", out object? latency))
- {
- conditions.Latency = TimeSpan.FromMilliseconds(Convert.ToDouble(latency));
- }
+ this.uploadThroughput = value;
+ }
+ }
- if (dictionary.TryGetValue("upload_throughput", out object? uploadThroughput))
- {
- conditions.UploadThroughput = (long)uploadThroughput!;
- }
+ [JsonPropertyName("latency")]
+ [JsonInclude]
+ [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+ internal long? SerializableLatency => Convert.ToInt64(this.Latency.TotalMilliseconds);
- if (dictionary.TryGetValue("download_throughput", out object? downloadThroughput))
- {
- conditions.DownloadThroughput = (long)downloadThroughput!;
- }
+ ///
+ /// Creates a ChromiumNetworkConditions object from a dictionary of key-value pairs.
+ ///
+ /// The dictionary to use to create the object.
+ /// The ChromiumNetworkConditions object created from the dictionary.
+ public static ChromiumNetworkConditions FromDictionary(Dictionary dictionary)
+ {
+ ChromiumNetworkConditions conditions = new ChromiumNetworkConditions();
+ if (dictionary.TryGetValue("offline", out object? offline))
+ {
+ conditions.IsOffline = (bool)offline!;
+ }
- return conditions;
+ if (dictionary.TryGetValue("latency", out object? latency))
+ {
+ conditions.Latency = TimeSpan.FromMilliseconds(Convert.ToDouble(latency));
}
- ///
- /// Sets the upload and download throughput properties to the same value.
- ///
- /// The throughput of the network connection in bytes/second for both upload and download.
- /// If is negative.
- public void SetBidirectionalThroughput(long throughput)
+ if (dictionary.TryGetValue("upload_throughput", out object? uploadThroughput))
{
- if (throughput < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(throughput), "Throughput values cannot be negative.");
- }
+ conditions.UploadThroughput = (long)uploadThroughput!;
+ }
- this.uploadThroughput = throughput;
- this.downloadThroughput = throughput;
+ if (dictionary.TryGetValue("download_throughput", out object? downloadThroughput))
+ {
+ conditions.DownloadThroughput = (long)downloadThroughput!;
}
+
+ return conditions;
+ }
+
+ ///
+ /// Sets the upload and download throughput properties to the same value.
+ ///
+ /// The throughput of the network connection in bytes/second for both upload and download.
+ /// If is negative.
+ public void SetBidirectionalThroughput(long throughput)
+ {
+ if (throughput < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(throughput), "Throughput values cannot be negative.");
+ }
+
+ this.uploadThroughput = throughput;
+ this.downloadThroughput = throughput;
}
}
diff --git a/dotnet/src/webdriver/Chromium/ChromiumOptions.cs b/dotnet/src/webdriver/Chromium/ChromiumOptions.cs
index eb7805504eda8..6ad454ac77a12 100644
--- a/dotnet/src/webdriver/Chromium/ChromiumOptions.cs
+++ b/dotnet/src/webdriver/Chromium/ChromiumOptions.cs
@@ -22,647 +22,646 @@
using System.Collections.ObjectModel;
using System.IO;
-namespace OpenQA.Selenium.Chromium
+namespace OpenQA.Selenium.Chromium;
+
+///
+/// Abstract class to manage options specific to Chromium-based browsers.
+///
+public abstract class ChromiumOptions : DriverOptions
{
+ private const string ArgumentsChromeOption = "args";
+ private const string BinaryChromeOption = "binary";
+ private const string ExtensionsChromeOption = "extensions";
+ private const string LocalStateChromeOption = "localState";
+ private const string PreferencesChromeOption = "prefs";
+ private const string DetachChromeOption = "detach";
+ private const string DebuggerAddressChromeOption = "debuggerAddress";
+ private const string ExcludeSwitchesChromeOption = "excludeSwitches";
+ private const string MinidumpPathChromeOption = "minidumpPath";
+ private const string MobileEmulationChromeOption = "mobileEmulation";
+ private const string PerformanceLoggingPreferencesChromeOption = "perfLoggingPrefs";
+ private const string WindowTypesChromeOption = "windowTypes";
+ private const string UseSpecCompliantProtocolOption = "w3c";
+ private bool useSpecCompliantProtocol = true;
+ private readonly List arguments = new List();
+ private readonly List extensionFiles = new List();
+ private readonly List encodedExtensions = new List();
+ private readonly List excludedSwitches = new List();
+ private readonly List windowTypes = new List();
+ private readonly Dictionary additionalChromeOptions = new Dictionary();
+ private Dictionary? userProfilePreferences;
+ private Dictionary? localStatePreferences;
+
+ private string? mobileEmulationDeviceName;
+ private ChromiumMobileEmulationDeviceSettings? mobileEmulationDeviceSettings;
+
///
- /// Abstract class to manage options specific to Chromium-based browsers.
+ /// Initializes a new instance of the class.
///
- public abstract class ChromiumOptions : DriverOptions
+ public ChromiumOptions() : base()
{
- private const string ArgumentsChromeOption = "args";
- private const string BinaryChromeOption = "binary";
- private const string ExtensionsChromeOption = "extensions";
- private const string LocalStateChromeOption = "localState";
- private const string PreferencesChromeOption = "prefs";
- private const string DetachChromeOption = "detach";
- private const string DebuggerAddressChromeOption = "debuggerAddress";
- private const string ExcludeSwitchesChromeOption = "excludeSwitches";
- private const string MinidumpPathChromeOption = "minidumpPath";
- private const string MobileEmulationChromeOption = "mobileEmulation";
- private const string PerformanceLoggingPreferencesChromeOption = "perfLoggingPrefs";
- private const string WindowTypesChromeOption = "windowTypes";
- private const string UseSpecCompliantProtocolOption = "w3c";
- private bool useSpecCompliantProtocol = true;
- private readonly List arguments = new List();
- private readonly List extensionFiles = new List();
- private readonly List encodedExtensions = new List();
- private readonly List excludedSwitches = new List();
- private readonly List windowTypes = new List();
- private readonly Dictionary additionalChromeOptions = new Dictionary();
- private Dictionary? userProfilePreferences;
- private Dictionary? localStatePreferences;
-
- private string? mobileEmulationDeviceName;
- private ChromiumMobileEmulationDeviceSettings? mobileEmulationDeviceSettings;
-
- ///
- /// Initializes a new instance of the class.
- ///
- public ChromiumOptions() : base()
- {
- this.AddKnownCapabilityName(this.CapabilityName, "current ChromiumOptions class instance");
- this.AddKnownCapabilityName(CapabilityType.LoggingPreferences, "SetLoggingPreference method");
- this.AddKnownCapabilityName(this.LoggingPreferencesChromeOption, "SetLoggingPreference method");
- this.AddKnownCapabilityName(ChromiumOptions.ArgumentsChromeOption, "AddArguments method");
- this.AddKnownCapabilityName(ChromiumOptions.BinaryChromeOption, "BinaryLocation property");
- this.AddKnownCapabilityName(ChromiumOptions.ExtensionsChromeOption, "AddExtensions method");
- this.AddKnownCapabilityName(ChromiumOptions.LocalStateChromeOption, "AddLocalStatePreference method");
- this.AddKnownCapabilityName(ChromiumOptions.PreferencesChromeOption, "AddUserProfilePreference method");
- this.AddKnownCapabilityName(ChromiumOptions.DetachChromeOption, "LeaveBrowserRunning property");
- this.AddKnownCapabilityName(ChromiumOptions.DebuggerAddressChromeOption, "DebuggerAddress property");
- this.AddKnownCapabilityName(ChromiumOptions.ExcludeSwitchesChromeOption, "AddExcludedArgument property");
- this.AddKnownCapabilityName(ChromiumOptions.MinidumpPathChromeOption, "MinidumpPath property");
- this.AddKnownCapabilityName(ChromiumOptions.MobileEmulationChromeOption, "EnableMobileEmulation method");
- this.AddKnownCapabilityName(ChromiumOptions.PerformanceLoggingPreferencesChromeOption, "PerformanceLoggingPreferences property");
- this.AddKnownCapabilityName(ChromiumOptions.WindowTypesChromeOption, "AddWindowTypes method");
- this.AddKnownCapabilityName(ChromiumOptions.UseSpecCompliantProtocolOption, "UseSpecCompliantProtocol property");
- }
-
- ///
- /// Gets the vendor prefix to apply to Chromium-specific capability names.
- ///
- protected abstract string VendorPrefix { get; }
-
- private string LoggingPreferencesChromeOption => this.VendorPrefix + ":loggingPrefs";
-
- ///
- /// Gets the name of the capability used to store Chromium options in
- /// an object.
- ///
- public abstract string CapabilityName { get; }
-
- ///
- /// Gets or sets the location of the Chromium browser's binary executable file.
- ///
- public override string? BinaryLocation { get; set; }
-
- ///
- /// Gets or sets a value indicating whether Chromium should be left running after the
- /// ChromeDriver instance is exited. Defaults to .
- ///
- public bool LeaveBrowserRunning { get; set; }
-
- ///
- /// Gets the list of arguments appended to the Chromium command line as a string array.
- ///
- public ReadOnlyCollection Arguments => this.arguments.AsReadOnly();
-
- ///
- /// Gets the list of extensions to be installed as an array of base64-encoded strings.
- ///
- public ReadOnlyCollection Extensions
- {
- get
- {
- List allExtensions = new List(this.encodedExtensions);
- foreach (string extensionFile in this.extensionFiles)
- {
- byte[] extensionByteArray = File.ReadAllBytes(extensionFile);
- string encodedExtension = Convert.ToBase64String(extensionByteArray);
- allExtensions.Add(encodedExtension);
- }
-
- return allExtensions.AsReadOnly();
- }
- }
+ this.AddKnownCapabilityName(this.CapabilityName, "current ChromiumOptions class instance");
+ this.AddKnownCapabilityName(CapabilityType.LoggingPreferences, "SetLoggingPreference method");
+ this.AddKnownCapabilityName(this.LoggingPreferencesChromeOption, "SetLoggingPreference method");
+ this.AddKnownCapabilityName(ChromiumOptions.ArgumentsChromeOption, "AddArguments method");
+ this.AddKnownCapabilityName(ChromiumOptions.BinaryChromeOption, "BinaryLocation property");
+ this.AddKnownCapabilityName(ChromiumOptions.ExtensionsChromeOption, "AddExtensions method");
+ this.AddKnownCapabilityName(ChromiumOptions.LocalStateChromeOption, "AddLocalStatePreference method");
+ this.AddKnownCapabilityName(ChromiumOptions.PreferencesChromeOption, "AddUserProfilePreference method");
+ this.AddKnownCapabilityName(ChromiumOptions.DetachChromeOption, "LeaveBrowserRunning property");
+ this.AddKnownCapabilityName(ChromiumOptions.DebuggerAddressChromeOption, "DebuggerAddress property");
+ this.AddKnownCapabilityName(ChromiumOptions.ExcludeSwitchesChromeOption, "AddExcludedArgument property");
+ this.AddKnownCapabilityName(ChromiumOptions.MinidumpPathChromeOption, "MinidumpPath property");
+ this.AddKnownCapabilityName(ChromiumOptions.MobileEmulationChromeOption, "EnableMobileEmulation method");
+ this.AddKnownCapabilityName(ChromiumOptions.PerformanceLoggingPreferencesChromeOption, "PerformanceLoggingPreferences property");
+ this.AddKnownCapabilityName(ChromiumOptions.WindowTypesChromeOption, "AddWindowTypes method");
+ this.AddKnownCapabilityName(ChromiumOptions.UseSpecCompliantProtocolOption, "UseSpecCompliantProtocol property");
+ }
- ///
- /// Gets or sets the address of a Chromium debugger server to connect to.
- /// Should be of the form "{hostname|IP address}:port".
- ///
- public string? DebuggerAddress { get; set; }
+ ///
+ /// Gets the vendor prefix to apply to Chromium-specific capability names.
+ ///
+ protected abstract string VendorPrefix { get; }
- ///
- /// Gets or sets the directory in which to store minidump files.
- ///
- public string? MinidumpPath { get; set; }
+ private string LoggingPreferencesChromeOption => this.VendorPrefix + ":loggingPrefs";
- ///
- /// Gets or sets the performance logging preferences for the driver.
- ///
- public ChromiumPerformanceLoggingPreferences? PerformanceLoggingPreferences { get; set; }
+ ///
+ /// Gets the name of the capability used to store Chromium options in
+ /// an object.
+ ///
+ public abstract string CapabilityName { get; }
+
+ ///
+ /// Gets or sets the location of the Chromium browser's binary executable file.
+ ///
+ public override string? BinaryLocation { get; set; }
- ///
- /// Gets or sets the options for automating Chromium applications on Android.
- ///
- public ChromiumAndroidOptions? AndroidOptions { get; set; }
+ ///
+ /// Gets or sets a value indicating whether Chromium should be left running after the
+ /// ChromeDriver instance is exited. Defaults to .
+ ///
+ public bool LeaveBrowserRunning { get; set; }
+
+ ///
+ /// Gets the list of arguments appended to the Chromium command line as a string array.
+ ///
+ public ReadOnlyCollection Arguments => this.arguments.AsReadOnly();
- ///
- /// Adds a single argument to the list of arguments to be appended to the browser executable command line.
- ///
- /// The argument to add.
- /// If is or .
- public void AddArgument(string argument)
+ ///
+ /// Gets the list of extensions to be installed as an array of base64-encoded strings.
+ ///
+ public ReadOnlyCollection Extensions
+ {
+ get
{
- if (string.IsNullOrEmpty(argument))
+ List allExtensions = new List(this.encodedExtensions);
+ foreach (string extensionFile in this.extensionFiles)
{
- throw new ArgumentException("argument must not be null or empty", nameof(argument));
+ byte[] extensionByteArray = File.ReadAllBytes(extensionFile);
+ string encodedExtension = Convert.ToBase64String(extensionByteArray);
+ allExtensions.Add(encodedExtension);
}
- this.AddArguments(argument);
+ return allExtensions.AsReadOnly();
}
+ }
+
+ ///
+ /// Gets or sets the address of a Chromium debugger server to connect to.
+ /// Should be of the form "{hostname|IP address}:port".
+ ///
+ public string? DebuggerAddress { get; set; }
+
+ ///
+ /// Gets or sets the directory in which to store minidump files.
+ ///
+ public string? MinidumpPath { get; set; }
+
+ ///
+ /// Gets or sets the performance logging preferences for the driver.
+ ///
+ public ChromiumPerformanceLoggingPreferences? PerformanceLoggingPreferences { get; set; }
+
+ ///
+ /// Gets or sets the options for automating Chromium applications on Android.
+ ///
+ public ChromiumAndroidOptions? AndroidOptions { get; set; }
- ///
- /// Adds arguments to be appended to the browser executable command line.
- ///
- /// An array of arguments to add.
- /// If is .
- public void AddArguments(params string[] argumentsToAdd)
+ ///
+ /// Adds a single argument to the list of arguments to be appended to the browser executable command line.
+ ///
+ /// The argument to add.
+ /// If is or .
+ public void AddArgument(string argument)
+ {
+ if (string.IsNullOrEmpty(argument))
{
- this.AddArguments((IEnumerable)argumentsToAdd);
+ throw new ArgumentException("argument must not be null or empty", nameof(argument));
}
- ///
- /// Adds arguments to be appended to the browser executable command line.
- ///
- /// An object of arguments to add.
- /// If is .
- public void AddArguments(IEnumerable argumentsToAdd)
- {
- if (argumentsToAdd == null)
- {
- throw new ArgumentNullException(nameof(argumentsToAdd), "argumentsToAdd must not be null");
- }
+ this.AddArguments(argument);
+ }
- this.arguments.AddRange(argumentsToAdd);
- }
+ ///
+ /// Adds arguments to be appended to the browser executable command line.
+ ///
+ /// An array of arguments to add.
+ /// If is .
+ public void AddArguments(params string[] argumentsToAdd)
+ {
+ this.AddArguments((IEnumerable)argumentsToAdd);
+ }
- ///
- /// Adds a single argument to be excluded from the list of arguments passed by default
- /// to the browser executable command line by chromedriver.exe.
- ///
- /// The argument to exclude.
- /// If