How to use Connection class of Microsoft.Playwright.Transport package

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

Connection.cs

Source:Connection.cs Github

copy

Full Screen

...38using Microsoft.Playwright.Transport.Converters;39using Microsoft.Playwright.Transport.Protocol;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);...

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

...37 /// </summary>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() switch79 {80 global::Microsoft.Playwright.BrowserType.Chromium => Chromium,81 global::Microsoft.Playwright.BrowserType.Firefox => Firefox,82 global::Microsoft.Playwright.BrowserType.Webkit => Webkit,83 _ => null,84 };85 public void Dispose()86 {87 Dispose(true);88 GC.SuppressFinalize(this);89 }90 private void Dispose(bool disposing)91 {92 if (!disposing)93 {94 return;95 }96 Connection?.Dispose();97 }98 }99}...

Full Screen

Full Screen

Artifact.cs

Source:Artifact.cs Github

copy

Full Screen

...31namespace Microsoft.Playwright.Core32{33 internal class Artifact : ChannelOwnerBase, IChannelOwner<Artifact>34 {35 private readonly Connection _connection;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)...

Full Screen

Full Screen

Playwright.cs

Source:Playwright.cs Github

copy

Full Screen

...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

Root.cs

Source:Root.cs Github

copy

Full Screen

...27namespace Microsoft.Playwright.Transport.Channels28{29 internal class Root : ChannelOwnerBase30 {31 private readonly Connection _connection;32 internal Root(IChannelOwner parent, Connection connection, string guid) : base(parent, connection, guid)33 {34 _connection = connection;35 }36 internal async Task<PlaywrightImpl> InitializeAsync()37 {38 var args = new39 {40 sdkLanguage = "csharp",41 };42 var jsonElement = await _connection.SendMessageToServerAsync(string.Empty, "initialize", args).ConfigureAwait(false);43 return jsonElement.GetObject<PlaywrightImpl>("playwright", _connection);44 }45 }46}...

Full Screen

Full Screen

Connection

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright.Transport;2using Microsoft.Playwright.Transport.Channels;3using Microsoft.Playwright.Transport.Protocol;4using System;5using System.Collections.Generic;6using System.Linq;7using System.Text;8using System.Threading.Tasks;9{10 {11 static async Task Main(string[] args)12 {13 var browser = await connection.WaitForObjectWithKnownNameAsync<BrowserChannel>("browser");14 var page = await browser.NewPageAsync();15 await page.ScreenshotAsync(new PageScreenshotOptions {Path = "screenshot.png"});16 await connection.CloseAsync();17 }18 }19}20using Microsoft.Playwright;21using System;22using System.Collections.Generic;23using System.Linq;24using System.Text;25using System.Threading.Tasks;26{27 {28 static async Task Main(string[] args)29 {30 var playwright = await Playwright.CreateAsync();31 var browser = await playwright.Chromium.LaunchAsync();32 var page = await browser.NewPageAsync();33 await page.ScreenshotAsync(new PageScreenshotOptions {Path = "screenshot.png"});34 await browser.CloseAsync();35 }36 }37}38using Microsoft.Playwright;39using System;40using System.Collections.Generic;41using System.Linq;42using System.Text;43using System.Threading.Tasks;44{45 {46 static async Task Main(string[] args)47 {48 var playwright = await Playwright.CreateAsync();49 var browser = await playwright.Chromium.LaunchAsync();50 var page = await browser.NewPageAsync();51 await page.ScreenshotAsync(new PageScreenshotOptions {Path = "screenshot.png"});52 await browser.CloseAsync();53 }54 }55}56using Microsoft.Playwright;57using System;58using System.Collections.Generic;59using System.Linq;60using System.Text;61using System.Threading.Tasks;62{63 {64 static async Task Main(string[] args

Full Screen

Full Screen

Connection

Using AI Code Generation

copy

Full Screen

1var playwright = await Playwright.CreateAsync();2var browser = await playwright.Chromium.LaunchAsync();3var page = await browser.NewPageAsync();4await page.ScreenshotAsync("google.png");5await browser.CloseAsync();6await playwright.StopAsync();7var playwright = await Playwright.CreateAsync();8var browser = await playwright.Chromium.LaunchAsync();9var page = await browser.NewPageAsync();10await page.ScreenshotAsync("google.png");11await browser.CloseAsync();12await playwright.StopAsync();13The type or namespace name 'Playwright' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)143 -> Microsoft.Playwright.Transport 0.192.0 -> Microsoft.Playwright (>= 0.192.0)15NU1202 Package Microsoft.Playwright.Transport 0.192.0 is not compatible with net5.0 (.NETCoreApp,Version=v5.0). Package Microsoft.Playwright.Transport 0.192.0 supports: netstandard2.0 (.NETStandard,Version=v2.0)

Full Screen

Full Screen

Connection

Using AI Code Generation

copy

Full Screen

1var playwright = await Playwright.CreateAsync(connection);2var browser = await playwright.Chromium.LaunchAsync();3var page = await browser.NewPageAsync();4await page.ScreenshotAsync(new PageScreenshotOptions {Path = "example.png"});5await browser.CloseAsync();6await playwright.CloseAsync();7var playwright = await Playwright.CreateAsync();8var browser = await playwright.Chromium.LaunchAsync();9var page = await browser.NewPageAsync();10await page.ScreenshotAsync(new PageScreenshotOptions {Path = "example.png"});11await browser.CloseAsync();12await playwright.CloseAsync();13var playwright = await Playwright.CreateAsync(connection);14var browser = await playwright.Chromium.LaunchAsync();15var page = await browser.NewPageAsync();16await page.ScreenshotAsync(new PageScreenshotOptions {Path = "example.png"});17await browser.CloseAsync();18await playwright.CloseAsync();

Full Screen

Full Screen

Connection

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Playwright.Transport.Channels;4{5 {6 private readonly ConnectionChannel _channel;7 public Connection(ConnectionChannel channel)8 {9 _channel = channel;10 }11 public Task<ChannelBase> SendMessageToServerAsync(string guid, string method, object args) =>12 _channel.SendMessageToServerAsync(guid, method, args);13 public Task CloseAsync() => _channel.CloseAsync();14 public Task SetMaxWebSocketFrameSizeAsync(int size) => _channel.SetMaxWebSocketFrameSizeAsync(size);15 public void SetOwner(object owner) => _channel.SetOwner(owner);16 }17}18using System;19using System.Threading.Tasks;20using Microsoft.Playwright.Transport.Channels;21{22 {23 internal Playwright(IConnection connection, string guid) : base(connection, guid)24 {25 }26 public ChannelBase Channel => _channel;27 Playwright IChannelOwner<Playwright>.Object => this;28 public async Task<BrowserType> LaunchBrowserTypeAsync(string browserName, LaunchOptions options = null)29 {30 var guid = Guid.NewGuid().ToString();31 var playwrightChannel = (PlaywrightChannel)Channel;32 var browserTypeChannel = await playwrightChannel.LaunchBrowserTypeAsync(guid, browserName, options).ConfigureAwait(false);33 return new BrowserType(Connection, browserTypeChannel);34 }35 }36}37using System;38using System.Threading.Tasks;39using Microsoft.Playwright.Transport.Channels;40{41 {42 internal BrowserType(IConnection connection, ChannelBase channel) : base(connection, channel)43 {44 }45 public ChannelBase Channel => _channel;46 BrowserType IChannelOwner<BrowserType>.Object => this;47 public async Task<Browser> LaunchAsync(LaunchOptions options = null)48 {49 var guid = Guid.NewGuid().ToString();50 var browserTypeChannel = (BrowserTypeChannel)Channel;51 var browserChannel = await browserTypeChannel.LaunchAsync(guid

Full Screen

Full Screen

Connection

Using AI Code Generation

copy

Full Screen

1var connection = new Connection();2var browser = await connection.NewBrowserAsync();3var page = await browser.NewPageAsync();4await connection.CloseAsync();5var connection = new Connection();6var browser = await connection.NewBrowserAsync();7var page = await browser.NewPageAsync();8await connection.CloseAsync();9var connection = new Connection();10var browser = await connection.NewBrowserAsync();11var page = await browser.NewPageAsync();12await connection.CloseAsync();13var connection = new Connection();14var browser = await connection.NewBrowserAsync();15var page = await browser.NewPageAsync();16await connection.CloseAsync();17var connection = new Connection();18var browser = await connection.NewBrowserAsync();19var page = await browser.NewPageAsync();20await connection.CloseAsync();21var connection = new Connection();22var browser = await connection.NewBrowserAsync();23var page = await browser.NewPageAsync();24await connection.CloseAsync();25var connection = new Connection();26var browser = await connection.NewBrowserAsync();27var page = await browser.NewPageAsync();28await connection.CloseAsync();29var connection = new Connection();30var browser = await connection.NewBrowserAsync();31var page = await browser.NewPageAsync();32await connection.CloseAsync();33var connection = new Connection();

Full Screen

Full Screen

Connection

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright.Transport;2using System;3using System.Collections.Generic;4using System.Text;5using System.Threading.Tasks;6{7 {8 public static async Task ConnectAsync()9 {

Full Screen

Full Screen

Connection

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright.Transport;2using Microsoft.Playwright.Transport.Channels;3using System;4using System.Threading.Tasks;5{6 {7 private static async Task Main()8 {9 var connection = new Connection();10 var page = await browser.NewPageAsync();11 await page.ScreenshotAsync("wikipedia.png");12 await browser.CloseAsync();13 }14 }15}16using Microsoft.Playwright;17using System;18using System.Threading.Tasks;19{20 {21 private static async Task Main()22 {23 var connection = new Connection();24 var page = await browser.NewPageAsync();25 await page.ScreenshotAsync("wikipedia.png");26 await browser.CloseAsync();27 }28 }29}30using Microsoft.Playwright;31using System;32using System.Threading.Tasks;33{34 {35 private static async Task Main()36 {37 var connection = new Connection();38 var page = await browser.NewPageAsync();39 await page.ScreenshotAsync("wikipedia.png");40 await browser.CloseAsync();41 }42 }43}44using Microsoft.Playwright;45using System;46using System.Threading.Tasks;47{48 {49 private static async Task Main()50 {51 var connection = new Connection();52 var page = await browser.NewPageAsync();53 await page.ScreenshotAsync("wikipedia.png");54 await browser.CloseAsync();55 }56 }57}

Full Screen

Full Screen

Connection

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright.Transport;2using Microsoft.Playwright.Transport.Channels;3{4 private static async Task Main(string[] args)5 {6 var connection = new Connection(new ConnectionOptions7 {8 {9 var webSocket = new ClientWebSocket();10 await webSocket.ConnectAsync(uri, CancellationToken.None);11 return webSocket;12 },13 });14 var browserTypeChannel = new BrowserTypeChannel(connection, "browserType", null);15 var browserType = new BrowserType(browserTypeChannel);16 var browser = await browserType.LaunchAsync();17 var page = await browser.NewPageAsync();18 await page.ScreenshotAsync("screenshot.png");19 await browser.CloseAsync();20 }21}22using Microsoft.Playwright;23{24 private static async Task Main(string[] args)25 {26 using var playwright = await Microsoft.Playwright.Playwright.CreateAsync();27 await using var browser = await playwright.Chromium.LaunchAsync();28 var page = await browser.NewPageAsync();29 await page.ScreenshotAsync("screenshot.png");30 await browser.CloseAsync();31 }32}

Full Screen

Full Screen

Connection

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4using Microsoft.Playwright.Transport;5using Microsoft.Playwright.Transport.Channels;6{7 {8 static async Task Main(string[] args)9 {

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