How to use KeyJsonElementValueObject class of Microsoft.Playwright.Transport.Converters package

Best Playwright-dotnet code snippet using Microsoft.Playwright.Transport.Converters.KeyJsonElementValueObject

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

KeyJsonElementValueObject.cs

Source: KeyJsonElementValueObject.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.Text.Json;
26
27namespace Microsoft.Playwright.Transport.Converters
28{
29    internal class KeyJsonElementValueObject
30    {
31        public string K { get; set; }
32
33        public JsonElement V { get; set; }
34    }
35}
36
Full Screen

EvaluateArgumentValueConverter.cs

Source: EvaluateArgumentValueConverter.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;
26using System.Collections;
27using System.Collections.Generic;
28using System.ComponentModel;
29using System.Dynamic;
30using System.Globalization;
31using System.Linq;
32using System.Text.Json;
33using System.Text.Json.Serialization;
34using System.Text.RegularExpressions;
35using Microsoft.Playwright.Core;
36using Microsoft.Playwright.Helpers;
37using Microsoft.Playwright.Transport.Channels;
38
39namespace Microsoft.Playwright.Transport.Converters
40{
41    internal class EvaluateArgumentValueConverter<T> : JsonConverter<T>
42    {
43        private readonly List<object> _visited = new();
44
45        public List<EvaluateArgumentGuidElement> Handles { get; } = new();
46
47        public override bool CanConvert(Type type) => true;
48
49        public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
50        {
51            using JsonDocument document = JsonDocument.ParseValue(ref reader);
52            var result = document.RootElement;
53
54            return (T)ParseEvaluateResult(
55                result.ValueKind == JsonValueKind.Object && result.TryGetProperty("value", out var valueProperty)
56                    ? valueProperty
57                    : result,
58                typeof(T),
59                options);
60        }
61
62        public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
63        {
64        }
65
66        public object Serialize(object value)
67        {
68            if (_visited.Contains(value))
69            {
70                throw new JsonException("Argument is a circular structure");
71            }
72
73            if (value == null)
74            {
75                return new { v = "null" };
76            }
77
78            if (value is double nan && double.IsNaN(nan))
79            {
80                return new { v = "NaN" };
81            }
82
83            if (value is double infinity && double.IsPositiveInfinity(infinity))
84            {
85                return new { v = "Infinity" };
86            }
87
88            if (value is double negativeInfinity && double.IsNegativeInfinity(negativeInfinity))
89            {
90                return new { v = "-Infinity" };
91            }
92
93            if (value is double negativeZero && negativeZero.IsNegativeZero())
94            {
95                return new { v = "-0" };
96            }
97
98            if (value.GetType() == typeof(string))
99            {
100                return new { s = value };
101            }
102
103            if (value.GetType().IsEnum)
104            {
105                return new { n = (int)value };
106            }
107
108            if (
109                value.GetType() == typeof(int) ||
110                value.GetType() == typeof(decimal) ||
111                value.GetType() == typeof(long) ||
112                value.GetType() == typeof(short) ||
113                value.GetType() == typeof(double) ||
114                value.GetType() == typeof(int?) ||
115                value.GetType() == typeof(decimal?) ||
116                value.GetType() == typeof(long?) ||
117                value.GetType() == typeof(short?) ||
118                value.GetType() == typeof(double?))
119            {
120                return new { n = value };
121            }
122
123            if (value.GetType() == typeof(bool) || value.GetType() == typeof(bool?))
124            {
125                return new { b = value };
126            }
127
128            if (value is DateTime date)
129            {
130                return new { d = date.ToString("o", CultureInfo.InvariantCulture) };
131            }
132
133            if (value is Regex regex)
134            {
135                return new { r = new { p = regex.ToString(), f = regex.Options.GetInlineFlags() } };
136            }
137
138            if (value is IDictionary dictionary && dictionary.Keys.OfType<string>().Any())
139            {
140                _visited.Add(value);
141
142                var o = new List<object>();
143                foreach (object key in dictionary.Keys)
144                {
145                    object obj = dictionary[key];
146                    o.Add(new { k = key.ToString(), v = Serialize(obj) });
147                }
148
149                _visited.Remove(value);
150                return new { o = o };
151            }
152
153            if (value is IEnumerable array)
154            {
155                var a = new List<object>();
156                foreach (object item in array)
157                {
158                    a.Add(Serialize(item));
159                }
160
161                return new { a = a };
162            }
163
164            if (value is IChannelOwner channelOwner)
165            {
166                Handles.Add(new() { Guid = channelOwner.Channel.Guid });
167                return new { h = Handles.Count - 1 };
168            }
169
170            _visited.Add(value);
171
172            var entries = new List<object>();
173            foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(value))
174            {
175                object obj = propertyDescriptor.GetValue(value);
176                entries.Add(new { k = propertyDescriptor.Name, v = Serialize(obj) });
177            }
178
179            _visited.Remove(value);
180            return new { o = entries };
181        }
182
183        private static object ParseEvaluateResult(JsonElement result, Type t, JsonSerializerOptions options)
184        {
185            if (result.ValueKind == JsonValueKind.Object && result.TryGetProperty("v", out var value))
186            {
187                if (value.ValueKind == JsonValueKind.Null)
188                {
189                    return GetDefaultValue(t);
190                }
191
192                return value.ToString() switch
193                {
194                    "null" => GetDefaultValue(t),
195                    "undefined" => GetDefaultValue(t),
196                    "Infinity" => double.PositiveInfinity,
197                    "-Infinity" => double.NegativeInfinity,
198                    "-0" => -0d,
199                    "NaN" => double.NaN,
200                    _ => value.ToObject(t),
201                };
202            }
203
204            if (result.ValueKind == JsonValueKind.Object && result.TryGetProperty("d", out var date))
205            {
206                return date.ToObject<DateTime>();
207            }
208
209            if (result.ValueKind == JsonValueKind.Object && result.TryGetProperty("r", out var regex))
210            {
211                return new Regex(regex.GetProperty("p").ToString(), RegexOptionsExtensions.FromInlineFlags(regex.GetProperty("f").ToString()));
212            }
213
214            if (result.ValueKind == JsonValueKind.Object && result.TryGetProperty("b", out var boolean))
215            {
216                return boolean.ToObject(t);
217            }
218
219            if (result.ValueKind == JsonValueKind.Object && result.TryGetProperty("s", out var stringValue))
220            {
221                return stringValue.ToObject(t);
222            }
223
224            if (result.ValueKind == JsonValueKind.Object && result.TryGetProperty("n", out var numericValue))
225            {
226                return numericValue.ToObject(t);
227            }
228
229            if (result.ValueKind == JsonValueKind.Object && result.TryGetProperty("o", out var obj))
230            {
231                var keyValues = obj.ToObject<KeyJsonElementValueObject[]>();
232
233                if (t == typeof(JsonElement) || t == typeof(JsonElement?) || t == typeof(ExpandoObject) || t == typeof(object))
234                {
235                    var dynamicResult = new ExpandoObject();
236                    IDictionary<string, object> dicResult;
237
238                    if (typeof(T) == typeof(ExpandoObject) || typeof(T) == typeof(object))
239                    {
240                        dicResult = dynamicResult;
241                    }
242                    else
243                    {
244                        dicResult = new Dictionary<string, object>();
245                    }
246
247                    foreach (var kv in keyValues)
248                    {
249                        var serializerOptions = JsonExtensions.GetNewDefaultSerializerOptions();
250                        var type = ValueKindToType(kv.V);
251
252                        serializerOptions.Converters.Add(GetNewConverter(type));
253                        dicResult[kv.K] = kv.V.ToObject(type, serializerOptions);
254                    }
255
256                    if (typeof(T) == typeof(ExpandoObject) || typeof(T) == typeof(object))
257                    {
258                        return dynamicResult;
259                    }
260
261                    var defaultConverter = JsonExtensions.GetNewDefaultSerializerOptions();
262                    string serialized = JsonSerializer.Serialize(dicResult, defaultConverter);
263
264                    var retValue = JsonSerializer.Deserialize<T>(serialized, defaultConverter);
265
266                    // This particular check & clone call is required because otherwise, when we attempt to
267                    // access the value, we run into an Object Disposed Exception.
268                    // See: https://github.com/microsoft/playwright-dotnet/issues/1706
269                    if (retValue is JsonElement retValueAsJson)
270                    {
271                        return retValueAsJson.Clone();
272                    }
273                }
274
275                try
276                {
277                    object objResult = Activator.CreateInstance(t);
278
279                    foreach (var kv in keyValues)
280                    {
281                        var serializerOptions = JsonExtensions.GetNewDefaultSerializerOptions();
282
283                        var property = t.GetProperties().FirstOrDefault(prop => string.Equals(prop.Name, kv.K, StringComparison.OrdinalIgnoreCase));
284                        serializerOptions.Converters.Add(GetNewConverter(property.PropertyType));
285                        property.SetValue(objResult, kv.V.ToObject(property.PropertyType, serializerOptions));
286                    }
287
288                    return objResult;
289                }
290                catch (Exception)
291                {
292                    return null;
293                }
294            }
295
296            if (result.ValueKind == JsonValueKind.Object && result.TryGetProperty("v", out var vNull) && vNull.ValueKind == JsonValueKind.Null)
297            {
298                return GetDefaultValue(t);
299            }
300
301            if (result.ValueKind == JsonValueKind.Object && result.TryGetProperty("a", out var array) && array.ValueKind == JsonValueKind.Array)
302            {
303                if (t == typeof(ExpandoObject) || t == typeof(object))
304                {
305                    return ReadList(array, options);
306                }
307
308                return array.ToObject(t, options);
309            }
310
311            if (t == typeof(JsonElement?))
312            {
313                // we need to make sure that the returned instance *is not* dependent on the
314                // lifecycle of JsonDocument, hence we Clone it
315                return result.Clone();
316            }
317
318            if (result.ValueKind == JsonValueKind.Array)
319            {
320                var elementType = t.GetElementType();
321                var serializerOptions = JsonExtensions.GetNewDefaultSerializerOptions();
322                serializerOptions.Converters.Add(GetNewConverter(elementType));
323
324                var resultArray = Array.CreateInstance(elementType, result.GetArrayLength());
325                var i = 0;
326                foreach (var item in result.EnumerateArray())
327                {
328                    resultArray.SetValue(ParseEvaluateResult(item, elementType, serializerOptions), i++);
329                }
330
331                return resultArray;
332            }
333
334            return result.ToObject(t);
335        }
336
337        private static object GetDefaultValue(Type t)
338        {
339            if (t.IsValueType)
340            {
341                return Activator.CreateInstance(t);
342            }
343
344            return null;
345        }
346
347        private static JsonConverter GetNewConverter(Type type)
348        {
349            var converter = typeof(EvaluateArgumentValueConverter<>);
350            Type[] typeArgs = { type };
351            var makeme = converter.MakeGenericType(typeArgs);
352            return (JsonConverter)Activator.CreateInstance(makeme);
353        }
354
355        private static Type ValueKindToType(JsonElement element)
356        {
357            if (element.ValueKind == JsonValueKind.Object)
358            {
359                if (element.TryGetProperty("d", out _))
360                {
361                    return typeof(DateTime);
362                }
363
364                if (element.TryGetProperty("b", out _))
365                {
366                    return typeof(bool);
367                }
368
369                if (element.TryGetProperty("s", out _))
370                {
371                    return typeof(string);
372                }
373
374                if (element.TryGetProperty("n", out _))
375                {
376                    return typeof(decimal);
377                }
378
379                if (
380                    element.TryGetProperty("v", out var number) &&
381                    (number.ToString() == "Infinity" || number.ToString() == "-Infinity" || number.ToString() == "-0" || number.ToString() == "NaN"))
382                {
383                    return typeof(double);
384                }
385            }
386
387            return element.ValueKind switch
388            {
389                JsonValueKind.Array => typeof(Array),
390                JsonValueKind.String => typeof(string),
391                JsonValueKind.Number => decimal.Truncate(element.ToObject<decimal>()) != element.ToObject<decimal>() ? typeof(decimal) : typeof(int),
392                JsonValueKind.True => typeof(bool),
393                JsonValueKind.False => typeof(bool),
394                _ => typeof(object),
395            };
396        }
397
398        private static object ReadList(JsonElement jsonElement, JsonSerializerOptions options)
399        {
400            IList<object> list = new List<object>();
401            foreach (var item in jsonElement.EnumerateArray())
402            {
403                list.Add(ParseEvaluateResult(item, ValueKindToType(item), options));
404            }
405
406            return list.Count == 0 ? null : list;
407        }
408
409        private static object ReadObject(JsonElement jsonElement, JsonSerializerOptions options)
410        {
411            IDictionary<string, object> expandoObject = new ExpandoObject();
412            foreach (var obj in jsonElement.EnumerateObject())
413            {
414                expandoObject[obj.Name] = ParseEvaluateResult(obj.Value, ValueKindToType(obj.Value), options);
415            }
416
417            return expandoObject;
418        }
419    }
420}
421
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 KeyJsonElementValueObject

    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)