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

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

Connection.cs

Source:Connection.cs Github

copy

Full Screen

...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();...

Full Screen

Full Screen

Waiter.cs

Source:Waiter.cs Github

copy

Full Screen

...56 {57 dispose();58 }59 var afterArgs = new { info = new { waitId = _waitId, phase = "after", error = _error } };60 _channelOwner.WrapApiCallAsync(() => _channelOwner.Connection.SendMessageToServerAsync(_channelOwner.Channel.Guid, "waitForEventInfo", afterArgs), true).IgnoreException();61 _cts.Cancel();62 _cts.Dispose();63 }64 }65 internal void Log(string log)66 {67 _logs.Add(log);68 var logArgs = new { info = new { waitId = _waitId, phase = "log", message = log } };69 _channelOwner.WrapApiCallAsync(() => _channelOwner.Connection.SendMessageToServerAsync(_channelOwner.Channel.Guid, "waitForEventInfo", logArgs), true).IgnoreException();70 }71 internal void RejectImmediately(Exception exception)72 {73 _immediateError = exception;74 }75 internal void RejectOnEvent<T>(76 object eventSource,77 string e,78 PlaywrightException navigationException,79 Func<T, bool> predicate = null)80 {81 if (eventSource == null)82 {83 return;...

Full Screen

Full Screen

ChannelOwnerBase.cs

Source:ChannelOwnerBase.cs Github

copy

Full Screen

...63 item.DisposeOwner();64 }65 _objects.Clear();66 }67 public Task<T> WrapApiCallAsync<T>(Func<Task<T>> action, bool isInternal = false) => _connection.WrapApiCallAsync(action, isInternal);68 public Task WrapApiBoundaryAsync(Func<Task> action) => _connection.WrapApiBoundaryAsync(action);69 }70}...

Full Screen

Full Screen

IChannelOwner.cs

Source:IChannelOwner.cs Github

copy

Full Screen

...46 /// <summary>47 /// Removes the object from the parent and the connection list.48 /// </summary>49 void DisposeOwner();50 Task<T> WrapApiCallAsync<T>(Func<Task<T>> action, bool isInternal = false);51 Task WrapApiBoundaryAsync(Func<Task> action);52 }53 /// <summary>54 /// An IChannelOwner has the ability to build data coming from a Playwright server and convert it into a Playwright class.55 /// </summary>56 /// <typeparam name="T">Channel Owner implementation.</typeparam>57 internal interface IChannelOwner<T> : IChannelOwner58 where T : ChannelOwnerBase, IChannelOwner<T>59 {60 /// <summary>61 /// Channel.62 /// </summary>63 new IChannel<T> Channel { get; }64 }...

Full Screen

Full Screen

WrapApiCallAsync

Using AI Code Generation

copy

Full Screen

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

Full Screen

Full Screen

WrapApiCallAsync

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;6using Microsoft.Playwright.Transport.Protocol;7using Microsoft.Playwright.Transport.Protocol.Input;8using Microsoft.Playwright.Transport.Protocol.Page;9using Microsoft.Playwright.Transport.Protocol.Playwright;10{11 {12 static async Task Main(string[] args)13 {14 var playwright = await Playwright.CreateAsync();15 var browser = await playwright.Chromium.LaunchAsync();16 var page = await browser.NewPageAsync();17 await page.SetViewportSizeAsync(1024, 768);18 await page.ScreenshotAsync(new PageScreenshotOptions { Path = "google.png" });19 await browser.CloseAsync();20 }21 }22}

Full Screen

Full Screen

WrapApiCallAsync

Using AI Code Generation

copy

Full Screen

1await using var playwright = await Playwright.CreateAsync();2var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions3{4 Args = new[] { "--remote-debugging-port=9222" },5});6var page = await browser.NewPageAsync();7var connection = page.Context.Browser.Connection;8var result = await connection.WrapApiCallAsync<object>("Page.addScriptToEvaluateOnNewDocument", new Dictionary<string, object>9{10 { "source", "window.__playwright = true;" }11});12Console.WriteLine(result);13await browser.CloseAsync();14await using var playwright = await Playwright.CreateAsync();15var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions16{17 Args = new[] { "--remote-debugging-port=9222" },18});19var page = await browser.NewPageAsync();20var connection = page.Context.Browser.Connection;21var result = await connection.WrapApiCallAsync<object>("Page.addScriptToEvaluateOnNewDocument", new Dictionary<string, object>22{23 { "source", "window.__playwright = true;" }24});25Console.WriteLine(result);26await browser.CloseAsync();27await using var playwright = await Playwright.CreateAsync();28var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions29{30 Args = new[] { "--remote-debugging-port=9222" },31});32var page = await browser.NewPageAsync();33var connection = page.Context.Browser.Connection;34var result = await connection.WrapApiCallAsync<object>("Page.addScriptToEvaluateOnNewDocument", new Dictionary<string, object>35{36 { "source", "window.__playwright = true;" }37});38Console.WriteLine(result);39await browser.CloseAsync();40await using var playwright = await Playwright.CreateAsync();

Full Screen

Full Screen

WrapApiCallAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false });10 var page = await browser.NewPageAsync();11 var connection = page.Channel.Connection;12 var result = await connection.WrapApiCallAsync(13 {14 },15 );16 }17 }18}19using System;20using System.Threading.Tasks;21using Microsoft.Playwright;22{23 {24 static async Task Main(string[] args)25 {26 using var playwright = await Playwright.CreateAsync();27 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false });28 var page = await browser.NewPageAsync();29 await page.SetContentAsync(@"<html><body><div>hello world</div></body></html>");30 }31 }32}

Full Screen

Full Screen

WrapApiCallAsync

Using AI Code Generation

copy

Full Screen

1using System;2using System.Threading.Tasks;3using Microsoft.Playwright;4{5 {6 static async Task Main(string[] args)7 {8 using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions10 {11 });12 var context = await browser.NewContextAsync();13 var page = await context.NewPageAsync();14 var result = await page.GetAttributeAsync("html", "outerHTML");15 Console.WriteLine(result);16 }17 }18}19using System;20using System.Threading.Tasks;21using Microsoft.Playwright;22{23 {24 static async Task Main(string[] args)25 {26 using var playwright = await Playwright.CreateAsync();27 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions28 {29 });30 var context = await browser.NewContextAsync();31 var page = await context.NewPageAsync();32 var result = await page.GetAttributeAsync("html", "outerHTML");33 Console.WriteLine(result);34 }35 }36}

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