How to use DialogInitializer class of Microsoft.Playwright.Transport.Protocol package

Best Playwright-dotnet code snippet using Microsoft.Playwright.Transport.Protocol.DialogInitializer

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

Dialog.cs

Source: Dialog.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) Microsoft Corporation.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25using System.Threading.Tasks;
26using Microsoft.Playwright.Transport;
27using Microsoft.Playwright.Transport.Channels;
28using Microsoft.Playwright.Transport.Protocol;
29
30namespace Microsoft.Playwright.Core
31{
32    internal class Dialog : ChannelOwnerBase, IChannelOwner<Dialog>, IDialog
33    {
34        private readonly DialogChannel _channel;
35        private readonly DialogInitializer _initializer;
36
37        public Dialog(IChannelOwner parent, string guid, DialogInitializer initializer) : base(parent, guid)
38        {
39            _channel = new(guid, parent.Connection, this);
40            _initializer = initializer;
41        }
42
43        public string Type => _initializer.Type;
44
45        public string DefaultValue => _initializer.DefaultValue;
46
47        public string Message => _initializer.Message;
48
49        ChannelBase IChannelOwner.Channel => _channel;
50
51        IChannel<Dialog> IChannelOwner<Dialog>.Channel => _channel;
52
53        public Task AcceptAsync(string promptText) => _channel.AcceptAsync(promptText ?? string.Empty);
54
55        public Task DismissAsync() => _channel.DismissAsync();
56    }
57}
58
Full Screen

DialogInitializer.cs

Source: DialogInitializer.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) Microsoft Corporation.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25using System.Collections.Generic;
26
27namespace Microsoft.Playwright.Transport.Protocol
28{
29    internal class DialogInitializer
30    {
31        public string Type { get; set; }
32
33        public string Message { get; set; }
34
35        public string DefaultValue { get; set; }
36    }
37}
38
Full Screen

Connection.cs

Source: Connection.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) 2020 Darío Kondratiuk
5 * Copyright (c) 2020 Meir Blachman
6 * Modifications copyright (c) Microsoft Corporation.
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in all
16 * copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 * SOFTWARE.
25 */
26
27using System;
28using System.Collections.Concurrent;
29using System.Collections.Generic;
30using System.ComponentModel;
31using System.Diagnostics;
32using System.Linq;
33using System.Text.Json;
34using System.Threading;
35using System.Threading.Tasks;
36using Microsoft.Playwright.Core;
37using Microsoft.Playwright.Helpers;
38using Microsoft.Playwright.Transport.Channels;
39using Microsoft.Playwright.Transport.Converters;
40using Microsoft.Playwright.Transport.Protocol;
41
42namespace Microsoft.Playwright.Transport
43{
44    internal class Connection : IDisposable
45    {
46        private readonly ConcurrentDictionary<int, ConnectionCallback> _callbacks = new();
47        private readonly Root _rootObject;
48        private readonly TaskQueue _queue = new();
49        private int _lastId;
50        private string _reason = string.Empty;
51
52        public Connection()
53        {
54            _rootObject = new(null, this, string.Empty);
55
56            DefaultJsonSerializerOptions = JsonExtensions.GetNewDefaultSerializerOptions();
57            DefaultJsonSerializerOptions.Converters.Add(new ChannelToGuidConverter(this));
58            DefaultJsonSerializerOptions.Converters.Add(new ChannelOwnerToGuidConverter<JSHandle>(this));
59            DefaultJsonSerializerOptions.Converters.Add(new ChannelOwnerToGuidConverter<ElementHandle>(this));
60            DefaultJsonSerializerOptions.Converters.Add(new ChannelOwnerToGuidConverter<IChannelOwner>(this));
61
62            // Workaround for https://github.com/dotnet/runtime/issues/46522
63            DefaultJsonSerializerOptions.Converters.Add(new ChannelOwnerListToGuidListConverter<WritableStream>(this));
64        }
65
66        /// <inheritdoc cref="IDisposable.Dispose"/>
67        ~Connection() => Dispose(false);
68
69        internal event EventHandler<string> Close;
70
71        public ConcurrentDictionary<string, IChannelOwner> Objects { get; } = new();
72
73        internal AsyncLocal<List<ApiZone>> ApiZone { get; } = new();
74
75        public bool IsClosed { get; private set; }
76
77        internal bool IsRemote { get; set; }
78
79        internal Func<object, Task> OnMessage { get; set; }
80
81        internal JsonSerializerOptions DefaultJsonSerializerOptions { get; }
82
83        public void Dispose()
84        {
85            Dispose(true);
86            GC.SuppressFinalize(this);
87        }
88
89        internal Task<JsonElement?> SendMessageToServerAsync(
90            string guid,
91            string method,
92            object args = null)
93            => SendMessageToServerAsync<JsonElement?>(guid, method, args);
94
95        internal Task<T> SendMessageToServerAsync<T>(
96            string guid,
97            string method,
98            object args = null) => WrapApiCallAsync(() => InnerSendMessageToServerAsync<T>(guid, method, args));
99
100        private async Task<T> InnerSendMessageToServerAsync<T>(
101            string guid,
102            string method,
103            object args = null)
104        {
105            if (IsClosed)
106            {
107                throw new PlaywrightException($"Connection closed ({_reason})");
108            }
109
110            int id = Interlocked.Increment(ref _lastId);
111            var tcs = new TaskCompletionSource<JsonElement?>(TaskCreationOptions.RunContinuationsAsynchronously);
112            var callback = new ConnectionCallback
113            {
114                TaskCompletionSource = tcs,
115            };
116
117            _callbacks.TryAdd(id, callback);
118
119            var sanitizedArgs = new Dictionary<string, object>();
120            if (args != null)
121            {
122                if (args is IDictionary<string, object> dictionary && dictionary.Keys.Any(f => f != null))
123                {
124                    foreach (var kv in dictionary)
125                    {
126                        if (kv.Value != null)
127                        {
128                            sanitizedArgs.Add(kv.Key, kv.Value);
129                        }
130                    }
131                }
132                else
133                {
134                    foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(args))
135                    {
136                        object obj = propertyDescriptor.GetValue(args);
137                        if (obj != null)
138                        {
139#pragma warning disable CA1845 // Use span-based 'string.Concat' and 'AsSpan' instead of 'Substring
140                            string name = propertyDescriptor.Name.Substring(0, 1).ToLower() + propertyDescriptor.Name.Substring(1);
141#pragma warning restore CA2000 // Use span-based 'string.Concat' and 'AsSpan' instead of 'Substring
142                            sanitizedArgs.Add(name, obj);
143                        }
144                    }
145                }
146            }
147
148            await _queue.EnqueueAsync(() =>
149            {
150                var message = new MessageRequest
151                {
152                    Id = id,
153                    Guid = guid,
154                    Method = method,
155                    Params = sanitizedArgs,
156                    Metadata = ApiZone.Value[0],
157                };
158
159                TraceMessage("pw:channel:command", message);
160
161                return OnMessage(message);
162            }).ConfigureAwait(false);
163
164            var result = await tcs.Task.ConfigureAwait(false);
165
166            if (typeof(T) == typeof(JsonElement?))
167            {
168                return (T)(object)result?.Clone();
169            }
170            else if (result == null)
171            {
172                return default;
173            }
174            else if (typeof(ChannelBase).IsAssignableFrom(typeof(T)) || typeof(ChannelBase[]).IsAssignableFrom(typeof(T)))
175            {
176                var enumerate = result.Value.EnumerateObject();
177
178                return enumerate.Any()
179                    ? enumerate.FirstOrDefault().Value.ToObject<T>(DefaultJsonSerializerOptions)
180                    : default;
181            }
182            else
183            {
184                return result.Value.ToObject<T>(DefaultJsonSerializerOptions);
185            }
186        }
187
188        internal IChannelOwner GetObject(string guid)
189        {
190            Objects.TryGetValue(guid, out var result);
191            return result;
192        }
193
194        internal void MarkAsRemote() => IsRemote = true;
195
196        internal Task<PlaywrightImpl> InitializePlaywrightAsync()
197        {
198            return _rootObject.InitializeAsync();
199        }
200
201        internal void OnObjectCreated(string guid, IChannelOwner result)
202        {
203            Objects.TryAdd(guid, result);
204        }
205
206        internal void Dispatch(PlaywrightServerMessage message)
207        {
208            if (message.Id.HasValue)
209            {
210                TraceMessage("pw:channel:response", message);
211
212                if (_callbacks.TryRemove(message.Id.Value, out var callback))
213                {
214                    if (message.Error != null)
215                    {
216                        callback.TaskCompletionSource.TrySetException(CreateException(message.Error.Error));
217                    }
218                    else
219                    {
220                        callback.TaskCompletionSource.TrySetResult(message.Result);
221                    }
222                }
223
224                return;
225            }
226
227            TraceMessage("pw:channel:event", message);
228
229            try
230            {
231                if (message.Method == "__create__")
232                {
233                    var createObjectInfo = message.Params.Value.ToObject<CreateObjectInfo>(DefaultJsonSerializerOptions);
234                    CreateRemoteObject(message.Guid, createObjectInfo.Type, createObjectInfo.Guid, createObjectInfo.Initializer);
235
236                    return;
237                }
238
239                if (message.Method == "__dispose__")
240                {
241                    Objects.TryGetValue(message.Guid, out var disableObject);
242                    disableObject?.DisposeOwner();
243                    return;
244                }
245
246                Objects.TryGetValue(message.Guid, out var obj);
247                obj?.Channel?.OnMessage(message.Method, message.Params);
248            }
249            catch (Exception ex)
250            {
251                DoClose(ex);
252            }
253        }
254
255        private void CreateRemoteObject(string parentGuid, ChannelOwnerType type, string guid, JsonElement? initializer)
256        {
257            IChannelOwner result = null;
258            var parent = string.IsNullOrEmpty(parentGuid) ? _rootObject : Objects[parentGuid];
259
260#pragma warning disable CA2000 // Dispose objects before losing scope
261            switch (type)
262            {
263                case ChannelOwnerType.Artifact:
264                    result = new Artifact(parent, guid, initializer?.ToObject<ArtifactInitializer>(DefaultJsonSerializerOptions));
265                    break;
266                case ChannelOwnerType.BindingCall:
267                    result = new BindingCall(parent, guid, initializer?.ToObject<BindingCallInitializer>(DefaultJsonSerializerOptions));
268                    break;
269                case ChannelOwnerType.Playwright:
270                    result = new PlaywrightImpl(parent, guid, initializer?.ToObject<PlaywrightInitializer>(DefaultJsonSerializerOptions));
271                    break;
272                case ChannelOwnerType.Browser:
273                    var browserInitializer = initializer?.ToObject<BrowserInitializer>(DefaultJsonSerializerOptions);
274                    result = new Browser(parent, guid, browserInitializer);
275                    break;
276                case ChannelOwnerType.BrowserType:
277                    var browserTypeInitializer = initializer?.ToObject<BrowserTypeInitializer>(DefaultJsonSerializerOptions);
278                    result = new Core.BrowserType(parent, guid, browserTypeInitializer);
279                    break;
280                case ChannelOwnerType.BrowserContext:
281                    var browserContextInitializer = initializer?.ToObject<BrowserContextInitializer>(DefaultJsonSerializerOptions);
282                    result = new BrowserContext(parent, guid, browserContextInitializer);
283                    break;
284                case ChannelOwnerType.ConsoleMessage:
285                    result = new ConsoleMessage(parent, guid, initializer?.ToObject<ConsoleMessageInitializer>(DefaultJsonSerializerOptions));
286                    break;
287                case ChannelOwnerType.Dialog:
288                    result = new Dialog(parent, guid, initializer?.ToObject<DialogInitializer>(DefaultJsonSerializerOptions));
289                    break;
290                case ChannelOwnerType.ElementHandle:
291                    result = new ElementHandle(parent, guid, initializer?.ToObject<ElementHandleInitializer>(DefaultJsonSerializerOptions));
292                    break;
293                case ChannelOwnerType.Frame:
294                    result = new Frame(parent, guid, initializer?.ToObject<FrameInitializer>(DefaultJsonSerializerOptions));
295                    break;
296                case ChannelOwnerType.JSHandle:
297                    result = new JSHandle(parent, guid, initializer?.ToObject<JSHandleInitializer>(DefaultJsonSerializerOptions));
298                    break;
299                case ChannelOwnerType.JsonPipe:
300                    result = new JsonPipe(parent, guid, initializer?.ToObject<JsonPipeInitializer>(DefaultJsonSerializerOptions));
301                    break;
302                case ChannelOwnerType.LocalUtils:
303                    result = new LocalUtils(parent, guid, initializer);
304                    break;
305                case ChannelOwnerType.Page:
306                    result = new Page(parent, guid, initializer?.ToObject<PageInitializer>(DefaultJsonSerializerOptions));
307                    break;
308                case ChannelOwnerType.Request:
309                    result = new Request(parent, guid, initializer?.ToObject<RequestInitializer>(DefaultJsonSerializerOptions));
310                    break;
311                case ChannelOwnerType.Response:
312                    result = new Response(parent, guid, initializer?.ToObject<ResponseInitializer>(DefaultJsonSerializerOptions));
313                    break;
314                case ChannelOwnerType.Route:
315                    result = new Route(parent, guid, initializer?.ToObject<RouteInitializer>(DefaultJsonSerializerOptions));
316                    break;
317                case ChannelOwnerType.Worker:
318                    result = new Worker(parent, guid, initializer?.ToObject<WorkerInitializer>(DefaultJsonSerializerOptions));
319                    break;
320                case ChannelOwnerType.WebSocket:
321                    result = new WebSocket(parent, guid, initializer?.ToObject<WebSocketInitializer>(DefaultJsonSerializerOptions));
322                    break;
323                case ChannelOwnerType.Selectors:
324                    result = new Selectors(parent, guid);
325                    break;
326                case ChannelOwnerType.SocksSupport:
327                    result = new SocksSupport(parent, guid);
328                    break;
329                case ChannelOwnerType.Stream:
330                    result = new Stream(parent, guid);
331                    break;
332                case ChannelOwnerType.WritableStream:
333                    result = new WritableStream(parent, guid);
334                    break;
335                case ChannelOwnerType.Tracing:
336                    result = new Tracing(parent, guid);
337                    break;
338                default:
339                    TraceMessage("pw:dotnet", "Missing type " + type);
340                    break;
341            }
342#pragma warning restore CA2000
343
344            Objects.TryAdd(guid, result);
345            OnObjectCreated(guid, result);
346        }
347
348        private void DoClose(Exception ex)
349        {
350            TraceMessage("pw:dotnet", $"Connection Close: {ex.Message}\n{ex.StackTrace}");
351            DoClose(ex.Message);
352        }
353
354        internal void DoClose(string reason)
355        {
356            _reason = string.IsNullOrEmpty(_reason) ? reason : _reason;
357            if (!IsClosed)
358            {
359                foreach (var callback in _callbacks)
360                {
361                    callback.Value.TaskCompletionSource.TrySetException(new PlaywrightException(reason));
362                }
363
364                Dispose();
365                IsClosed = true;
366            }
367        }
368
369        private Exception CreateException(PlaywrightServerError error)
370        {
371            if (string.IsNullOrEmpty(error.Message))
372            {
373                return new PlaywrightException(error.Value);
374            }
375
376            if (error.Name == "TimeoutError")
377            {
378                return new TimeoutException(error.Message);
379            }
380
381            return new PlaywrightException(error.Message);
382        }
383
384        private void Dispose(bool disposing)
385        {
386            if (!disposing)
387            {
388                return;
389            }
390
391            _queue.Dispose();
392            Close.Invoke(this, "Connection disposed");
393        }
394
395        [Conditional("DEBUG")]
396        internal void TraceMessage(string logLevel, object message)
397        {
398            string actualLogLevel = Environment.GetEnvironmentVariable("DEBUG");
399            if (!string.IsNullOrEmpty(actualLogLevel))
400            {
401                if (!actualLogLevel.Contains(logLevel))
402                {
403                    return;
404                }
405                if (!(message is string))
406                {
407                    message = JsonSerializer.Serialize(message, DefaultJsonSerializerOptions);
408                }
409                string line = $"{logLevel}: {message}";
410                Trace.WriteLine(line);
411                Console.Error.WriteLine(line);
412            }
413        }
414
415        internal async Task<T> WrapApiCallAsync<T>(Func<Task<T>> action, bool isInternal = false)
416        {
417            EnsureApiZoneExists();
418            if (ApiZone.Value[0] != null)
419            {
420                return await action().ConfigureAwait(false);
421            }
422            var st = new StackTrace(true);
423            var stack = new List<object>();
424            var lastInternalApiName = string.Empty;
425            var apiName = string.Empty;
426            for (int i = 0; i < st.FrameCount; ++i)
427            {
428                var sf = st.GetFrame(i);
429                string fileName = sf.GetFileName();
430                string cSharpNamespace = sf.GetMethod().ReflectedType?.Namespace;
431                bool playwrightInternal = cSharpNamespace != null &&
432                                          (cSharpNamespace == "Microsoft.Playwright" ||
433                                          cSharpNamespace.StartsWith("Microsoft.Playwright.Core", StringComparison.InvariantCultureIgnoreCase) ||
434                                          cSharpNamespace.StartsWith("Microsoft.Playwright.Transport", StringComparison.InvariantCultureIgnoreCase) ||
435                                          cSharpNamespace.StartsWith("Microsoft.Playwright.Helpers", StringComparison.InvariantCultureIgnoreCase));
436                if (string.IsNullOrEmpty(fileName) && !playwrightInternal)
437                {
438                    continue;
439                }
440
441                if (!playwrightInternal)
442                {
443                    stack.Add(new { file = fileName, line = sf.GetFileLineNumber(), column = sf.GetFileColumnNumber() });
444                }
445
446                string methodName = $"{sf?.GetMethod()?.DeclaringType?.Name}.{sf?.GetMethod()?.Name}";
447                if (methodName.Contains("WrapApiBoundaryAsync"))
448                {
449                    break;
450                }
451                if (methodName.StartsWith("<", StringComparison.InvariantCultureIgnoreCase))
452                {
453                    continue;
454                }
455                if (playwrightInternal)
456                {
457                    lastInternalApiName = methodName;
458                }
459                else if (!string.IsNullOrEmpty(lastInternalApiName))
460                {
461                    apiName = lastInternalApiName;
462                    lastInternalApiName = string.Empty;
463                }
464            }
465            if (string.IsNullOrEmpty(apiName))
466            {
467                apiName = lastInternalApiName;
468            }
469            try
470            {
471                if (!string.IsNullOrEmpty(apiName))
472                {
473                    ApiZone.Value[0] = new() { ApiName = apiName, Stack = stack, IsInternal = isInternal };
474                }
475                return await action().ConfigureAwait(false);
476            }
477            finally
478            {
479                ApiZone.Value[0] = null;
480            }
481        }
482
483        internal async Task WrapApiBoundaryAsync(Func<Task> action)
484        {
485            EnsureApiZoneExists();
486            try
487            {
488                ApiZone.Value.Insert(0, null);
489                await action().ConfigureAwait(false);
490            }
491            finally
492            {
493                ApiZone.Value.RemoveAt(0);
494            }
495        }
496
497        private void EnsureApiZoneExists()
498        {
499            if (ApiZone.Value == null)
500            {
501                ApiZone.Value = new() { null };
502            }
503        }
504    }
505}
506
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used methods in DialogInitializer

    No methods found for this class 😞

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)