How to use new method of Microsoft.Playwright.Transport.Connection class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Transport.Connection.new

Connection.cs

Source:Connection.cs Github

copy

Full Screen

...40namespace Microsoft.Playwright.Transport41{42 internal class Connection : IDisposable43 {44 private readonly ConcurrentDictionary<int, ConnectionCallback> _callbacks = new();45 private readonly Root _rootObject;46 private readonly TaskQueue _queue = new();47 private int _lastId;48 private string _reason = string.Empty;49 public Connection()50 {51 _rootObject = new(null, this, string.Empty);52 DefaultJsonSerializerOptions = JsonExtensions.GetNewDefaultSerializerOptions();53 DefaultJsonSerializerOptions.Converters.Add(new ChannelToGuidConverter(this));54 DefaultJsonSerializerOptions.Converters.Add(new ChannelOwnerToGuidConverter<JSHandle>(this));55 DefaultJsonSerializerOptions.Converters.Add(new ChannelOwnerToGuidConverter<ElementHandle>(this));56 DefaultJsonSerializerOptions.Converters.Add(new ChannelOwnerToGuidConverter<IChannelOwner>(this));57 // Workaround for https://github.com/dotnet/runtime/issues/4652258 DefaultJsonSerializerOptions.Converters.Add(new ChannelOwnerListToGuidListConverter<WritableStream>(this));59 }60 /// <inheritdoc cref="IDisposable.Dispose"/>61 ~Connection() => Dispose(false);62 internal event EventHandler<string> Close;63 public ConcurrentDictionary<string, IChannelOwner> Objects { get; } = new();64 internal AsyncLocal<List<ApiZone>> ApiZone { get; } = new();65 public bool IsClosed { get; private set; }66 internal bool IsRemote { get; set; }67 internal Func<object, Task> OnMessage { get; set; }68 internal JsonSerializerOptions DefaultJsonSerializerOptions { get; }69 public void Dispose()70 {71 Dispose(true);72 GC.SuppressFinalize(this);73 }74 internal Task<JsonElement?> SendMessageToServerAsync(75 string guid,76 string method,77 object args = null)78 => SendMessageToServerAsync<JsonElement?>(guid, method, args);79 internal Task<T> SendMessageToServerAsync<T>(80 string guid,81 string method,82 object args = null) => WrapApiCallAsync(() => InnerSendMessageToServerAsync<T>(guid, method, args));83 private async Task<T> InnerSendMessageToServerAsync<T>(84 string guid,85 string method,86 object args = null)87 {88 if (IsClosed)89 {90 throw new PlaywrightException($"Connection closed ({_reason})");91 }92 int id = Interlocked.Increment(ref _lastId);93 var tcs = new TaskCompletionSource<JsonElement?>(TaskCreationOptions.RunContinuationsAsynchronously);94 var callback = new ConnectionCallback95 {96 TaskCompletionSource = tcs,97 };98 _callbacks.TryAdd(id, callback);99 var sanitizedArgs = new Dictionary<string, object>();100 if (args != null)101 {102 if (args is IDictionary<string, object> dictionary && dictionary.Keys.Any(f => f != null))103 {104 foreach (var kv in dictionary)105 {106 if (kv.Value != null)107 {108 sanitizedArgs.Add(kv.Key, kv.Value);109 }110 }111 }112 else113 {114 foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(args))115 {116 object obj = propertyDescriptor.GetValue(args);117 if (obj != null)118 {119#pragma warning disable CA1845 // Use span-based 'string.Concat' and 'AsSpan' instead of 'Substring120 string name = propertyDescriptor.Name.Substring(0, 1).ToLower() + propertyDescriptor.Name.Substring(1);121#pragma warning restore CA2000 // Use span-based 'string.Concat' and 'AsSpan' instead of 'Substring122 sanitizedArgs.Add(name, obj);123 }124 }125 }126 }127 await _queue.EnqueueAsync(() =>128 {129 var message = new MessageRequest130 {131 Id = id,132 Guid = guid,133 Method = method,134 Params = sanitizedArgs,135 Metadata = ApiZone.Value[0],136 };137 TraceMessage("pw:channel:command", message);138 return OnMessage(message);139 }).ConfigureAwait(false);140 var result = await tcs.Task.ConfigureAwait(false);141 if (typeof(T) == typeof(JsonElement?))142 {143 return (T)(object)result?.Clone();144 }145 else if (result == null)146 {147 return default;148 }149 else if (typeof(ChannelBase).IsAssignableFrom(typeof(T)) || typeof(ChannelBase[]).IsAssignableFrom(typeof(T)))150 {151 var enumerate = result.Value.EnumerateObject();152 return enumerate.Any()153 ? enumerate.FirstOrDefault().Value.ToObject<T>(DefaultJsonSerializerOptions)154 : default;155 }156 else157 {158 return result.Value.ToObject<T>(DefaultJsonSerializerOptions);159 }160 }161 internal IChannelOwner GetObject(string guid)162 {163 Objects.TryGetValue(guid, out var result);164 return result;165 }166 internal void MarkAsRemote() => IsRemote = true;167 internal Task<PlaywrightImpl> InitializePlaywrightAsync()168 {169 return _rootObject.InitializeAsync();170 }171 internal void OnObjectCreated(string guid, IChannelOwner result)172 {173 Objects.TryAdd(guid, result);174 }175 internal void Dispatch(PlaywrightServerMessage message)176 {177 if (message.Id.HasValue)178 {179 TraceMessage("pw:channel:response", message);180 if (_callbacks.TryRemove(message.Id.Value, out var callback))181 {182 if (message.Error != null)183 {184 callback.TaskCompletionSource.TrySetException(CreateException(message.Error.Error));185 }186 else187 {188 callback.TaskCompletionSource.TrySetResult(message.Result);189 }190 }191 return;192 }193 TraceMessage("pw:channel:event", message);194 try195 {196 if (message.Method == "__create__")197 {198 var createObjectInfo = message.Params.Value.ToObject<CreateObjectInfo>(DefaultJsonSerializerOptions);199 CreateRemoteObject(message.Guid, createObjectInfo.Type, createObjectInfo.Guid, createObjectInfo.Initializer);200 return;201 }202 if (message.Method == "__dispose__")203 {204 Objects.TryGetValue(message.Guid, out var disableObject);205 disableObject?.DisposeOwner();206 return;207 }208 Objects.TryGetValue(message.Guid, out var obj);209 obj?.Channel?.OnMessage(message.Method, message.Params);210 }211 catch (Exception ex)212 {213 DoClose(ex);214 }215 }216 private void CreateRemoteObject(string parentGuid, ChannelOwnerType type, string guid, JsonElement? initializer)217 {218 IChannelOwner result = null;219 var parent = string.IsNullOrEmpty(parentGuid) ? _rootObject : Objects[parentGuid];220#pragma warning disable CA2000 // Dispose objects before losing scope221 switch (type)222 {223 case ChannelOwnerType.Artifact:224 result = new Artifact(parent, guid, initializer?.ToObject<ArtifactInitializer>(DefaultJsonSerializerOptions));225 break;226 case ChannelOwnerType.BindingCall:227 result = new BindingCall(parent, guid, initializer?.ToObject<BindingCallInitializer>(DefaultJsonSerializerOptions));228 break;229 case ChannelOwnerType.Playwright:230 result = new PlaywrightImpl(parent, guid, initializer?.ToObject<PlaywrightInitializer>(DefaultJsonSerializerOptions));231 break;232 case ChannelOwnerType.Browser:233 var browserInitializer = initializer?.ToObject<BrowserInitializer>(DefaultJsonSerializerOptions);234 result = new Browser(parent, guid, browserInitializer);235 break;236 case ChannelOwnerType.BrowserType:237 var browserTypeInitializer = initializer?.ToObject<BrowserTypeInitializer>(DefaultJsonSerializerOptions);238 result = new Core.BrowserType(parent, guid, browserTypeInitializer);239 break;240 case ChannelOwnerType.BrowserContext:241 var browserContextInitializer = initializer?.ToObject<BrowserContextInitializer>(DefaultJsonSerializerOptions);242 result = new BrowserContext(parent, guid, browserContextInitializer);243 break;244 case ChannelOwnerType.ConsoleMessage:245 result = new ConsoleMessage(parent, guid, initializer?.ToObject<ConsoleMessageInitializer>(DefaultJsonSerializerOptions));246 break;247 case ChannelOwnerType.Dialog:248 result = new Dialog(parent, guid, initializer?.ToObject<DialogInitializer>(DefaultJsonSerializerOptions));249 break;250 case ChannelOwnerType.ElementHandle:251 result = new ElementHandle(parent, guid, initializer?.ToObject<ElementHandleInitializer>(DefaultJsonSerializerOptions));252 break;253 case ChannelOwnerType.Frame:254 result = new Frame(parent, guid, initializer?.ToObject<FrameInitializer>(DefaultJsonSerializerOptions));255 break;256 case ChannelOwnerType.JSHandle:257 result = new JSHandle(parent, guid, initializer?.ToObject<JSHandleInitializer>(DefaultJsonSerializerOptions));258 break;259 case ChannelOwnerType.JsonPipe:260 result = new JsonPipe(parent, guid, initializer?.ToObject<JsonPipeInitializer>(DefaultJsonSerializerOptions));261 break;262 case ChannelOwnerType.LocalUtils:263 result = new LocalUtils(parent, guid, initializer);264 break;265 case ChannelOwnerType.Page:266 result = new Page(parent, guid, initializer?.ToObject<PageInitializer>(DefaultJsonSerializerOptions));267 break;268 case ChannelOwnerType.Request:269 result = new Request(parent, guid, initializer?.ToObject<RequestInitializer>(DefaultJsonSerializerOptions));270 break;271 case ChannelOwnerType.Response:272 result = new Response(parent, guid, initializer?.ToObject<ResponseInitializer>(DefaultJsonSerializerOptions));273 break;274 case ChannelOwnerType.Route:275 result = new Route(parent, guid, initializer?.ToObject<RouteInitializer>(DefaultJsonSerializerOptions));276 break;277 case ChannelOwnerType.Worker:278 result = new Worker(parent, guid, initializer?.ToObject<WorkerInitializer>(DefaultJsonSerializerOptions));279 break;280 case ChannelOwnerType.WebSocket:281 result = new WebSocket(parent, guid, initializer?.ToObject<WebSocketInitializer>(DefaultJsonSerializerOptions));282 break;283 case ChannelOwnerType.Selectors:284 result = new Selectors(parent, guid);285 break;286 case ChannelOwnerType.SocksSupport:287 result = new SocksSupport(parent, guid);288 break;289 case ChannelOwnerType.Stream:290 result = new Stream(parent, guid);291 break;292 case ChannelOwnerType.WritableStream:293 result = new WritableStream(parent, guid);294 break;295 case ChannelOwnerType.Tracing:296 result = new Tracing(parent, guid);297 break;298 default:299 TraceMessage("pw:dotnet", "Missing type " + type);300 break;301 }302#pragma warning restore CA2000303 Objects.TryAdd(guid, result);304 OnObjectCreated(guid, result);305 }306 private void DoClose(Exception ex)307 {308 TraceMessage("pw:dotnet", $"Connection Close: {ex.Message}\n{ex.StackTrace}");309 DoClose(ex.Message);310 }311 internal void DoClose(string reason)312 {313 _reason = string.IsNullOrEmpty(_reason) ? reason : _reason;314 if (!IsClosed)315 {316 foreach (var callback in _callbacks)317 {318 callback.Value.TaskCompletionSource.TrySetException(new PlaywrightException(reason));319 }320 Dispose();321 IsClosed = true;322 }323 }324 private Exception CreateException(PlaywrightServerError error)325 {326 if (string.IsNullOrEmpty(error.Message))327 {328 return new PlaywrightException(error.Value);329 }330 if (error.Name == "TimeoutError")331 {332 return new TimeoutException(error.Message);333 }334 return new PlaywrightException(error.Message);335 }336 private void Dispose(bool disposing)337 {338 if (!disposing)339 {340 return;341 }342 _queue.Dispose();343 Close.Invoke(this, "Connection disposed");344 }345 [Conditional("DEBUG")]346 internal void TraceMessage(string logLevel, object message)347 {348 string actualLogLevel = Environment.GetEnvironmentVariable("DEBUG");349 if (!string.IsNullOrEmpty(actualLogLevel))350 {351 if (!actualLogLevel.Contains(logLevel))352 {353 return;354 }355 if (!(message is string))356 {357 message = JsonSerializer.Serialize(message, DefaultJsonSerializerOptions);358 }359 string line = $"{logLevel}: {message}";360 Trace.WriteLine(line);361 Console.Error.WriteLine(line);362 }363 }364 internal async Task<T> WrapApiCallAsync<T>(Func<Task<T>> action, bool isInternal = false)365 {366 EnsureApiZoneExists();367 if (ApiZone.Value[0] != null)368 {369 return await action().ConfigureAwait(false);370 }371 var st = new StackTrace(true);372 var stack = new List<object>();373 var lastInternalApiName = string.Empty;374 var apiName = string.Empty;375 for (int i = 0; i < st.FrameCount; ++i)376 {377 var sf = st.GetFrame(i);378 string fileName = sf.GetFileName();379 string cSharpNamespace = sf.GetMethod().ReflectedType?.Namespace;380 bool playwrightInternal = cSharpNamespace != null &&381 (cSharpNamespace == "Microsoft.Playwright" ||382 cSharpNamespace.StartsWith("Microsoft.Playwright.Core", StringComparison.InvariantCultureIgnoreCase) ||383 cSharpNamespace.StartsWith("Microsoft.Playwright.Transport", StringComparison.InvariantCultureIgnoreCase) ||384 cSharpNamespace.StartsWith("Microsoft.Playwright.Helpers", StringComparison.InvariantCultureIgnoreCase));385 if (string.IsNullOrEmpty(fileName) && !playwrightInternal)386 {387 continue;388 }389 if (!playwrightInternal)390 {391 stack.Add(new { file = fileName, line = sf.GetFileLineNumber(), column = sf.GetFileColumnNumber() });392 }393 string methodName = $"{sf?.GetMethod()?.DeclaringType?.Name}.{sf?.GetMethod()?.Name}";394 if (methodName.Contains("WrapApiBoundaryAsync"))395 {396 break;397 }398 if (methodName.StartsWith("<", StringComparison.InvariantCultureIgnoreCase))399 {400 continue;401 }402 if (playwrightInternal)403 {404 lastInternalApiName = methodName;405 }406 else if (!string.IsNullOrEmpty(lastInternalApiName))407 {408 apiName = lastInternalApiName;409 lastInternalApiName = string.Empty;410 }411 }412 if (string.IsNullOrEmpty(apiName))413 {414 apiName = lastInternalApiName;415 }416 try417 {418 if (!string.IsNullOrEmpty(apiName))419 {420 ApiZone.Value[0] = new() { ApiName = apiName, Stack = stack, IsInternal = isInternal };421 }422 return await action().ConfigureAwait(false);423 }424 finally425 {426 ApiZone.Value[0] = null;427 }428 }429 internal async Task WrapApiBoundaryAsync(Func<Task> action)430 {431 EnsureApiZoneExists();432 try433 {434 ApiZone.Value.Insert(0, null);435 await action().ConfigureAwait(false);436 }437 finally438 {439 ApiZone.Value.RemoveAt(0);440 }441 }442 private void EnsureApiZoneExists()443 {444 if (ApiZone.Value == null)445 {446 ApiZone.Value = new() { null };447 }448 }449 }450}...

Full Screen

Full Screen

BrowserType.cs

Source:BrowserType.cs Github

copy

Full Screen

...38 private readonly BrowserTypeChannel _channel;39 internal BrowserType(IChannelOwner parent, string guid, BrowserTypeInitializer initializer) : base(parent, guid)40 {41 _initializer = initializer;42 _channel = new(guid, parent.Connection, this);43 }44 ChannelBase IChannelOwner.Channel => _channel;45 IChannel<BrowserType> IChannelOwner<BrowserType>.Channel => _channel;46 internal PlaywrightImpl Playwright { get; set; }47 public string ExecutablePath => _initializer.ExecutablePath;48 public string Name => _initializer.Name;49 public async Task<IBrowser> LaunchAsync(BrowserTypeLaunchOptions options = default)50 {51 options ??= new BrowserTypeLaunchOptions();52 Browser browser = (await _channel.LaunchAsync(53 headless: options.Headless,54 channel: options.Channel,55 executablePath: options.ExecutablePath,56 passedArguments: options.Args,57 proxy: options.Proxy,58 downloadsPath: options.DownloadsPath,59 tracesDir: options.TracesDir,60 chromiumSandbox: options.ChromiumSandbox,61 firefoxUserPrefs: options.FirefoxUserPrefs,62 handleSIGINT: options.HandleSIGINT,63 handleSIGTERM: options.HandleSIGTERM,64 handleSIGHUP: options.HandleSIGHUP,65 timeout: options.Timeout,66 env: options.Env,67 devtools: options.Devtools,68 slowMo: options.SlowMo,69 ignoreDefaultArgs: options.IgnoreDefaultArgs,70 ignoreAllDefaultArgs: options.IgnoreAllDefaultArgs).ConfigureAwait(false)).Object;71 browser.LocalUtils = Playwright.Utils;72 return browser;73 }74 public async Task<IBrowserContext> LaunchPersistentContextAsync(string userDataDir, BrowserTypeLaunchPersistentContextOptions options = default)75 {76 options ??= new BrowserTypeLaunchPersistentContextOptions();77 var context = (await _channel.LaunchPersistentContextAsync(78 userDataDir,79 headless: options.Headless,80 channel: options.Channel,81 executablePath: options.ExecutablePath,82 args: options.Args,83 proxy: options.Proxy,84 downloadsPath: options.DownloadsPath,85 tracesDir: options.TracesDir,86 chromiumSandbox: options.ChromiumSandbox,87 handleSIGINT: options.HandleSIGINT,88 handleSIGTERM: options.HandleSIGTERM,89 handleSIGHUP: options.HandleSIGHUP,90 timeout: options.Timeout,91 env: options.Env,92 devtools: options.Devtools,93 slowMo: options.SlowMo,94 acceptDownloads: options.AcceptDownloads,95 ignoreHTTPSErrors: options.IgnoreHTTPSErrors,96 bypassCSP: options.BypassCSP,97 viewportSize: options.ViewportSize,98 screenSize: options.ScreenSize,99 userAgent: options.UserAgent,100 deviceScaleFactor: options.DeviceScaleFactor,101 isMobile: options.IsMobile,102 hasTouch: options.HasTouch,103 javaScriptEnabled: options.JavaScriptEnabled,104 timezoneId: options.TimezoneId,105 geolocation: options.Geolocation,106 locale: options.Locale,107 permissions: options.Permissions,108 extraHTTPHeaders: options.ExtraHTTPHeaders,109 offline: options.Offline,110 httpCredentials: options.HttpCredentials,111 colorScheme: options.ColorScheme,112 reducedMotion: options.ReducedMotion,113 recordHarPath: options.RecordHarPath,114 recordHarOmitContent: options.RecordHarOmitContent,115 recordVideo: Browser.GetVideoArgs(options.RecordVideoDir, options.RecordVideoSize),116 ignoreDefaultArgs: options.IgnoreDefaultArgs,117 ignoreAllDefaultArgs: options.IgnoreAllDefaultArgs,118 baseUrl: options.BaseURL,119 forcedColors: options.ForcedColors).ConfigureAwait(false)).Object;120 // TODO: unite with a single browser context options type which is derived from channels121 context.Options = new()122 {123 RecordVideoDir = options.RecordVideoDir,124 RecordVideoSize = options.RecordVideoSize,125 RecordHarPath = options.RecordHarPath,126 RecordHarOmitContent = options.RecordHarOmitContent,127 };128 ((Core.Tracing)context.Tracing).LocalUtils = Playwright.Utils;129 return context;130 }131 public async Task<IBrowser> ConnectAsync(string wsEndpoint, BrowserTypeConnectOptions options = null)132 {133 options ??= new BrowserTypeConnectOptions();134 var headers = new List<KeyValuePair<string, string>>(options.Headers ?? new Dictionary<string, string>())135 {136 new KeyValuePair<string, string>("x-playwright-browser", Name),137 }.ToDictionary(pair => pair.Key, pair => pair.Value);138 JsonPipe pipe = (await _channel.ConnectAsync(wsEndpoint: wsEndpoint, headers: headers, slowMo: options.SlowMo, timeout: options.Timeout).ConfigureAwait(false)).Object;139 void ClosePipe()140 {141 pipe.CloseAsync().IgnoreException();142 }143#pragma warning disable CA2000 // Dispose objects before losing scope144 var connection = new Connection();145#pragma warning restore CA2000146 connection.MarkAsRemote();147 connection.Close += (_, _) => ClosePipe();148 string closeError = null;149 Browser browser = null;150 void OnPipeClosed()151 {152 // Emulate all pages, contexts and the browser closing upon disconnect.153 foreach (BrowserContext context in browser?.BrowserContextsList.ToArray() ?? Array.Empty<BrowserContext>())154 {155 foreach (Page page in context.PagesList.ToArray())156 {157 page.OnClose();158 }159 context.OnClose();160 }161 browser?.DidClose();162 connection.DoClose(closeError != null ? closeError : DriverMessages.BrowserClosedExceptionMessage);163 }164 pipe.Closed += (_, _) => OnPipeClosed();165 connection.OnMessage = async (object message) =>166 {167 try168 {169 await pipe.SendAsync(message).ConfigureAwait(false);170 }171 catch (Exception e) when (DriverMessages.IsSafeCloseError(e))172 {173 // swallow exception174 }175 catch176 {177 OnPipeClosed();178 }179 };180 pipe.Message += (_, message) =>181 {182 try183 {184 connection.Dispatch(message);185 }186 catch (Exception ex)187 {188 closeError = ex.ToString();189 _channel.Connection.TraceMessage("pw:dotnet", $"Dispatching error: {ex.Message}\n{ex.StackTrace}");190 ClosePipe();191 }192 };193 async Task<IBrowser> CreateBrowserAsync()194 {195 var playwright = await connection.InitializePlaywrightAsync().ConfigureAwait(false);196 playwright.Connection = connection;197 if (playwright.PreLaunchedBrowser == null)198 {199 ClosePipe();200 throw new ArgumentException("Malformed endpoint. Did you use launchServer method?");201 }202 browser = playwright.PreLaunchedBrowser;203 browser.ShouldCloseConnectionOnClose = true;204 browser.Disconnected += (_, _) => ClosePipe();205 browser.LocalUtils = Playwright.Utils;206 return playwright.PreLaunchedBrowser;207 }208 var task = CreateBrowserAsync();209 var timeout = options?.Timeout != null ? (int)options.Timeout : 30_000;210 return await task.WithTimeout(timeout, _ => throw new TimeoutException($"BrowserType.ConnectAsync: Timeout {options.Timeout}ms exceeded")).ConfigureAwait(false);211 }212 public async Task<IBrowser> ConnectOverCDPAsync(string endpointURL, BrowserTypeConnectOverCDPOptions options = null)213 {214 if (Name != "chromium")215 {216 throw new ArgumentException("Connecting over CDP is only supported in Chromium.");217 }218 options ??= new BrowserTypeConnectOverCDPOptions();219 JsonElement result = await _channel.ConnectOverCDPAsync(endpointURL, headers: options.Headers, slowMo: options.SlowMo, timeout: options.Timeout).ConfigureAwait(false);220 Browser browser = result.GetProperty("browser").ToObject<Browser>(_channel.Connection.DefaultJsonSerializerOptions);221 if (result.TryGetProperty("defaultContext", out JsonElement defaultContextValue))222 {223 browser.BrowserContextsList.Add(defaultContextValue.ToObject<BrowserContext>(_channel.Connection.DefaultJsonSerializerOptions));224 }225 browser.LocalUtils = Playwright.Utils;226 return browser;227 }228 }229}...

Full Screen

Full Screen

PlaywrightImpl.cs

Source:PlaywrightImpl.cs Github

copy

Full Screen

...38 public const int DefaultTimeout = 30_000;39 private readonly PlaywrightInitializer _initializer;40 private readonly PlaywrightChannel _channel;41 private readonly Connection _connection;42 private readonly Dictionary<string, BrowserNewContextOptions> _devices = new(StringComparer.InvariantCultureIgnoreCase);43 internal PlaywrightImpl(IChannelOwner parent, string guid, PlaywrightInitializer initializer)44 : base(parent, guid)45 {46 _connection = parent.Connection;47 _initializer = initializer;48 _channel = new(guid, parent.Connection, this);49 foreach (var entry in initializer.DeviceDescriptors)50 {51 _devices[entry.Name] = entry.Descriptor;52 }53 Utils = initializer.Utils;54 _initializer.Chromium.Playwright = this;55 _initializer.Firefox.Playwright = this;56 _initializer.Webkit.Playwright = this;57 }58 ~PlaywrightImpl() => Dispose(false);59 Connection IChannelOwner.Connection => _connection;60 ChannelBase IChannelOwner.Channel => _channel;61 IChannel<PlaywrightImpl> IChannelOwner<PlaywrightImpl>.Channel => _channel;62 public IBrowserType Chromium { get => _initializer.Chromium; set => throw new NotSupportedException(); }63 public IBrowserType Firefox { get => _initializer.Firefox; set => throw new NotSupportedException(); }64 public IBrowserType Webkit { get => _initializer.Webkit; set => throw new NotSupportedException(); }65 public ISelectors Selectors => _initializer.Selectors;66 public IReadOnlyDictionary<string, BrowserNewContextOptions> Devices => _devices;67 internal Connection Connection { get; set; }68 internal Browser PreLaunchedBrowser => _initializer.PreLaunchedBrowser;69 internal LocalUtils Utils { get; set; }70 /// <summary>71 /// Gets a <see cref="IBrowserType"/>.72 /// </summary>73 /// <param name="browserType"><see cref="IBrowserType"/> name. You can get the names from <see cref="global::Microsoft.Playwright.BrowserType"/>.74 /// e.g.: <see cref="global::Microsoft.Playwright.BrowserType.Chromium"/>,75 /// <see cref="global::Microsoft.Playwright.BrowserType.Firefox"/> or <see cref="global::Microsoft.Playwright.BrowserType.Webkit"/>.76 /// </param>77 public IBrowserType this[string browserType]78 => browserType?.ToLower() switch...

Full Screen

Full Screen

Artifact.cs

Source:Artifact.cs Github

copy

Full Screen

...36 private readonly ArtifactChannel _channel;37 internal Artifact(IChannelOwner parent, string guid, ArtifactInitializer initializer) : base(parent, guid)38 {39 _connection = parent.Connection;40 _channel = new(guid, parent.Connection, this);41 AbsolutePath = initializer.AbsolutePath;42 }43 Connection IChannelOwner.Connection => _connection;44 ChannelBase IChannelOwner.Channel => _channel;45 IChannel<Artifact> IChannelOwner<Artifact>.Channel => _channel;46 internal string AbsolutePath { get; }47 public async Task<string> PathAfterFinishedAsync()48 {49 if (_connection.IsRemote)50 {51 throw new PlaywrightException("Path is not available when connecting remotely. Use SaveAsAsync() to save a local copy.");52 }53 return await _channel.PathAfterFinishedAsync().ConfigureAwait(false);54 }55 public async Task SaveAsAsync(string path)56 {57 if (!_connection.IsRemote)58 {59 await _channel.SaveAsAsync(path).ConfigureAwait(false);60 return;61 }62 System.IO.Directory.CreateDirectory(Path.GetDirectoryName(path));63 var stream = await _channel.SaveAsStreamAsync().ConfigureAwait(false);64 await using (stream.ConfigureAwait(false))65 {66 using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))67 {68 await stream.StreamImpl.CopyToAsync(fileStream).ConfigureAwait(false);69 }70 }71 }72 public async Task<System.IO.Stream> CreateReadStreamAsync()73 {74 var stream = await _channel.StreamAsync().ConfigureAwait(false);75 return stream.StreamImpl;76 }77 internal Task CancelAsync() => _channel.CancelAsync();78 internal Task<string> FailureAsync() => _channel.FailureAsync();79 internal Task DeleteAsync() => _channel.DeleteAsync();80 }...

Full Screen

Full Screen

ChannelHelpers.cs

Source:ChannelHelpers.cs Github

copy

Full Screen

...23 if (optional)24 {25 return null;26 }27 throw new ArgumentNullException($"Element {name} was expected to not be optional, yet was not present in the data.");28 }29 internal static T? GetObject<T>(this JsonElement? element, string name, Connection connection)30 where T : ChannelOwnerBase, IChannelOwner<T>31 {32 if (!element.HasValue)33 {34 return null;35 }36 JsonElement retElement;37 if (!element.Value.TryGetProperty(name, out retElement))38 {39 return null;40 }41 var guid = retElement.GetProperty("guid").ToString();42 return connection.GetObject(guid) as T;43 }44 internal static T GetObject<T>(this JsonElement element, string name, Connection connection)45 where T : ChannelOwnerBase, IChannelOwner<T>46 {47 var result = GetObject<T>((JsonElement?)element, name, connection);48 if (result == null)49 {50 throw new ArgumentNullException($"Element {name} expected, but was not found.");51 }52 return result;53 }54 // this method is needed, because a converter for <see cref="Exception"/> is no longer supported55 // since .NET5 and throws an exception of "Serialization and deserialization of 'System.Type' instances are not supported and should be avoided since they can lead to security issues."}56 internal static dynamic ToObject(this Exception exception)57 {58 if (exception == null)59 {60 return new { };61 }62 return new63 {64 error = new65 {66 message = exception.Message,67 stack = exception.StackTrace,68 name = exception.GetType().Name,69 },70 };71 }72 }73}74#nullable disable75#pragma warning restore IDE0018 // Inline variable declaration...

Full Screen

Full Screen

Playwright.cs

Source:Playwright.cs Github

copy

Full Screen

...40 /// <returns>A <see cref="Task"/> that completes when the playwright driver is ready to be used.</returns>41 public static async Task<IPlaywright> CreateAsync()42 {43#pragma warning disable CA2000 // Dispose objects before losing scope44 var transport = new StdIOTransport();45#pragma warning restore CA200046 var connection = new Connection();47 transport.MessageReceived += (_, message) => connection.Dispatch(JsonSerializer.Deserialize<PlaywrightServerMessage>(message, JsonExtensions.DefaultJsonSerializerOptions));48 transport.LogReceived += (_, log) => Console.Error.WriteLine(log);49 transport.TransportClosed += (_, reason) => connection.DoClose(reason);50 connection.OnMessage = (message) => transport.SendAsync(JsonSerializer.SerializeToUtf8Bytes(message, connection.DefaultJsonSerializerOptions));51 connection.Close += (_, reason) => transport.Close(reason);52 var playwright = await connection.InitializePlaywrightAsync().ConfigureAwait(false);53 playwright.Connection = connection;54 return playwright;55 }56 }57} ...

Full Screen

Full Screen

JsonPipe.cs

Source:JsonPipe.cs Github

copy

Full Screen

...33 private readonly JsonPipeChannel _channel;34 private readonly JsonPipeInitializer _initializer;35 public JsonPipe(IChannelOwner parent, string guid, JsonPipeInitializer initializer) : base(parent, guid)36 {37 _channel = new(guid, parent.Connection, this);38 _initializer = initializer;39 _channel.Closed += (_, e) => Closed.Invoke(this, e);40 _channel.Message += (_, e) => Message.Invoke(this, e);41 }42 public event EventHandler<PlaywrightServerMessage> Message;43 public event EventHandler<SerializedError> Closed;44 ChannelBase IChannelOwner.Channel => _channel;45 IChannel<JsonPipe> IChannelOwner<JsonPipe>.Channel => _channel;46 public Task CloseAsync() => _channel.CloseAsync();47 public Task SendAsync(object message) => _channel.SendAsync(message);48 }49}...

Full Screen

Full Screen

LocalUtils.cs

Source:LocalUtils.cs Github

copy

Full Screen

...35 {36 private readonly LocalUtilsChannel _channel;37 public LocalUtils(IChannelOwner parent, string guid, JsonElement? initializer) : base(parent, guid)38 {39 _channel = new(guid, parent.Connection, this);40 }41 ChannelBase IChannelOwner.Channel => _channel;42 IChannel<LocalUtils> IChannelOwner<LocalUtils>.Channel => _channel;43 internal Task ZipAsync(string zipFile, List<NameValueEntry> entries)44 => _channel.ZipAsync(zipFile, entries);45 }46}

Full Screen

Full Screen

new

Using AI Code Generation

copy

Full Screen

1var playwright = await Microsoft.Playwright.Playwright.CreateAsync();2var browser = await playwright.Chromium.LaunchAsync();3var page = await browser.NewPageAsync();4await page.ScreenshotAsync(new Microsoft.Playwright.PageScreenshotOptions { Path = "2.png" });5await browser.CloseAsync();6var playwright = await Microsoft.Playwright.Playwright.CreateAsync();7var browser = await playwright.Chromium.LaunchAsync();8var page = await browser.NewPageAsync();9await page.ScreenshotAsync(new Microsoft.Playwright.PageScreenshotOptions { Path = "3.png" });10await browser.CloseAsync();11var playwright = await Microsoft.Playwright.Playwright.CreateAsync();12var browser = await playwright.Chromium.LaunchAsync();13var page = await browser.NewPageAsync();14await page.ScreenshotAsync(new Microsoft.Playwright.PageScreenshotOptions { Path = "4.png" });15await browser.CloseAsync();16var playwright = await Microsoft.Playwright.Playwright.CreateAsync();17var browser = await playwright.Chromium.LaunchAsync();18var page = await browser.NewPageAsync();19await page.ScreenshotAsync(new Microsoft.Playwright.PageScreenshotOptions { Path = "5.png" });20await browser.CloseAsync();21var playwright = await Microsoft.Playwright.Playwright.CreateAsync();22var browser = await playwright.Chromium.LaunchAsync();23var page = await browser.NewPageAsync();24await page.ScreenshotAsync(new Microsoft.Playwright.PageScreenshotOptions { Path = "6.png" });25await browser.CloseAsync();26var playwright = await Microsoft.Playwright.Playwright.CreateAsync();27var browser = await playwright.Chromium.LaunchAsync();28var page = await browser.NewPageAsync();

Full Screen

Full Screen

new

Using AI Code Generation

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using Microsoft.Playwright;7using Microsoft.Playwright.Transport;8{9 {10 static async Task Main(string[] args)11 {12 var browser = await connection.CreateAsync<IBrowser>("BrowserType.launch");13 var page = await connection.CreateAsync<IPage>("Browser.newPage");14 var title = await page.TitleAsync();15 Console.WriteLine(title);16 await browser.CloseAsync();17 connection.Dispose();18 }19 }20}

Full Screen

Full Screen

new

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using Microsoft.Playwright.Transport;3using System;4using System.Threading.Tasks;5{6 {7 static async Task Main(string[] args)8 {9 var connection = new Connection();10 await connection.ConnectAsync();11 var browser = await connection.CreateBrowserAsync();12 var page = await browser.NewPageAsync();13 await page.ScreenshotAsync("screenshot.png");14 await browser.CloseAsync();15 await connection.DisposeAsync();16 }17 }18}

Full Screen

Full Screen

new

Using AI Code Generation

copy

Full Screen

1Connection connection = new Connection();2var browser = await connection.NewBrowserAsync();3var page = await browser.NewPageAsync();4var browser = await Connection.NewBrowserAsync();5var page = await browser.NewPageAsync();6var playwright = await Playwright.CreateAsync();7var browser = await playwright.Chromium.LaunchAsync();8var page = await browser.NewPageAsync();9var playwright = await Playwright.CreateAsync();10var browser = await playwright.Chromium.LaunchAsync();11var page = await browser.NewPageAsync();12var playwright = await Playwright.CreateAsync();13var browser = await playwright.Firefox.LaunchAsync();14var page = await browser.NewPageAsync();15var playwright = await Playwright.CreateAsync();16var browser = await playwright.Webkit.LaunchAsync();17var page = await browser.NewPageAsync();18var playwright = await Playwright.CreateAsync();19var browser = await playwright.Webkit.LaunchAsync();20var page = await browser.NewPageAsync();21await page.ScreenshotAsync("bing.png");22var playwright = await Playwright.CreateAsync();23var browser = await playwright.Webkit.LaunchAsync();24var page = await browser.NewPageAsync();25await page.ScreenshotAsync("bing.png");26var playwright = await Playwright.CreateAsync();27var browser = await playwright.Webkit.LaunchAsync();28var page = await browser.NewPageAsync();29await page.ScreenshotAsync("bing.png");30var playwright = await Playwright.CreateAsync();31var browser = await playwright.Webkit.LaunchAsync();32var page = await browser.NewPageAsync();33await page.ScreenshotAsync("bing.png");34var playwright = await Playwright.CreateAsync();

Full Screen

Full Screen

new

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using Microsoft.Playwright.Transport;3using System;4using System.Threading.Tasks;5{6 {7 static async Task Main(string[] args)8 {9 var playwright = await Playwright.CreateAsync(connection);10 var browser = await playwright.Chromium.LaunchAsync();11 var context = await browser.NewContextAsync();12 var page = await context.NewPageAsync();13 await page.ScreenshotAsync("screenshot.png");14 await browser.CloseAsync();15 }16 }17}18using Microsoft.Playwright;19using Microsoft.Playwright.Transport;20using System;21using System.Threading.Tasks;22{23 {24 static async Task Main(string[] args)25 {26 var playwright = await Playwright.CreateAsync(connection);27 var browser = await playwright.Firefox.LaunchAsync();28 var context = await browser.NewContextAsync();29 var page = await context.NewPageAsync();30 await page.ScreenshotAsync("screenshot.png");31 await browser.CloseAsync();32 }33 }34}35using Microsoft.Playwright;36using Microsoft.Playwright.Transport;37using System;38using System.Threading.Tasks;39{40 {41 static async Task Main(string[] args)42 {43 var playwright = await Playwright.CreateAsync(connection);44 var browser = await playwright.Webkit.LaunchAsync();45 var context = await browser.NewContextAsync();46 var page = await context.NewPageAsync();47 await page.ScreenshotAsync("screenshot.png");48 await browser.CloseAsync();49 }

Full Screen

Full Screen

new

Using AI Code Generation

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.Linq;4using System.Threading.Tasks;5using Microsoft.Playwright.Core;6{7 {8 private readonly IConnectionTransport _transport;9 private readonly Dictionary<string, TaskCompletionSource<IChannelOwner>> _pendingCommands = new Dictionary<string, TaskCompletionSource<IChannelOwner>>();10 private readonly Dictionary<string, IChannelOwner> _objects = new Dictionary<string, IChannelOwner>();11 private readonly Dictionary<string, HashSet<string>> _objectOwners = new Dictionary<string, HashSet<string>>();12 private readonly Dictionary<string, HashSet<string>> _objectChildren = new Dictionary<string, HashSet<string>>();13 private readonly Dictionary<string, HashSet<string>> _objectEvents = new Dictionary<string, HashSet<string>>();14 private readonly Dictionary<string, string> _objectName = new Dictionary<string, string>();15 private readonly Dictionary<string, string> _objectGuid = new Dictionary<string, string>();16 private readonly Dictionary<string, string> _objectType = new Dictionary<string, string>();17 private readonly Dictionary<string, HashSet<string>> _objectEventTypes = new Dictionary<string, HashSet<string>>();18 private readonly Dictionary<string, Dictionary<string, string>> _objectEventParams = new Dictionary<string, Dictionary<string, string>>();19 private readonly Dictionary<string, Dictionary<string, string>> _objectEventTypesParams = new Dictionary<string, Dictionary<string, string>>();20 private readonly Dictionary<string, Dictionary<string, string>> _objectEventTypesParamsTypes = new Dictionary<string, Dictionary<string, string>>();21 private readonly Dictionary<string, Dictionary<string, string>> _objectEventTypesParamsGuid = new Dictionary<string, Dictionary<string, string>>();22 private readonly Dictionary<string, Dictionary<string, string>> _objectEventTypesParamsName = new Dictionary<string, Dictionary<string, string>>();23 private readonly Dictionary<string, HashSet<string>> _objectMethods = new Dictionary<string, HashSet<string>>();24 private readonly Dictionary<string, Dictionary<string, string>> _objectMethodParams = new Dictionary<string, Dictionary<string, string>>();25 private readonly Dictionary<string, Dictionary<string, string>> _objectMethodParamsTypes = new Dictionary<string, Dictionary<string, string>>();26 private readonly Dictionary<string, Dictionary<string, string>> _objectMethodParamsGuid = new Dictionary<string, Dictionary<string, string>>();27 private readonly Dictionary<string, Dictionary<string, string>> _objectMethodParamsName = new Dictionary<string, Dictionary<string, string>>();

Full Screen

Full Screen

new

Using AI Code Generation

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.Threading.Tasks;4using Microsoft.Playwright;5{6 {7 static async Task Main(string[] args)8 {9 var playwright = await Playwright.CreateAsync();10 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions11 {12 });13 var page = await browser.NewPageAsync();

Full Screen

Full Screen

new

Using AI Code Generation

copy

Full Screen

1var playwright = await Microsoft.Playwright.Playwright.CreateAsync();2var browser = await playwright.Chromium.LaunchAsync();3var page = await browser.NewPageAsync();4await page.ScreenshotAsync(new Microsoft.Playwright.PageScreenshotOptions() { Path = "screenshot.png" });5await browser.CloseAsync();6var playwright = await Microsoft.Playwright.Playwright.CreateAsync();7var browser = await playwright.Chromium.LaunchAsync();8var page = await browser.NewPageAsync();9await page.ScreenshotAsync(new Microsoft.Playwright.PageScreenshotOptions() { Path = "screenshot.png" });10await browser.CloseAsync();11var playwright = await Microsoft.Playwright.Playwright.CreateAsync();12var browser = await playwright.Chromium.LaunchAsync();13var page = await browser.NewPageAsync();14await page.ScreenshotAsync(new Microsoft.Playwright.PageScreenshotOptions() { Path = "screenshot.png" });15await browser.CloseAsync();16var playwright = await Microsoft.Playwright.Playwright.CreateAsync();17var browser = await playwright.Chromium.LaunchAsync();18var page = await browser.NewPageAsync();19await page.ScreenshotAsync(new Microsoft.Playwright.PageScreenshotOptions() { Path = "screenshot.png" });20await browser.CloseAsync();21var playwright = await Microsoft.Playwright.Playwright.CreateAsync();22var browser = await playwright.Chromium.LaunchAsync();23var page = await browser.NewPageAsync();24await page.ScreenshotAsync(new Microsoft.Playwright.PageScreenshotOptions() { Path = "screenshot.png" });25await browser.CloseAsync();

Full Screen

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright-dotnet automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful