Skip to content

Instantly share code, notes, and snippets.

@jimevans
jimevans / EventResponder{T}.cs
Last active February 28, 2024 22:10
EventHandler Helper Class with Support for Async Events
namespace WebDriverBiDi.Client;
using System.Reflection;
/// <summary>
/// Delegate for asynchronously handling events.
/// </summary>
/// <typeparam name="T">The type of <see cref="EventArgs"/> object containing information about the event.</typeparam>
/// <param name="sender">The sender of the event. This argument is optional and may be <see langword="null"/>.</param>
/// <param name="eventArgs">The <see cref="EventArgs"/> object containing information about the event.</param>
// Assume driver and element are properly defined and assigned elsewhere.
PointerInputDevice mouse = new PointerInputDevice();
ActionBuilder builder = new ActionBuilder();
builder.AddActions(
mouse.CreatePointerMove(element, 0, 0, TimeSpan.FromMilliseconds(100),
mouse.CreatePointerDown(MouseButton.Left),
mouse.CreatePointerMove(element, 100, 100, TimeSpan.FromMilliseconds(100),
mouse.CreatePointerUp(MouseButton.Left)
);
((IActionExecutor)driver).PerformActions(builder.ToActionSequence());
@jimevans
jimevans / AddCustomCommand.cs
Created November 29, 2021 17:44
Add custom command
// N.B., this example is far more verbose than required to showcase
// the full statements required. Production code would not need to be
// this verbose. Execution of custom commands is usually accomplished
// by subclassing the base class and having custom methods to use
// the executor to call the custom commands.
// The name of the command should be unique among command names.
string commandName = "someArbitraryUniqueCommandName";
// HttpCommandInfo can use either Get, Post, or Delete commands. The
IWebDriver driver = new RemoteWebDriver(new Uri("http://localhost:4444"), new ChromeOptions());
ICustomDriverCommandExecutor customCommandDriver = driver as ICustomDriverCommandExecutor;
customCommandDriver.RegisterCustomDriverCommands(ChromeDriver.CustomCommandDefinitions);
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
networkConditions.IsOffline = true;
Dictionary<string, Object> parameters = new Dictionary<string, object>();
parameters.Add("network_conditions", networkConditions);
customCommandDriver.ExecuteCustomDriverCommand(ChromeDriver.SetNetworkConditionsCommand, parameters);
@jimevans
jimevans / NetworkInterception.cs
Last active May 31, 2024 07:49
Selenium C# network traffic logging example
public async Task LogNetworkRequests(IWebDriver driver)
{
INetwork interceptor = driver.Manage().Network;
interceptor.NetworkRequestSent += OnNetworkRequestSent;
interceptor.NetworkResponseReceived += OnNetworkResponseReceived;
await interceptor.StartMonitoring();
driver.Url = "http://the-internet.herokuapp.com/redirect";
await interceptor.StopMonitoring();
}
@jimevans
jimevans / DomMutation.cs
Created October 12, 2021 16:57
Selenium C# DOM Mutation example
List<DomMutationData> attributeValueChanges = new List<DomMutationData>();
DefaultWait<List<DomMutationData>> wait = new DefaultWait<List<DomMutationData>>(attributeValueChanges);
wait.Timeout = TimeSpan.FromSeconds(3);
IJavaScriptEngine monitor = new JavaScriptEngine(driver);
monitor.DomMutated += (sender, e) =>
{
attributeValueChanges.Add(e.AttributeData);
};
await monitor.StartEventMonitoring();
@jimevans
jimevans / Metrics.cs
Created October 11, 2021 18:04
Selenium C# Performance Metrics example
// File must contain the following using statements
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.DevTools;
// We must use a version-specific set of domains
using OpenQA.Selenium.DevTools.V94.Performance;
public async Task PerformanceMetricsExample()
{
@jimevans
jimevans / JavaScriptExceptions.cs
Created October 11, 2021 16:45
Selenium C# JavaScript exception listening example
List<string> exceptionMessages = new List<string>();
IJavaScriptEngine monitor = new JavaScriptEngine(driver);
monitor.JavaScriptExceptionThrown += (sender, e) =>
{
exceptionMessages.Add(e.Message);
};
await monitor.StartEventMonitoring();
driver.Navigate.GoToUrl("<your site url>");
@jimevans
jimevans / ConsoleLog.cs
Created October 11, 2021 16:33
Selenium C# JavaScript Console Log monitoring example
IJavaScriptEngine monitor = new JavaScriptEngine(driver);
List<string> consoleMessages = new List<string>();
monitor.JavaScriptConsoleApiCalled += (sender, e) =>
{
Console.WriteLine("Log: {0}", e.MessageContent);
};
await monitor.StartEventMonitoring();
@jimevans
jimevans / auth.cs
Created October 11, 2021 16:08
Selenium Authentication C# Example
NetworkAuthenticationHandler handler = new NetworkAuthenticationHandler()
{
UriMatcher = (d) => d.Host.Contains("your-domain.com"),
Credentials = new PasswordCredentials("admin", "password")
};
INetwork networkInterceptor = driver.Manage().Network;
networkInterceptor.AddAuthenticationHandler(handler);
await networkInterceptor.StartMonitoring();