How to use CountAsync method of Microsoft.Playwright.Core.Locator class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.Locator.CountAsync

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

BotCore.cs

Source: BotCore.cs Github

copy
1using System;
2using System.Collections.Concurrent;
3using System.Collections.Generic;
4using System.Diagnostics;
5using System.IO;
6using System.Linq;
7using System.Text;
8using System.Threading;
9using BotCore.Dto;
10using Microsoft.Playwright;
11using Newtonsoft.Json;
12
13namespace BotCore;
14
15public class Core
16{
17    private static readonly ConcurrentQueue<IBrowser> Browsers = new();
18
19    private static readonly Random _random = new();
20
21    public static string ZipDirectory = string.Empty;
22
23    public static string StreamUrl = string.Empty;
24
25    public static bool Headless;
26
27    public static int BrowserLimit;
28
29    private readonly JsonSerializerSettings _isoDateFormatSettings = new()
30    {
31        DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
32        DateParseHandling = DateParseHandling.DateTime
33    };
34
35    private readonly object _lockObject = new();
36
37    private readonly string _loginCookiesPath =
38        Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data", "loginCookies.json");
39
40    private readonly ConcurrentBag<string> _chatMessages = new();
41
42    private StreamReader _file;
43
44    private bool _firstPage = true;
45
46    private List<Process> _initialChromeProcesses = new();
47
48    private IPlaywright _playwright;
49
50    private int _refreshInterval;
51
52    private bool _useLowCpuRam;
53
54    public Action AllBrowsersTerminated;
55
56    public bool CanRun = true;
57
58    public Action DecreaseViewer;
59
60    public Action DidItsJob;
61
62    public Action IncreaseViewer;
63
64    public Action<Exception> InitializationError;
65
66    public Action<string> LiveViewer;
67
68    public Action<Exception> LogMessage;
69
70    public string PreferredQuality;
71
72    public void Start(ExecuteNeedsDto executeNeeds)
73    {
74        if (executeNeeds.UseLowCpuRam)
75            executeNeeds.RefreshInterval = 1;
76
77        if (_playwright != null)
78            _playwright.Dispose();
79
80        _playwright = Playwright.CreateAsync().GetAwaiter().GetResult();
81
82        BrowserLimit = executeNeeds.BrowserLimit;
83        CanRun = true;
84        _firstPage = true;
85        _useLowCpuRam = executeNeeds.UseLowCpuRam;
86        Headless = executeNeeds.Headless;
87        PreferredQuality = executeNeeds.PreferredQuality;
88        _refreshInterval = executeNeeds.RefreshInterval;
89        var i = 0;
90        StreamUrl = executeNeeds.Stream;
91        
92        var executeNeedsChatMessages = executeNeeds.ChatMessages;
93        Shuffle(ref executeNeedsChatMessages);
94        foreach (var item in executeNeedsChatMessages) _chatMessages.Add(item);
95
96        if (BrowserLimit > 0)
97        {
98            var thr = new Thread(LoopWithLimit);
99            thr.Start();
100        }
101        
102        _initialChromeProcesses = Process.GetProcessesByName("chrome").ToList();
103
104        do
105        {
106            try
107            {
108                _file = new StreamReader(executeNeeds.ProxyListDirectory);
109
110                string line;
111
112                while (CanRun && (line = _file.ReadLine()) != null)
113                {
114                    line = line.Replace(" ", "");
115
116                    if (string.IsNullOrEmpty(line))
117                        continue;
118
119                    var array = line.Split(':');
120
121                    var proxy = new Proxy
122                    {
123                        Server = "http://" + array[0] + ":" + array[1],
124                        Username = array[2],
125                        Password = array[3]
126                    };
127
128                    var thr = new Thread(Request) {Priority = ThreadPriority.AboveNormal};
129                    var r = new Random();
130                    var rInt = r.Next(5000, 8000);
131
132                    while (BrowserLimit > 0 && Browsers.Count >= BrowserLimit) Thread.Sleep(1000);
133
134                    if (!CanRun)
135                        continue;
136
137                    executeNeeds.LoginInfos.TryDequeue(out var loginInfo);
138
139                    thr.Start(new SessionConfigurationDto
140                    {
141                        Url = line,
142                        Count = i,
143                        PreferredQuality = executeNeeds.PreferredQuality,
144                        LoginInfo = loginInfo,
145                        Service = executeNeeds.Service,
146                        Proxy = proxy
147                    });
148
149                    i++;
150
151                    Thread.Sleep(BrowserLimit == 0 ? rInt : 1000);
152                }
153
154                _file.Close();
155            }
156            catch (Exception e)
157            {
158                InitializationError?.Invoke(e is IndexOutOfRangeException
159                    ? new Exception("Please select a valid proxy file.")
160                    : e);
161            }
162
163            if (!CanRun)
164                break;
165        } while (executeNeeds.BrowserLimit > 0);
166
167        DidItsJob?.Invoke();
168    }
169
170    private void Shuffle(ref List<string> list)
171    {
172        var n = list.Count;
173        while (n > 1)
174        {
175            n--;
176            var k = _random.Next(n + 1);
177            (list[k], list[n]) = (list[n], list[k]);
178        }
179    }
180
181    private void StoreCookie(Tuple<string, List<BrowserContextCookiesResult>> cookie)
182    {
183        var myCookie = new List<MyCookie>();
184
185        foreach (var item in cookie.Item2)
186            myCookie.Add(new MyCookie
187            {
188                Domain = item.Domain,
189                Expiry = item.Expires,
190                HttpOnly = Convert.ToBoolean(item.HttpOnly),
191                Name = item.Name,
192                Path = item.Path,
193                Value = item.Value,
194                Secure = Convert.ToBoolean(item.Secure)
195            });
196
197        lock (_lockObject)
198        {
199            if (!File.Exists(_loginCookiesPath))
200            {
201                var item = new Dictionary<string, List<MyCookie>> {{cookie.Item1, myCookie}};
202                File.WriteAllText(_loginCookiesPath, JsonConvert.SerializeObject(item), Encoding.UTF8);
203                return;
204            }
205
206            var readCookiesJson = File.ReadAllText(_loginCookiesPath);
207            var readCookies = JsonConvert.DeserializeObject<Dictionary<string, List<MyCookie>>>(readCookiesJson);
208
209            readCookies.TryGetValue(cookie.Item1, out var value);
210
211            if (value?.Count > 0)
212                readCookies[cookie.Item1] = myCookie;
213            else
214                readCookies.Add(cookie.Item1, myCookie);
215
216
217            File.WriteAllText(_loginCookiesPath, JsonConvert.SerializeObject(readCookies), Encoding.UTF8);
218        }
219    }
220
221    private List<MyCookie> GetCookie(string username)
222    {
223        lock (_lockObject)
224        {
225            if (!File.Exists(_loginCookiesPath)) return new List<MyCookie>();
226
227            var readCookiesJson = File.ReadAllText(_loginCookiesPath);
228            var readCookies = JsonConvert.DeserializeObject<Dictionary<string, List<MyCookie>>>(readCookiesJson);
229
230            return readCookies.FirstOrDefault(x => x.Key == username).Value;
231        }
232    }
233
234    private void KillAllProcesses()
235    {
236        var allChromeProcesses = Process.GetProcessesByName("chrome");
237
238        foreach (var process in allChromeProcesses)
239            if (_initialChromeProcesses.All(x => x.Id != process.Id))
240            {
241                var startInfo = new ProcessStartInfo
242                {
243                    CreateNoWindow = true,
244                    FileName = "CMD.exe"
245                };
246                var strCmd = $"/C taskkill /F /PID {process.Id}";
247                startInfo.Arguments = strCmd;
248                var processTemp = new Process();
249                processTemp.StartInfo = startInfo;
250                processTemp.Start();
251            }
252
253        _initialChromeProcesses.Clear();
254
255        var allChromeDriverProcesses = Process.GetProcessesByName("chromedriver");
256
257        foreach (var chromeDriverService in allChromeDriverProcesses)
258            try
259            {
260                chromeDriverService.Kill();
261            }
262            catch (Exception)
263            {
264                //ignored
265            }
266    }
267
268    public void Stop()
269    {
270        CanRun = false;
271
272        _file?.Close();
273
274        KillAllProcesses();
275        
276        Browsers.Clear();
277
278        AllBrowsersTerminated?.Invoke();
279    }
280
281    private void LoopWithLimit()
282    {
283        while (CanRun)
284            try
285            {
286                if (Browsers.Count >= BrowserLimit)
287                {
288                    KillAllProcesses();
289                    Browsers.Clear();
290                }
291
292                Thread.Sleep(500);
293            }
294            catch (Exception)
295            {
296                //ignored
297            }
298    }
299
300    private void Request(object obj)
301    {
302        try
303        {
304            var r = new Random();
305            var itm = (SessionConfigurationDto) obj;
306            var array = itm.Url.Split(':');
307
308            var args = new List<string>();
309
310            string[] resolutions =
311                {"1480,900", "1550,790", "1600,900", "1920,1080", "1480,768", "1780,940"};
312
313            var browserLaunchOptions = new BrowserTypeLaunchOptions()
314            {
315                Headless = false,
316                Channel = "chrome",
317                Timeout = 120000,
318                Proxy = itm.Proxy
319            };
320
321            if (_useLowCpuRam)
322            {
323                args.Add("--disable-extensions-except=" + AppDomain.CurrentDomain.BaseDirectory +
324                         "\\Extensions\\TwitchAlternative.crx");
325                args.Add("--load-extension=" + AppDomain.CurrentDomain.BaseDirectory +
326                         "\\Extensions\\TwitchAlternative.crx");
327            }
328
329            if (Headless) browserLaunchOptions.Headless = true;
330
331            var localChrome = AppDomain.CurrentDomain.BaseDirectory + "\\Extensions\\LocalChrome\\chrome.exe";
332            if (File.Exists(localChrome)) browserLaunchOptions.ExecutablePath = localChrome;
333
334            args.Add("--mute-audio");
335
336            args.Add("--enable-automation");
337
338            args.Add("--useAutomationExtension=false");
339
340            browserLaunchOptions.Args = args;
341
342            var browser = _playwright.Chromium.LaunchAsync(browserLaunchOptions).GetAwaiter().GetResult();
343
344            var page = browser.NewPageAsync(new BrowserNewPageOptions()
345            {
346                ViewportSize = new ViewportSize
347                {
348                    Width = Convert.ToInt32(resolutions[r.Next(0, resolutions.Length - 1)].Split(',')[0]),
349                    Height = Convert.ToInt32(resolutions[r.Next(0, resolutions.Length - 1)].Split(',')[1])
350                },
351                UserAgent =
352                    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36",
353                Geolocation = new Geolocation() {Latitude = r.Next(-90, 90), Longitude = r.Next(-180, 180)},
354            }).GetAwaiter().GetResult();
355
356            page.GotoAsync(StreamUrl, new PageGotoOptions() {Timeout = 120000, WaitUntil = WaitUntilState.Load})
357                .GetAwaiter().GetResult();
358
359            if (BrowserLimit > 0)
360            {
361                Thread.Sleep(1000);
362
363                return;
364            }
365
366            Browsers.Enqueue(browser);
367
368            IncreaseViewer?.Invoke();
369
370            var firstPage = false;
371
372            var startDate = DateTime.Now;
373
374            var messageStartDate = DateTime.Now;
375
376            var messageInterval = _random.Next(1, 10);
377
378            if (itm.Service == StreamService.Service.Twitch)
379            {
380                if (!Headless && !_useLowCpuRam)
381                    try
382                    {
383                        page.EvaluateAsync("window.localStorage.setItem('video-quality', '" + itm.PreferredQuality +
384                                           "');");
385                        page.ReloadAsync().GetAwaiter().GetResult();
386                    }
387                    catch (Exception)
388                    {
389                        //ignored
390                    }
391
392                var matureClicked = false;
393                var matureCheckCount = 0;
394                var cacheClicked = false;
395                var cacheCheckCount = 0;
396                if (itm.LoginInfo != null)
397                {
398                    Thread.Sleep(1000);
399
400                    var allCookies = GetCookie(itm.LoginInfo.Username);
401
402                    if (allCookies != null)
403                        foreach (var cookie in allCookies)
404                        {
405                            Cookie[] cookies =
406                            {
407                                new()
408                                {
409                                    Domain = cookie.Domain, Expires = cookie.Expiry, Name = cookie.Name,
410                                    Path = cookie.Path, Secure = cookie.Secure, Url = cookie.Path,
411                                    HttpOnly = cookie.HttpOnly, Value = cookie.Value
412                                }
413                            };
414
415                            page.Context.AddCookiesAsync(cookies);
416                        }
417
418                    try
419                    {
420                        var loginButton =
421                            page.Locator(
422                                "xpath=/html/body/div[1]/div/div[2]/nav/div/div[3]/div[3]/div/div[1]/div[1]/button/div/div");
423
424                        if (loginButton.CountAsync().GetAwaiter().GetResult() > 0)
425                        {
426                            Click(ref loginButton);
427
428                            Thread.Sleep(1000);
429
430                            var usernameBox =
431                                page.Locator(
432                                    "xpath=/html/body/div[3]/div/div/div/div/div/div[1]/div/div/div[3]/form/div/div[1]/div/div[2]/input");
433
434                            if (usernameBox.CountAsync().GetAwaiter().GetResult() > 0)
435                            {
436                                Click(ref usernameBox);
437
438                                Thread.Sleep(1000);
439
440                                usernameBox.TypeAsync(itm.LoginInfo.Username).GetAwaiter().GetResult();
441
442                                var passwordBox =
443                                    page.Locator(
444                                        "xpath=/html/body/div[3]/div/div/div/div/div/div[1]/div/div/div[3]/form/div/div[2]/div/div[1]/div[2]/div[1]/input");
445
446                                if (passwordBox.CountAsync().GetAwaiter().GetResult() > 0)
447                                {
448                                    Click(ref passwordBox);
449
450                                    Thread.Sleep(1000);
451
452                                    passwordBox.TypeAsync(itm.LoginInfo.Password).GetAwaiter().GetResult();
453
454                                    Thread.Sleep(1000);
455
456                                    var login = page.Locator(
457                                        "xpath=/html/body/div[3]/div/div/div/div/div/div[1]/div/div/div[3]/form/div/div[3]/button/div/div");
458
459                                    Thread.Sleep(1000);
460
461                                    if (login.CountAsync().GetAwaiter().GetResult() > 0)
462                                        Click(ref login);
463                                }
464                            }
465                        }
466                    }
467                    catch (Exception ex)
468                    {
469                        LogMessage?.Invoke(new Exception($"Login failed: {ex.Message}"));
470                    }
471
472                    while (true)
473                    {
474                        Thread.Sleep(1000);
475
476                        var cookie = page.Context.CookiesAsync().GetAwaiter().GetResult()
477                            .Any(x => x.Name == "auth-token");
478
479                        if (cookie)
480                        {
481                            StoreCookie(new Tuple<string, List<BrowserContextCookiesResult>>(itm.LoginInfo.Username,
482                                new List<BrowserContextCookiesResult>(page.Context.CookiesAsync().GetAwaiter()
483                                    .GetResult().ToArray())));
484
485                            break;
486                        }
487                    }
488                }
489
490                while (true)
491                {
492                    try
493                    {
494                        if (_firstPage)
495                        {
496                            firstPage = true;
497                            _firstPage = false;
498                        }
499
500                        if (firstPage)
501                        {
502                            var liveViewers =
503                                page.Locator(
504                                    "xpath=/html/body/div[1]/div/div[2]/div[1]/main/div[2]/div[3]/div/div/div[1]/div[1]/div[2]/div/div[1]/div/div/div/div[2]/div[2]/div[2]/div/div/div[1]/div[1]/div/p/span");
505
506                            if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)
507                            {
508                                LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult());
509                                Thread.Sleep(5000);
510                            }
511                        }
512                    }
513                    catch (Exception)
514                    {
515                        LiveViewer.Invoke("N/A");
516                    }
517
518                    Thread.Sleep(1000);
519
520                    try
521                    {
522                        var connectionError =
523                            page.Locator(
524                                "xpath=/html/body/div[1]/div/div[2]/div[1]/main/div[2]/div[3]/div/div/div[2]/div/div[2]/div/div/div/div/div[7]/div/div[3]/button/div/div[2]");
525
526                        if (connectionError.CountAsync().GetAwaiter().GetResult() > 0)
527                            connectionError.ClickAsync().GetAwaiter().GetResult();
528                    }
529                    catch (Exception)
530                    {
531                        //ignored
532                    }
533                    
534                    try
535                    {
536                        if (!matureClicked && matureCheckCount < 5)
537                            try
538                            {
539                                var mature =
540                                    page.Locator(
541                                        "xpath=/html/body/div[1]/div/div[2]/div[1]/main/div[2]/div[3]/div/div/div[2]/div/div[2]/div/div/div/div/div[5]/div/div[3]/button/div/div");
542
543                                if (mature.CountAsync().GetAwaiter().GetResult() > 0)
544                                {
545                                    Click(ref mature);
546                                    matureClicked = true;
547                                    matureCheckCount++;
548                                }
549                            }
550                            catch
551                            {
552                                //ignored because there is no mature button
553                            }
554                    }
555                    catch (Exception)
556                    {
557                        // ignored
558                    }
559
560                    try
561                    {
562                        if (!cacheClicked && cacheCheckCount < 5)
563                            try
564                            {
565                                var cache = page.Locator(
566                                    "xpath=/html/body/div[1]/div/div[2]/div[1]/div/div/div[3]/button/div/div/div");
567
568                                if (cache.CountAsync().GetAwaiter().GetResult() > 0)
569                                {
570                                    Click(ref cache);
571                                    cacheClicked = true;
572                                }
573
574                                cacheCheckCount++;
575                            }
576                            catch (Exception)
577                            {
578                                //ignored because there is no cache button
579                            }
580                    }
581                    catch (Exception)
582                    {
583                        // ignored
584                    }
585
586                    try
587                    {
588                        if (_refreshInterval != 0 &&
589                            DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))
590                        {
591                            page.ReloadAsync().GetAwaiter().GetResult();
592
593                            startDate = DateTime.Now;
594                        }
595                    }
596                    catch (Exception)
597                    {
598                        //ignored
599                    }
600
601                    try
602                    {
603                        if (messageInterval != 0 &&
604                            DateTime.Now - messageStartDate > TimeSpan.FromMinutes(messageInterval) &&
605                            itm.LoginInfo != null)
606                        {
607                            SendMessage();
608
609                            messageStartDate = DateTime.Now;
610                        }
611                    }
612                    catch (Exception)
613                    {
614                        //ignored
615                    }
616                }
617
618                void SendMessage()
619                {
620                    try
621                    {
622                        var chatBox = page.WaitForSelectorAsync(".chat-wysiwyg-input__editor").GetAwaiter()
623                            .GetResult();
624
625                        if (_chatMessages.TryTake(out var message))
626                        {
627                            chatBox?.TypeAsync(message).GetAwaiter().GetResult();
628                            page.Keyboard.PressAsync("Enter").GetAwaiter().GetResult();
629                        }
630                    }
631                    catch (Exception)
632                    {
633                        //ignored  
634                    }
635                }
636            }
637
638            if (itm.Service == StreamService.Service.Youtube)
639            {
640                Thread.Sleep(3000);
641
642                try
643                {
644                    var play = page.Locator(
645                        "xpath=/html/body/ytd-app/div/ytd-page-manager/ytd-watch-flexy/div[5]/div[1]/div/div[1]/div/div/div/ytd-player/div/div/div[5]/button");
646
647                    play?.ClickAsync().GetAwaiter().GetResult();
648                }
649                catch (Exception)
650                {
651                    //ignored
652                }
653
654                while (true)
655                {
656                    try
657                    {
658                        if (_firstPage)
659                        {
660                            firstPage = true;
661                            _firstPage = false;
662                        }
663
664                        if (firstPage)
665                        {
666                            var liveViewers = page.Locator(
667                                "xpath=/html/body/ytd-app/div/ytd-page-manager/ytd-watch-flexy/div[5]/div[1]/div/div[6]/div[2]/ytd-video-primary-info-renderer/div/div/div[1]/div[1]/ytd-video-view-count-renderer/span[1]");
668
669                            if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)
670                            {
671                                LiveViewer.Invoke(
672                                    liveViewers.InnerTextAsync().GetAwaiter().GetResult().Split(' ')[0]);
673                                Thread.Sleep(5000);
674                            }
675                        }
676                    }
677                    catch (Exception)
678                    {
679                        LiveViewer.Invoke("N/A");
680                    }
681
682                    try
683                    {
684                        if (_refreshInterval != 0 &&
685                            DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))
686                        {
687                            page.ReloadAsync().GetAwaiter().GetResult();
688
689                            startDate = DateTime.Now;
690                        }
691                    }
692                    catch
693                    {
694                        //ignored
695                    }
696                }
697            }
698
699            if (itm.Service == StreamService.Service.DLive)
700            {
701                Thread.Sleep(3000);
702
703                var isPlaying = false;
704
705                while (true)
706                {
707                    try
708                    {
709                        if (_firstPage)
710                        {
711                            firstPage = true;
712                            _firstPage = false;
713                        }
714
715                        if (firstPage)
716                        {
717                            try
718                            {
719                                var liveViewers =
720                                    page.Locator(
721                                        "xpath=/html/body/div/div[1]/div[20]/div[2]/div/div[2]/div/div/div/div[1]/div/div[1]/div[3]/div/div[1]/div/div[2]/div[2]");
722
723                                if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)
724                                {
725                                    LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult()
726                                        .Split(" ")[0]);
727                                    Thread.Sleep(5000);
728                                }
729                            }
730                            catch (Exception)
731                            {
732                                //ignored
733                            }
734
735                            try
736                            {
737                                var liveViewers =
738                                    page.Locator(
739                                        "xpath=/html/body/div/div[1]/div[18]/div[2]/div/div/div/div/div/div/div/div/div[3]/div/div[3]/div/div/div[1]/div/div[1]/div[2]/div/div[1]/span");
740
741                                if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)
742                                {
743                                    LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult());
744                                    Thread.Sleep(5000);
745                                }
746                            }
747                            catch (Exception)
748                            {
749                                //ignored
750                            }
751                        }
752
753                        if (!isPlaying)
754                        {
755                            var play = page.Locator(
756                                "xpath=/html/body/div/div[1]/div[14]/div[2]/div/div[2]/div/div/div/div/div/div/div[1]/div/div/div/div/div[4]/div[2]/button/svg");
757
758                            if (play.CountAsync().GetAwaiter().GetResult() > 0)
759                            {
760                                Click(ref play);
761                                isPlaying = true;
762                            }
763                        }
764
765                        Thread.Sleep(1000);
766                    }
767                    catch (Exception)
768                    {
769                        //ignored
770                    }
771
772                    try
773                    {
774                        if (_refreshInterval != 0 &&
775                            DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))
776                        {
777                            page.ReloadAsync().GetAwaiter().GetResult();
778                            isPlaying = false;
779                            startDate = DateTime.Now;
780                        }
781                    }
782                    catch (Exception)
783                    {
784                        //ignored
785                    }
786                }
787            }
788
789            if (itm.Service == StreamService.Service.NimoTv)
790            {
791                Thread.Sleep(3000);
792
793                var isPlaying = false;
794
795                if (itm.LoginInfo != null)
796                {
797                    Thread.Sleep(1000);
798
799                    var allCookies = GetCookie(itm.LoginInfo.Username);
800
801                    if (allCookies != null)
802                        foreach (var cookie in allCookies)
803                        {
804                            Cookie[] cookies =
805                            {
806                                new()
807                                {
808                                    Domain = cookie.Domain, Expires = cookie.Expiry, Name = cookie.Name,
809                                    Path = cookie.Path, Secure = cookie.Secure, Url = cookie.Path,
810                                    HttpOnly = cookie.HttpOnly, Value = cookie.Value
811                                }
812                            };
813
814                            page.Context.AddCookiesAsync(cookies);
815                        }
816
817                    try
818                    {
819                        var loginButton =
820                            page.Locator("xpath=/html/body/div[2]/div[1]/div/div[2]/div/div[2]/button");
821
822                        if (loginButton.CountAsync().GetAwaiter().GetResult() > 0)
823                        {
824                            Click(ref loginButton);
825
826                            Thread.Sleep(1000);
827
828                            var usernameBox =
829                                page.Locator(
830                                    "xpath=/html/body/div[6]/div/div[2]/div/div[2]/div/div/div[3]/div[1]/div[2]/input");
831
832                            if (usernameBox.CountAsync().GetAwaiter().GetResult() > 0)
833                            {
834                                Click(ref usernameBox);
835
836                                Thread.Sleep(1000);
837
838                                usernameBox.TypeAsync(itm.LoginInfo.Username.Split('/')[1]).GetAwaiter()
839                                    .GetResult();
840
841                                var countryCodeArrow =
842                                    page.Locator(
843                                        "xpath=/html/body/div[6]/div/div[2]/div/div[2]/div/div/div[3]/div[1]/div[2]/div[1]");
844
845                                if (countryCodeArrow.CountAsync().GetAwaiter().GetResult() > 0)
846                                {
847                                    Click(ref countryCodeArrow);
848
849                                    Thread.Sleep(1000);
850
851                                    var searchCountryCode =
852                                        page.Locator(
853                                            "xpath=/html/body/div[6]/div/div[2]/div/div[4]/div/div/div/div[1]/input");
854
855                                    if (searchCountryCode.CountAsync().GetAwaiter().GetResult() > 0)
856                                    {
857                                        searchCountryCode.TypeAsync(itm.LoginInfo.Username.Split('/')[0]
858                                            .Replace("+", string.Empty)).GetAwaiter().GetResult();
859
860                                        Thread.Sleep(1000);
861
862                                        var firstElement =
863                                            page.Locator(
864                                                "xpath=/html/body/div[6]/div/div[2]/div/div[4]/div/div/div/div[2]/div[1]/div[2]");
865
866                                        if (firstElement.CountAsync().GetAwaiter().GetResult() > 0)
867                                            Click(ref firstElement);
868                                    }
869                                }
870
871                                var passwordBox =
872                                    page.Locator(
873                                        "xpath=/html/body/div[6]/div/div[2]/div/div[2]/div/div/div[3]/div[1]/div[3]/input");
874
875                                if (passwordBox.CountAsync().GetAwaiter().GetResult() > 0)
876                                {
877                                    Click(ref passwordBox);
878
879                                    Thread.Sleep(1000);
880
881                                    passwordBox.TypeAsync(itm.LoginInfo.Password).GetAwaiter().GetResult();
882
883                                    Thread.Sleep(1000);
884
885                                    var login = page.Locator(
886                                        "xpath=/html/body/div[6]/div/div[2]/div/div[2]/div/div/div[3]/div[1]/button");
887
888
889                                    Thread.Sleep(1000);
890
891                                    if (login.CountAsync().GetAwaiter().GetResult() > 0)
892                                        Click(ref login);
893                                }
894                            }
895                        }
896                    }
897                    catch (Exception ex)
898                    {
899                        LogMessage?.Invoke(new Exception($"Login failed: {ex.Message}"));
900                    }
901
902                    while (true)
903                    {
904                        Thread.Sleep(1000);
905
906                        var cookie = page.Context.CookiesAsync().GetAwaiter().GetResult()
907                            .Any(x => x.Name == "userName");
908
909                        if (cookie)
910                        {
911                            StoreCookie(new Tuple<string, List<BrowserContextCookiesResult>>(itm.LoginInfo.Username,
912                                new List<BrowserContextCookiesResult>(page.Context.CookiesAsync().GetAwaiter()
913                                    .GetResult().ToArray())));
914
915                            break;
916                        }
917                    }
918                }
919
920                while (true)
921                {
922                    try
923                    {
924                        if (_firstPage)
925                        {
926                            firstPage = true;
927                            _firstPage = false;
928                        }
929
930                        if (firstPage)
931                        {
932                            var liveViewers =
933                                page.Locator(
934                                    "xpath=/html/body/div[2]/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/div[1]/div[1]/div/div[2]/div[3]/span");
935
936                            if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)
937                            {
938                                LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult());
939                                Thread.Sleep(5000);
940                            }
941                        }
942                    }
943                    catch (Exception)
944                    {
945                        LiveViewer.Invoke("N/A");
946                    }
947
948                    try
949                    {
950                        if (!isPlaying)
951                        {
952                            var play = page.Locator(
953                                "xpath=/html/body/div[2]/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/div[1]/div[2]/div[1]/div[2]/div/span");
954
955                            if (play.CountAsync().GetAwaiter().GetResult() > 0)
956                            {
957                                Click(ref play);
958                                isPlaying = true;
959                            }
960                        }
961                    }
962                    catch (Exception)
963                    {
964                        //ignored
965                    }
966
967                    try
968                    {
969                        if (_refreshInterval != 0 &&
970                            DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))
971                        {
972                            page.ReloadAsync().GetAwaiter().GetResult();
973                            isPlaying = false;
974                            startDate = DateTime.Now;
975                        }
976                    }
977                    catch (Exception)
978                    {
979                        //ignored
980                    }
981
982                    try
983                    {
984                        if (messageInterval != 0 &&
985                            DateTime.Now - messageStartDate > TimeSpan.FromMinutes(messageInterval) &&
986                            itm.LoginInfo != null)
987                        {
988                            SendMessage();
989
990                            messageStartDate = DateTime.Now;
991                        }
992                    }
993                    catch (Exception)
994                    {
995                        //ignored
996                    }
997
998                    void SendMessage()
999                    {
1000                        try
1001                        {
1002                            var chatBox = page.WaitForSelectorAsync(".nimo-room__chatroom__chat-box__input")
1003                                .GetAwaiter().GetResult();
1004
1005                            if (chatBox != null && _chatMessages.TryTake(out var message))
1006                            {
1007                                chatBox.TypeAsync(message).GetAwaiter().GetResult();
1008                                page.Keyboard.PressAsync("Enter");
1009                            }
1010                        }
1011                        catch (Exception)
1012                        {
1013                            //ignored  
1014                        }
1015                    }
1016
1017                    Thread.Sleep(1000);
1018                }
1019            }
1020
1021            if (itm.Service == StreamService.Service.Twitter)
1022            {
1023                Thread.Sleep(3000);
1024
1025                while (true)
1026                {
1027                    try
1028                    {
1029                        if (_firstPage)
1030                        {
1031                            firstPage = true;
1032                            _firstPage = false;
1033                        }
1034
1035                        if (firstPage)
1036                        {
1037                            var liveViewers =
1038                                page.Locator(
1039                                    "xpath=/html/body/div[2]/div[2]/div[2]/div[1]/div/div/div[2]/div[2]/div[1]/div[1]/div/div[2]/div[3]/span");
1040
1041                            if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)
1042                            {
1043                                LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult());
1044                                Thread.Sleep(5000);
1045                            }
1046                        }
1047                    }
1048                    catch (Exception)
1049                    {
1050                        LiveViewer.Invoke("N/A");
1051                    }
1052
1053                    try
1054                    {
1055                        if (_refreshInterval != 0 &&
1056                            DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))
1057                        {
1058                            page.ReloadAsync().GetAwaiter().GetResult();
1059                            startDate = DateTime.Now;
1060                        }
1061                    }
1062                    catch (Exception)
1063                    {
1064                        //ignored
1065                    }
1066
1067                    Thread.Sleep(1000);
1068                }
1069            }
1070
1071            if (itm.Service == StreamService.Service.Facebook)
1072            {
1073                Thread.Sleep(3000);
1074
1075                if (itm.LoginInfo != null)
1076                {
1077                    Thread.Sleep(1000);
1078
1079                    var allCookies = GetCookie(itm.LoginInfo.Username);
1080
1081                    if (allCookies != null)
1082                        foreach (var cookie in allCookies)
1083                        {
1084                            Cookie[] cookies =
1085                            {
1086                                new()
1087                                {
1088                                    Domain = cookie.Domain, Expires = cookie.Expiry, Name = cookie.Name,
1089                                    Path = cookie.Path, Secure = cookie.Secure, Url = cookie.Path,
1090                                    HttpOnly = cookie.HttpOnly, Value = cookie.Value
1091                                }
1092                            };
1093
1094                            page.Context.AddCookiesAsync(cookies);
1095                        }
1096
1097                    try
1098                    {
1099                        var usernameBox =
1100                            page.Locator(
1101                                "xpath=/html/body/div[1]/div/div[1]/div/div[2]/div[2]/div[2]/div/form/div[2]/div[1]/label/input");
1102
1103                        if (usernameBox.CountAsync().GetAwaiter().GetResult() > 0)
1104                        {
1105                            Click(ref usernameBox);
1106
1107                            Thread.Sleep(1000);
1108
1109                            usernameBox.TypeAsync(itm.LoginInfo.Username).GetAwaiter().GetResult();
1110
1111                            var passwordBox =
1112                                page.Locator(
1113                                    "xpath=/html/body/div[1]/div/div[1]/div/div[2]/div[2]/div[2]/div/form/div[2]/div[2]/label/input");
1114
1115                            if (passwordBox.CountAsync().GetAwaiter().GetResult() > 0)
1116                            {
1117                                Click(ref passwordBox);
1118
1119                                Thread.Sleep(1000);
1120
1121                                passwordBox.TypeAsync(itm.LoginInfo.Password).GetAwaiter().GetResult();
1122
1123                                Thread.Sleep(1000);
1124
1125                                var login = page.Locator(
1126                                    "xpath=/html/body/div[1]/div/div[1]/div/div[2]/div[2]/div[2]/div/form/div[2]/div[3]/div/div/div[1]/div/span/span");
1127
1128                                Thread.Sleep(1000);
1129
1130                                if (login.CountAsync().GetAwaiter().GetResult() > 0)
1131                                    Click(ref login);
1132                            }
1133                        }
1134                    }
1135                    catch (Exception ex)
1136                    {
1137                        LogMessage?.Invoke(new Exception($"Login failed: {ex.Message}"));
1138                    }
1139
1140                    Thread.Sleep(3000);
1141                    page.ReloadAsync().GetAwaiter().GetResult();
1142
1143                    while (true)
1144                    {
1145                        Thread.Sleep(1000);
1146
1147                        var cookie = page.Context.CookiesAsync().GetAwaiter().GetResult()
1148                            .Any(x => x.Name == "c_user");
1149
1150                        if (cookie)
1151                        {
1152                            StoreCookie(new Tuple<string, List<BrowserContextCookiesResult>>(itm.LoginInfo.Username,
1153                                new List<BrowserContextCookiesResult>(page.Context.CookiesAsync().GetAwaiter()
1154                                    .GetResult().ToArray())));
1155
1156                            break;
1157                        }
1158                    }
1159                }
1160
1161                while (true)
1162                {
1163                    try
1164                    {
1165                        if (_firstPage)
1166                        {
1167                            firstPage = true;
1168                            _firstPage = false;
1169                        }
1170
1171                        if (firstPage)
1172                        {
1173                            var liveViewers =
1174                                page.Locator(
1175                                    "xpath=/html/body/div[1]/div/div[1]/div/div[3]/div/div/div[1]/div[2]/div[1]/div/div/div/div[1]/div[1]/div/div/div/div[2]/div/div[5]/div[2]/span[2]");
1176
1177                            if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)
1178                            {
1179                                LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult());
1180                                Thread.Sleep(5000);
1181                            }
1182                        }
1183                    }
1184                    catch (Exception)
1185                    {
1186                        //ignored
1187                    }
1188
1189                    try
1190                    {
1191                        if (_refreshInterval != 0 &&
1192                            DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))
1193                        {
1194                            page.ReloadAsync().GetAwaiter().GetResult();
1195                            startDate = DateTime.Now;
1196                        }
1197                    }
1198                    catch (Exception)
1199                    {
1200                        //ignored
1201                    }
1202                }
1203            }
1204
1205            if (itm.Service == StreamService.Service.TrovoLive)
1206            {
1207                Thread.Sleep(5000);
1208
1209                if (!Headless && !_useLowCpuRam)
1210                    try
1211                    {
1212                        page.EvaluateAsync("window.localStorage.setItem('live/userClarityLevel', '" +
1213                                           itm.PreferredQuality + "');");
1214                        page.ReloadAsync().GetAwaiter().GetResult();
1215                    }
1216                    catch (Exception)
1217                    {
1218                        //ignored
1219                    }
1220
1221                if (itm.LoginInfo != null)
1222                {
1223                    Thread.Sleep(1000);
1224
1225                    var allCookies = GetCookie(itm.LoginInfo.Username);
1226
1227                    if (allCookies != null)
1228                        foreach (var cookie in allCookies)
1229                        {
1230                            Cookie[] cookies =
1231                            {
1232                                new()
1233                                {
1234                                    Domain = cookie.Domain, Expires = cookie.Expiry, Name = cookie.Name,
1235                                    Path = cookie.Path, Secure = cookie.Secure, Url = cookie.Path,
1236                                    HttpOnly = cookie.HttpOnly, Value = cookie.Value
1237                                }
1238                            };
1239
1240                            page.Context.AddCookiesAsync(cookies);
1241                        }
1242
1243                    try
1244                    {
1245                        var loginSignUpButton =
1246                            page.Locator("xpath=/html/body/div[1]/div/div/nav/div[3]/div[3]/button");
1247
1248                        if (loginSignUpButton.CountAsync().GetAwaiter().GetResult() > 0)
1249                        {
1250                            Click(ref loginSignUpButton);
1251
1252                            Thread.Sleep(4000);
1253
1254                            ILocator usernameBox;
1255
1256                            try
1257                            {
1258                                usernameBox =
1259                                    page.Locator(
1260                                        "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/div[1]/div/input");
1261                            }
1262                            catch
1263                            {
1264                                usernameBox =
1265                                    page.Locator(
1266                                        "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/div[1]/div[1]/input");
1267                            }
1268
1269                            if (usernameBox.CountAsync().GetAwaiter().GetResult() > 0)
1270                            {
1271                                Click(ref usernameBox);
1272
1273                                Thread.Sleep(1000);
1274
1275                                usernameBox.TypeAsync(itm.LoginInfo.Username).GetAwaiter().GetResult();
1276
1277                                Thread.Sleep(1000);
1278
1279                                var passwordBox =
1280                                    page.Locator(
1281                                        "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/div[3]/div/input");
1282
1283                                if (passwordBox.CountAsync().GetAwaiter().GetResult() > 0)
1284                                {
1285                                    passwordBox.TypeAsync(itm.LoginInfo.Password).GetAwaiter().GetResult();
1286
1287                                    var login = page.Locator(
1288                                        "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/button");
1289
1290                                    Thread.Sleep(1000);
1291
1292                                    if (login.CountAsync().GetAwaiter().GetResult() > 0)
1293                                        Click(ref login);
1294                                }
1295                            }
1296                        }
1297                    }
1298                    catch (Exception ex)
1299                    {
1300                        LogMessage?.Invoke(new Exception($"Login failed: {ex.Message}"));
1301                    }
1302
1303                    Thread.Sleep(3000);
1304                    page.ReloadAsync().GetAwaiter().GetResult();
1305
1306                    while (true)
1307                    {
1308                        Thread.Sleep(1000);
1309
1310                        var cookie = page.Context.CookiesAsync().GetAwaiter().GetResult().Any(x => x.Name == "uid");
1311
1312                        if (cookie)
1313                        {
1314                            StoreCookie(new Tuple<string, List<BrowserContextCookiesResult>>(itm.LoginInfo.Username,
1315                                new List<BrowserContextCookiesResult>(page.Context.CookiesAsync().GetAwaiter()
1316                                    .GetResult().ToArray())));
1317
1318                            break;
1319                        }
1320                    }
1321                }
1322
1323                var matureClicked = false;
1324
1325                var chatRulesClicked = false;
1326
1327                var matureCheckCount = 0;
1328
1329                while (true)
1330                {
1331                    try
1332                    {
1333                        if (_firstPage)
1334                        {
1335                            firstPage = true;
1336                            _firstPage = false;
1337                        }
1338
1339                        if (firstPage)
1340                        {
1341                            var liveViewers =
1342                                page.Locator(
1343                                    "xpath=/html/body/div[1]/div/div[1]/div/div[3]/div/div/div[1]/div[2]/div[1]/div/div/div/div[1]/div[1]/div/div/div/div[2]/div/div[5]/div[2]/span[2]");
1344
1345                            if (liveViewers.CountAsync().GetAwaiter().GetResult() > 0)
1346                            {
1347                                LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult());
1348                                Thread.Sleep(5000);
1349                            }
1350                        }
1351                    }
1352                    catch (Exception)
1353                    {
1354                        //ignored
1355                    }
1356
1357                    try
1358                    {
1359                        if (_refreshInterval != 0 &&
1360                            DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))
1361                        {
1362                            page.ReloadAsync().GetAwaiter().GetResult();
1363                            startDate = DateTime.Now;
1364                        }
1365                    }
1366                    catch (Exception)
1367                    {
1368                        //ignored
1369                    }
1370
1371                    try
1372                    {
1373                        if (!matureClicked && matureCheckCount < 5)
1374                            try
1375                            {
1376                                ILocator mature = null;
1377
1378                                try
1379                                {
1380                                    mature = page.Locator(
1381                                        "xpath=/html/body/div[1]/div/div/div/div[2]/div/div/div[1]/div[1]/div[1]/div/div[4]/div[3]/section/div/button[2]");
1382                                }
1383                                catch
1384                                {
1385                                    //ignored
1386                                }
1387
1388                                if (mature.CountAsync().GetAwaiter().GetResult() == 0)
1389                                    mature = page.Locator(
1390                                        "xpath=/html/body/div[1]/div/div/div/div[2]/div/div/div[1]/div[1]/div[1]/div/div[2]/div[3]/section/div/button[2]");
1391
1392                                if (mature.CountAsync().GetAwaiter().GetResult() > 0)
1393                                {
1394                                    Click(ref mature);
1395                                    matureClicked = true;
1396                                }
1397
1398                                matureCheckCount++;
1399                            }
1400                            catch
1401                            {
1402                                //ignored because there is no mature button
1403                            }
1404                    }
1405                    catch (Exception)
1406                    {
1407                        // ignored
1408                    }
1409
1410                    if (!chatRulesClicked)
1411                        try
1412                        {
1413                            var chatRules = page.Locator(
1414                                "xpath=/html/body/div[1]/div/div/div/div[2]/div/section/div[3]/div/section/section/div/button");
1415
1416                            if (chatRules.CountAsync().GetAwaiter().GetResult() > 0)
1417                            {
1418                                chatRules.ClickAsync().GetAwaiter().GetResult();
1419                                chatRulesClicked = true;
1420                            }
1421                        }
1422                        catch (Exception)
1423                        {
1424                            //ignored
1425                        }
1426
1427                    try
1428                    {
1429                        if (messageInterval != 0 &&
1430                            DateTime.Now - messageStartDate > TimeSpan.FromMinutes(messageInterval) &&
1431                            itm.LoginInfo != null)
1432                        {
1433                            SendMessage();
1434
1435                            messageStartDate = DateTime.Now;
1436                        }
1437                    }
1438                    catch (Exception)
1439                    {
1440                        //ignored
1441                    }
1442
1443                    void SendMessage()
1444                    {
1445                        try
1446                        {
1447                            var chatBox =
1448                                page.Locator(
1449                                    "xpath=/html/body/div[1]/div/div/div/div[2]/div/section/div[3]/div/section/div[1]/div[1]/div[1]");
1450
1451                            if (chatBox.CountAsync().GetAwaiter().GetResult() > 0 &&
1452                                _chatMessages.TryTake(out var message))
1453                            {
1454                                chatBox.TypeAsync(message).GetAwaiter().GetResult();
1455                                page.Keyboard.PressAsync("Enter");
1456                            }
1457                        }
1458                        catch (Exception)
1459                        {
1460                            //ignored  
1461                        }
1462                    }
1463
1464                    Thread.Sleep(1000);
1465                }
1466            }
1467
1468            if (itm.Service == StreamService.Service.BigoLive)
1469            {
1470                Thread.Sleep(2000);
1471
1472                page.ReloadAsync().GetAwaiter().GetResult();
1473                
1474                /*if (itm.LoginInfo != null)
1475                {
1476                    Thread.Sleep(1000);
1477
1478                    var allCookies = GetCookie(itm.LoginInfo.Username);
1479
1480                    if (allCookies != null)
1481                        foreach (var cookie in allCookies)
1482                        {
1483                            Cookie[] cookies =
1484                            {
1485                                new()
1486                                {
1487                                    Domain = cookie.Domain, Expires = cookie.Expiry, Name = cookie.Name,
1488                                    Path = cookie.Path, Secure = cookie.Secure, Url = cookie.Path,
1489                                    HttpOnly = cookie.HttpOnly, Value = cookie.Value
1490                                }
1491                            };
1492
1493                            page.Context.AddCookiesAsync(cookies);
1494                        }
1495
1496                    try
1497                    {
1498                        var loginSignUpButton =
1499                            page.Locator("xpath=/html/body/div/div/div/header/div[2]/div/button");
1500
1501                        if (loginSignUpButton.CountAsync().GetAwaiter().GetResult() > 0)
1502                        {
1503                            Click(ref loginSignUpButton);
1504                            
1505                            var withCredentialsButton =
1506                                page.Locator("xpath=/html/body/div/div[2]/div/header/div[3]/div/div[2]");
1507
1508                            if (withCredentialsButton.CountAsync().GetAwaiter().GetResult() > 0)
1509                            {
1510                                Click(ref withCredentialsButton);
1511
1512                                Thread.Sleep(4000);
1513
1514                                ILocator usernameBox;
1515
1516                                try
1517                                {
1518                                    usernameBox =
1519                                        page.Locator(
1520                                            "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/div[1]/div/input");
1521                                }
1522                                catch
1523                                {
1524                                    usernameBox =
1525                                        page.Locator(
1526                                            "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/div[1]/div[1]/input");
1527                                }
1528
1529                                if (usernameBox.CountAsync().GetAwaiter().GetResult() > 0)
1530                                {
1531                                    Click(ref usernameBox);
1532
1533                                    Thread.Sleep(1000);
1534
1535                                    usernameBox.TypeAsync(itm.LoginInfo.Username).GetAwaiter().GetResult();
1536
1537                                    Thread.Sleep(1000);
1538
1539                                    var passwordBox =
1540                                        page.Locator(
1541                                            "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/div[3]/div/input");
1542
1543                                    if (passwordBox.CountAsync().GetAwaiter().GetResult() > 0)
1544                                    {
1545                                        passwordBox.TypeAsync(itm.LoginInfo.Password).GetAwaiter().GetResult();
1546
1547                                        var login = page.Locator(
1548                                            "xpath=/html/body/div[4]/div/div[2]/div[3]/div[1]/button");
1549
1550                                        Thread.Sleep(1000);
1551
1552                                        if (login.CountAsync().GetAwaiter().GetResult() > 0)
1553                                            Click(ref login);
1554                                    }
1555                                }
1556                            }
1557                        }
1558                    }
1559                    catch (Exception ex)
1560                    {
1561                        LogMessage?.Invoke(new Exception($"Login failed: {ex.Message}"));
1562                    }
1563
1564                    Thread.Sleep(3000);
1565                    page.ReloadAsync().GetAwaiter().GetResult();
1566
1567                    while (true)
1568                    {
1569                        Thread.Sleep(1000);
1570
1571                        var cookie = page.Context.CookiesAsync().GetAwaiter().GetResult().Any(x => x.Name == "uid");
1572
1573                        if (cookie)
1574                        {
1575                            StoreCookie(new Tuple<string, List<BrowserContextCookiesResult>>(itm.LoginInfo.Username,
1576                                new List<BrowserContextCookiesResult>(page.Context.CookiesAsync().GetAwaiter()
1577                                    .GetResult().ToArray())));
1578
1579                            break;
1580                        }
1581                    }
1582                }*/
1583
1584                while (true)
1585                {
1586                    try
1587                    {
1588                        if (_firstPage)
1589                        {
1590                            firstPage = true;
1591                            _firstPage = false;
1592                        }
1593
1594                        if (firstPage)
1595                        {
1596                            var liveViewers = page.WaitForSelectorAsync(".info-view-nums").GetAwaiter().GetResult();
1597                            
1598                            if (liveViewers != null)
1599                            {
1600                                LiveViewer.Invoke(liveViewers.InnerTextAsync().GetAwaiter().GetResult());
1601                                Thread.Sleep(5000);
1602                            }
1603                        }
1604                    }
1605                    catch (Exception)
1606                    {
1607                        //ignored
1608                    }
1609
1610                    try
1611                    {
1612                        if (_refreshInterval != 0 &&
1613                            DateTime.Now - startDate > TimeSpan.FromMinutes(_refreshInterval))
1614                        {
1615                            page.ReloadAsync().GetAwaiter().GetResult();
1616                            startDate = DateTime.Now;
1617                        }
1618                    }
1619                    catch (Exception)
1620                    {
1621                        //ignored
1622                    }
1623
1624                    Thread.Sleep(1000);
1625                }
1626            }
1627
1628            try
1629            {
1630                page.CloseAsync().GetAwaiter().GetResult();
1631            }
1632            catch (Exception)
1633            {
1634                //ignored
1635            }
1636        }
1637        catch (InvalidOperationException ex)
1638        {
1639            if (ex.Message.Contains("only supports Chrome version"))
1640            {
1641                CanRun = false;
1642                InitializationError?.Invoke(new Exception("Please update your Google Chrome!"));
1643            }
1644        }
1645        catch (Exception ex)
1646        {
1647            InitializationError?.Invoke(ex);
1648        }
1649    }
1650
1651    private void Click(ref ILocator locator)
1652    {
1653        locator.ClickAsync().GetAwaiter().GetResult();
1654    }
1655
1656    private class MyCookie
1657    {
1658        public bool Secure { get; set; }
1659        public bool HttpOnly { get; set; }
1660        public string Name { get; set; }
1661        public string Value { get; set; }
1662        public string Domain { get; set; }
1663        public string Path { get; set; }
1664        public float Expiry { get; set; }
1665    }
1666}
Full Screen

Locator.cs

Source: Locator.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 */
26using System;
27using System.Collections.Generic;
28using System.Text.Json;
29using System.Threading.Tasks;
30using Microsoft.Playwright.Helpers;
31using Microsoft.Playwright.Transport.Protocol;
32
33namespace Microsoft.Playwright.Core
34{
35    internal class Locator : ILocator
36    {
37        internal readonly Frame _frame;
38        internal readonly string _selector;
39
40        private readonly LocatorLocatorOptions _options;
41
42        public Locator(Frame parent, string selector, LocatorLocatorOptions options = null)
43        {
44            _frame = parent;
45            _selector = selector;
46            _options = options;
47
48            if (options?.HasTextRegex != null)
49            {
50                _selector += $" >> :scope:text-matches({options.HasTextRegex.ToString().EscapeWithQuotes("\"")}, {options.HasTextRegex.Options.GetInlineFlags().EscapeWithQuotes("\"")})";
51            }
52            if (options?.HasTextString != null)
53            {
54                _selector += $" >> :scope:has-text({options.HasTextString.EscapeWithQuotes("\"")})";
55            }
56
57            if (options?.Has != null)
58            {
59                var has = (Locator)options.Has;
60                if (has._frame != _frame)
61                {
62                    throw new ArgumentException("Inner \"has\" locator must belong to the same frame.");
63                }
64                _selector += " >> has=" + JsonSerializer.Serialize(has._selector);
65            }
66        }
67
68        public ILocator First => new Locator(_frame, $"{_selector} >> nth=0");
69
70        public ILocator Last => new Locator(_frame, $"{_selector} >> nth=-1");
71
72        IPage ILocator.Page => _frame.Page;
73
74        public async Task<IReadOnlyList<string>> AllInnerTextsAsync()
75            => await EvaluateAllAsync<string[]>("ee => ee.map(e => e.innerText)").ConfigureAwait(false);
76
77        public async Task<IReadOnlyList<string>> AllTextContentsAsync()
78            => await EvaluateAllAsync<string[]>("ee => ee.map(e => e.textContent || '')").ConfigureAwait(false);
79
80        public async Task<LocatorBoundingBoxResult> BoundingBoxAsync(LocatorBoundingBoxOptions options = null)
81            => await WithElementAsync(
82                async (h, _) =>
83                {
84                    var bb = await h.BoundingBoxAsync().ConfigureAwait(false);
85                    if (bb == null)
86                    {
87                        return null;
88                    }
89
90                    return new LocatorBoundingBoxResult()
91                    {
92                        Height = bb.Height,
93                        Width = bb.Width,
94                        X = bb.X,
95                        Y = bb.Y,
96                    };
97                },
98                options).ConfigureAwait(false);
99
100        public Task CheckAsync(LocatorCheckOptions options = null)
101            => _frame.CheckAsync(
102                _selector,
103                ConvertOptions<FrameCheckOptions>(options));
104
105        public Task ClickAsync(LocatorClickOptions options = null)
106            => _frame.ClickAsync(
107                _selector,
108                ConvertOptions<FrameClickOptions>(options));
109
110        public Task SetCheckedAsync(bool checkedState, LocatorSetCheckedOptions options = null)
111            => checkedState ?
112                CheckAsync(ConvertOptions<LocatorCheckOptions>(options))
113                : UncheckAsync(ConvertOptions<LocatorUncheckOptions>(options));
114
115        public Task<int> CountAsync()
116            => _frame.QueryCountAsync(_selector);
117
118        public Task DblClickAsync(LocatorDblClickOptions options = null)
119            => _frame.DblClickAsync(_selector, ConvertOptions<FrameDblClickOptions>(options));
120
121        public Task DispatchEventAsync(string type, object eventInit = null, LocatorDispatchEventOptions options = null)
122            => _frame.DispatchEventAsync(_selector, type, eventInit, ConvertOptions<FrameDispatchEventOptions>(options));
123
124        public Task DragToAsync(ILocator target, LocatorDragToOptions options = null)
125            => _frame.DragAndDropAsync(_selector, ((Locator)target)._selector, ConvertOptions<FrameDragAndDropOptions>(options));
126
127        public async Task<IElementHandle> ElementHandleAsync(LocatorElementHandleOptions options = null)
128            => await _frame.WaitForSelectorAsync(
129                _selector,
130                ConvertOptions<FrameWaitForSelectorOptions>(options)).ConfigureAwait(false);
131
132        public Task<IReadOnlyList<IElementHandle>> ElementHandlesAsync()
133            => _frame.QuerySelectorAllAsync(_selector);
134
135        public Task<T> EvaluateAllAsync<T>(string expression, object arg = null)
136            => _frame.EvalOnSelectorAllAsync<T>(_selector, expression, arg);
137
138        public Task<JsonElement?> EvaluateAsync(string expression, object arg = null, LocatorEvaluateOptions options = null)
139            => EvaluateAsync<JsonElement?>(expression, arg, options);
140
141        public Task<T> EvaluateAsync<T>(string expression, object arg = null, LocatorEvaluateOptions options = null)
142            => _frame.EvalOnSelectorAsync<T>(_selector, expression, arg, ConvertOptions<FrameEvalOnSelectorOptions>(options));
143
144        public async Task<IJSHandle> EvaluateHandleAsync(string expression, object arg = null, LocatorEvaluateHandleOptions options = null)
145            => await WithElementAsync(async (e, _) => await e.EvaluateHandleAsync(expression, arg).ConfigureAwait(false), options).ConfigureAwait(false);
146
147        public async Task FillAsync(string value, LocatorFillOptions options = null)
148            => await _frame.FillAsync(_selector, value, ConvertOptions<FrameFillOptions>(options)).ConfigureAwait(false);
149
150        public Task FocusAsync(LocatorFocusOptions options = null)
151            => _frame.FocusAsync(_selector, ConvertOptions<FrameFocusOptions>(options));
152
153        IFrameLocator ILocator.FrameLocator(string selector) =>
154            new FrameLocator(_frame, $"{_selector} >> {selector}");
155
156        public Task<string> GetAttributeAsync(string name, LocatorGetAttributeOptions options = null)
157            => _frame.GetAttributeAsync(_selector, name, ConvertOptions<FrameGetAttributeOptions>(options));
158
159        public Task HoverAsync(LocatorHoverOptions options = null)
160            => _frame.HoverAsync(_selector, ConvertOptions<FrameHoverOptions>(options));
161
162        public Task<string> InnerHTMLAsync(LocatorInnerHTMLOptions options = null)
163            => _frame.InnerHTMLAsync(_selector, ConvertOptions<FrameInnerHTMLOptions>(options));
164
165        public Task<string> InnerTextAsync(LocatorInnerTextOptions options = null)
166            => _frame.InnerTextAsync(_selector, ConvertOptions<FrameInnerTextOptions>(options));
167
168        public Task<string> InputValueAsync(LocatorInputValueOptions options = null)
169            => _frame.InputValueAsync(_selector, ConvertOptions<FrameInputValueOptions>(options));
170
171        public Task<bool> IsCheckedAsync(LocatorIsCheckedOptions options = null)
172            => _frame.IsCheckedAsync(_selector, ConvertOptions<FrameIsCheckedOptions>(options));
173
174        public Task<bool> IsDisabledAsync(LocatorIsDisabledOptions options = null)
175            => _frame.IsDisabledAsync(_selector, ConvertOptions<FrameIsDisabledOptions>(options));
176
177        public Task<bool> IsEditableAsync(LocatorIsEditableOptions options = null)
178            => _frame.IsEditableAsync(_selector, ConvertOptions<FrameIsEditableOptions>(options));
179
180        public Task<bool> IsEnabledAsync(LocatorIsEnabledOptions options = null)
181            => _frame.IsEnabledAsync(_selector, ConvertOptions<FrameIsEnabledOptions>(options));
182
183        public Task<bool> IsHiddenAsync(LocatorIsHiddenOptions options = null)
184            => _frame.IsHiddenAsync(_selector, ConvertOptions<FrameIsHiddenOptions>(options));
185
186        public Task<bool> IsVisibleAsync(LocatorIsVisibleOptions options = null)
187            => _frame.IsVisibleAsync(_selector, ConvertOptions<FrameIsVisibleOptions>(options));
188
189        public ILocator Nth(int index)
190            => new Locator(_frame, $"{_selector} >> nth={index}");
191
192        public Task PressAsync(string key, LocatorPressOptions options = null)
193            => _frame.PressAsync(_selector, key, ConvertOptions<FramePressOptions>(options));
194
195        public Task<byte[]> ScreenshotAsync(LocatorScreenshotOptions options = null)
196            => WithElementAsync(async (h, o) => await h.ScreenshotAsync(ConvertOptions<ElementHandleScreenshotOptions>(o)).ConfigureAwait(false), options);
197
198        public Task ScrollIntoViewIfNeededAsync(LocatorScrollIntoViewIfNeededOptions options = null)
199            => WithElementAsync(async (h, o) => await h.ScrollIntoViewIfNeededAsync(ConvertOptions<ElementHandleScrollIntoViewIfNeededOptions>(o)).ConfigureAwait(false), options);
200
201        public Task<IReadOnlyList<string>> SelectOptionAsync(string values, LocatorSelectOptionOptions options = null)
202            => _frame.SelectOptionAsync(_selector, values, ConvertOptions<FrameSelectOptionOptions>(options));
203
204        public Task<IReadOnlyList<string>> SelectOptionAsync(IElementHandle values, LocatorSelectOptionOptions options = null)
205            => _frame.SelectOptionAsync(_selector, values, ConvertOptions<FrameSelectOptionOptions>(options));
206
207        public Task<IReadOnlyList<string>> SelectOptionAsync(IEnumerable<string> values, LocatorSelectOptionOptions options = null)
208            => _frame.SelectOptionAsync(_selector, values, ConvertOptions<FrameSelectOptionOptions>(options));
209
210        public Task<IReadOnlyList<string>> SelectOptionAsync(SelectOptionValue values, LocatorSelectOptionOptions options = null)
211            => _frame.SelectOptionAsync(_selector, values, ConvertOptions<FrameSelectOptionOptions>(options));
212
213        public Task<IReadOnlyList<string>> SelectOptionAsync(IEnumerable<IElementHandle> values, LocatorSelectOptionOptions options = null)
214            => _frame.SelectOptionAsync(_selector, values, ConvertOptions<FrameSelectOptionOptions>(options));
215
216        public Task<IReadOnlyList<string>> SelectOptionAsync(IEnumerable<SelectOptionValue> values, LocatorSelectOptionOptions options = null)
217            => _frame.SelectOptionAsync(_selector, values, ConvertOptions<FrameSelectOptionOptions>(options));
218
219        public Task SelectTextAsync(LocatorSelectTextOptions options = null)
220            => WithElementAsync((h, o) => h.SelectTextAsync(ConvertOptions<ElementHandleSelectTextOptions>(o)), options);
221
222        public Task SetInputFilesAsync(string files, LocatorSetInputFilesOptions options = null)
223            => _frame.SetInputFilesAsync(_selector, files, ConvertOptions<FrameSetInputFilesOptions>(options));
224
225        public Task SetInputFilesAsync(IEnumerable<string> files, LocatorSetInputFilesOptions options = null)
226            => _frame.SetInputFilesAsync(_selector, files, ConvertOptions<FrameSetInputFilesOptions>(options));
227
228        public Task SetInputFilesAsync(FilePayload files, LocatorSetInputFilesOptions options = null)
229            => _frame.SetInputFilesAsync(_selector, files, ConvertOptions<FrameSetInputFilesOptions>(options));
230
231        public Task SetInputFilesAsync(IEnumerable<FilePayload> files, LocatorSetInputFilesOptions options = null)
232            => _frame.SetInputFilesAsync(_selector, files, ConvertOptions<FrameSetInputFilesOptions>(options));
233
234        public Task TapAsync(LocatorTapOptions options = null)
235            => _frame.TapAsync(_selector, ConvertOptions<FrameTapOptions>(options));
236
237        public Task<string> TextContentAsync(LocatorTextContentOptions options = null)
238            => _frame.TextContentAsync(_selector, ConvertOptions<FrameTextContentOptions>(options));
239
240        public Task TypeAsync(string text, LocatorTypeOptions options = null)
241            => _frame.TypeAsync(_selector, text, ConvertOptions<FrameTypeOptions>(options));
242
243        public Task UncheckAsync(LocatorUncheckOptions options = null)
244            => _frame.UncheckAsync(_selector, ConvertOptions<FrameUncheckOptions>(options));
245
246        ILocator ILocator.Locator(string selector, LocatorLocatorOptions options)
247            => new Locator(_frame, $"{_selector} >> {selector}", options);
248
249        public Task WaitForAsync(LocatorWaitForOptions options = null)
250            => _frame.LocatorWaitForAsync(_selector, ConvertOptions<LocatorWaitForOptions>(options));
251
252        internal Task<FrameExpectResult> ExpectAsync(string expression, FrameExpectOptions options = null)
253            => _frame.ExpectAsync(
254                _selector,
255                expression,
256                options);
257
258        public override string ToString() => "[email protected]" + _selector;
259
260        private T ConvertOptions<T>(object source)
261            where T : class, new()
262        {
263            T target = new();
264            var targetType = target.GetType();
265            if (source != null)
266            {
267                var sourceType = source.GetType();
268                foreach (var sourceProperty in sourceType.GetProperties())
269                {
270                    var targetProperty = targetType.GetProperty(sourceProperty.Name);
271                    if (targetProperty != null)
272                    {
273                        targetProperty.SetValue(target, sourceProperty.GetValue(source));
274                    }
275                }
276            }
277            var strictProperty = targetType.GetProperty("Strict");
278            if (strictProperty != null && strictProperty.GetValue(target) == null)
279            {
280                strictProperty.SetValue(target, true);
281            }
282            return target;
283        }
284
285        private async Task<TResult> WithElementAsync<TOptions, TResult>(Func<IElementHandle, TOptions, Task<TResult>> callback, TOptions options)
286            where TOptions : class
287            where TResult : class
288        {
289            IElementHandle handle = await ElementHandleAsync(ConvertOptions<LocatorElementHandleOptions>(options)).ConfigureAwait(false);
290            try
291            {
292                return await callback(handle, options).ConfigureAwait(false);
293            }
294            finally
295            {
296                await handle.DisposeAsync().ConfigureAwait(false);
297            }
298        }
299
300        private async Task WithElementAsync<TOptions>(Func<IElementHandle, TOptions, Task> callback, TOptions options)
301            where TOptions : class
302        {
303            IElementHandle handle = await ElementHandleAsync(ConvertOptions<LocatorElementHandleOptions>(options)).ConfigureAwait(false);
304            try
305            {
306                await callback(handle, options).ConfigureAwait(false);
307            }
308            finally
309            {
310                await handle.DisposeAsync().ConfigureAwait(false);
311            }
312        }
313
314        public Task HighlightAsync() => _frame.HighlightAsync(_selector);
315    }
316}
317
Full Screen

BlazorServerTemplateTest.cs

Source: BlazorServerTemplateTest.cs Github

copy
1// Licensed to the .NET Foundation under one or more agreements.
2// The .NET Foundation licenses this file to you under the MIT license.
3
4using System;
5using System.Collections.Generic;
6using System.Linq;
7using System.Net;
8using System.Threading.Tasks;
9using Microsoft.AspNetCore.BrowserTesting;
10using Microsoft.AspNetCore.Testing;
11using Microsoft.Playwright;
12using ProjectTemplates.Tests.Infrastructure;
13using Templates.Test.Helpers;
14using Xunit;
15using Xunit.Abstractions;
16
17namespace BlazorTemplates.Tests;
18
19public class BlazorServerTemplateTest : BlazorTemplateTest
20{
21    public BlazorServerTemplateTest(ProjectFactoryFixture projectFactory)
22        : base(projectFactory)
23    {
24    }
25
26    public override string ProjectType { get; } = "blazorserver";
27
28    [Theory(Skip = "https://github.com/dotnet/aspnetcore/issues/30761")]
29    [InlineData(BrowserKind.Chromium)]
30    public async Task BlazorServerTemplateWorks_NoAuth(BrowserKind browserKind)
31    {
32        var project = await CreateBuildPublishAsync("blazorservernoauth" + browserKind);
33
34        await using var browser = BrowserManager.IsAvailable(browserKind) ?
35            await BrowserManager.GetBrowserInstance(browserKind, BrowserContextInfo) :
36            null;
37
38        using (var aspNetProcess = project.StartBuiltProjectAsync())
39        {
40            Assert.False(
41                aspNetProcess.Process.HasExited,
42                ErrorMessages.GetFailedProcessMessageOrEmpty("Run built project", project, aspNetProcess.Process));
43
44            await aspNetProcess.AssertStatusCode("/", HttpStatusCode.OK, "text/html");
45
46            if (BrowserManager.IsAvailable(browserKind))
47            {
48                var page = await browser.NewPageAsync();
49                await aspNetProcess.VisitInBrowserAsync(page);
50                await TestBasicNavigation(page);
51                await page.CloseAsync();
52            }
53            else
54            {
55                EnsureBrowserAvailable(browserKind);
56            }
57        }
58
59        using (var aspNetProcess = project.StartPublishedProjectAsync())
60        {
61            Assert.False(
62                aspNetProcess.Process.HasExited,
63                ErrorMessages.GetFailedProcessMessageOrEmpty("Run published project", project, aspNetProcess.Process));
64
65            await aspNetProcess.AssertStatusCode("/", HttpStatusCode.OK, "text/html");
66            if (BrowserManager.IsAvailable(browserKind))
67            {
68                var page = await browser.NewPageAsync();
69                await aspNetProcess.VisitInBrowserAsync(page);
70                await TestBasicNavigation(page);
71                await page.CloseAsync();
72            }
73            else
74            {
75                EnsureBrowserAvailable(browserKind);
76            }
77        }
78    }
79
80    public static IEnumerable<object[]> BlazorServerTemplateWorks_IndividualAuthData =>
81            BrowserManager.WithBrowsers(new[] { BrowserKind.Chromium }, true, false);
82
83    [Theory(Skip = "https://github.com/dotnet/aspnetcore/issues/30882")]
84    [MemberData(nameof(BlazorServerTemplateWorks_IndividualAuthData))]
85    [SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/30825", Queues = "All.OSX")]
86    public async Task BlazorServerTemplateWorks_IndividualAuth(BrowserKind browserKind, bool useLocalDB)
87    {
88        var project = await CreateBuildPublishAsync("blazorserverindividual" + browserKind + (useLocalDB ? "uld" : ""));
89
90        var browser = !BrowserManager.IsAvailable(browserKind) ?
91            null :
92            await BrowserManager.GetBrowserInstance(browserKind, BrowserContextInfo);
93
94        using (var aspNetProcess = project.StartBuiltProjectAsync())
95        {
96            Assert.False(
97                aspNetProcess.Process.HasExited,
98                ErrorMessages.GetFailedProcessMessageOrEmpty("Run built project", project, aspNetProcess.Process));
99
100            await aspNetProcess.AssertStatusCode("/", HttpStatusCode.OK, "text/html");
101            if (BrowserManager.IsAvailable(browserKind))
102            {
103                var page = await browser.NewPageAsync();
104                await aspNetProcess.VisitInBrowserAsync(page);
105                await TestBasicNavigation(page);
106                await page.CloseAsync();
107            }
108            else
109            {
110                EnsureBrowserAvailable(browserKind);
111            }
112        }
113
114        using (var aspNetProcess = project.StartPublishedProjectAsync())
115        {
116            Assert.False(
117                aspNetProcess.Process.HasExited,
118                ErrorMessages.GetFailedProcessMessageOrEmpty("Run published project", project, aspNetProcess.Process));
119
120            await aspNetProcess.AssertStatusCode("/", HttpStatusCode.OK, "text/html");
121            if (BrowserManager.IsAvailable(browserKind))
122            {
123                var page = await browser.NewPageAsync();
124                await aspNetProcess.VisitInBrowserAsync(page);
125                await TestBasicNavigation(page);
126                await page.CloseAsync();
127            }
128            else
129            {
130                EnsureBrowserAvailable(browserKind);
131            }
132        }
133    }
134
135    private async Task TestBasicNavigation(IPage page)
136    {
137        var socket = await page.WaitForWebSocketAsync();
138
139        var framesReceived = 0;
140        var framesSent = 0;
141
142        void FrameReceived(object sender, IWebSocketFrame frame) { framesReceived++; }
143        void FrameSent(object sender, IWebSocketFrame frame) { framesSent++; }
144
145        socket.FrameReceived += FrameReceived;
146        socket.FrameSent += FrameSent;
147
148        // Receive render batch
149        await page.WaitForWebSocketAsync(new() { Predicate = (s) => framesReceived == 1 });
150        await page.WaitForWebSocketAsync(new() { Predicate = (s) => framesSent == 1 });
151
152        // JS interop call to intercept navigation
153        await page.WaitForWebSocketAsync(new() { Predicate = (s) => framesReceived == 2 });
154        await page.WaitForWebSocketAsync(new() { Predicate = (s) => framesSent == 2 });
155
156        socket.FrameReceived -= FrameReceived;
157        socket.FrameSent -= FrameSent;
158
159        await page.WaitForSelectorAsync("nav");
160        // <title> element gets project ID injected into it during template execution
161        Assert.Equal("Index", (await page.TitleAsync()).Trim());
162
163        // Initially displays the home page
164        await page.WaitForSelectorAsync("h1 >> text=Hello, world!");
165
166        // Can navigate to the counter page
167        await page.ClickAsync("a[href=counter] >> text=Counter");
168        await page.WaitForSelectorAsync("h1+p >> text=Current count: 0");
169
170        // Clicking the counter button works
171        await page.ClickAsync("p+button >> text=Click me");
172        await page.WaitForSelectorAsync("h1+p >> text=Current count: 1");
173
174        // Can navigate to the 'fetch data' page
175        await page.ClickAsync("a[href=fetchdata] >> text=Fetch data");
176        await page.WaitForSelectorAsync("h1 >> text=Weather forecast");
177
178        // Asynchronously loads and displays the table of weather forecasts
179        await page.WaitForSelectorAsync("table>tbody>tr");
180        Assert.Equal(5, await page.Locator("p+table>tbody>tr").CountAsync());
181    }
182
183    [Theory(Skip = "https://github.com/dotnet/aspnetcore/issues/30882")]
184    [InlineData("IndividualB2C", null)]
185    [InlineData("IndividualB2C", new string[] { "--called-api-url \"https://graph.microsoft.com\"", "--called-api-scopes user.readwrite" })]
186    [InlineData("SingleOrg", null)]
187    [InlineData("SingleOrg", new string[] { "--called-api-url \"https://graph.microsoft.com\"", "--called-api-scopes user.readwrite" })]
188    [InlineData("SingleOrg", new string[] { "--calls-graph" })]
189    public Task BlazorServerTemplate_IdentityWeb_BuildAndPublish(string auth, string[] args)
190        => CreateBuildPublishAsync("blazorserveridweb" + Guid.NewGuid().ToString().Substring(0, 10).ToLowerInvariant(), auth, args);
191}
192
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
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)