How to use LocatorWaitForOptions method of Microsoft.Playwright.LocatorWaitForOptions class

Best Playwright-dotnet code snippet using Microsoft.Playwright.LocatorWaitForOptions.LocatorWaitForOptions

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

ElementsPage.cs

Source: ElementsPage.cs Github

copy
1using Microsoft.Playwright;
2
3namespace UIAutomationDemo.Specs.Pages.Playwright;
4
5public class ElementsPage : BasePage
6{
7    private static string Url => "https://letcode.in/elements";
8
9    private static string GitUsernameField => "[name='username']";
10    private static string GitSearchButton => "#search";
11    private static string GitProfile => "app-usercard";
12    private static string GitUsernameTitle => "app-usercard .title";
13    private static string GitUsernameImage => "app-usercard img";
14    private static string GitPublicRepos => "xpath=(.//app-usercard//span[@class='tag is-info'])[1]";
15
16    public ElementsPage(IPage page) : base(page, Url) { }
17
18    public async Task SearchGitUsername(string gitUsername)
19    {
20        await _page.TypeAsync(GitUsernameField, gitUsername);
21        await _page.ClickAsync(GitSearchButton);
22    }
23
24    public async Task<string> GetGitUsername() => await _page.InnerTextAsync(GitUsernameTitle);
25
26    public async Task<string> GetGitPublicRepos() => await _page.InnerTextAsync(GitPublicRepos);
27
28    public async Task<bool> HasGitProfileBeenFound()
29    {
30        try
31        {
32            await _page.Locator(GitProfile).WaitForAsync(new LocatorWaitForOptions() { Timeout = 5000 });
33            return true;
34        } 
35        catch 
36        { 
37            return false; 
38        }
39    }
40
41    public async Task<bool> HasGitProfileImage() => await _page.Locator(GitUsernameImage).CountAsync() > 0;
42}
43
Full Screen

LocatorWaitForOptions.cs

Source: LocatorWaitForOptions.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) Microsoft Corporation.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25using System;
26using System.Collections.Generic;
27using System.ComponentModel.DataAnnotations;
28using System.Drawing;
29using System.Globalization;
30using System.IO;
31using System.Runtime.Serialization;
32using System.Text.Json;
33using System.Text.Json.Serialization;
34using System.Text.RegularExpressions;
35using System.Threading;
36using System.Threading.Tasks;
37
38#nullable enable
39
40namespace Microsoft.Playwright
41{
42    public class LocatorWaitForOptions
43    {
44        public LocatorWaitForOptions() { }
45
46        public LocatorWaitForOptions(LocatorWaitForOptions clone)
47        {
48            if (clone == null)
49            {
50                return;
51            }
52
53            State = clone.State;
54            Timeout = clone.Timeout;
55        }
56
57        /// <summary>
58        /// <para>Defaults to <c>'visible'</c>. Can be either:</para>
59        /// <list type="bullet">
60        /// <item><description><c>'attached'</c> - wait for element to be present in DOM.</description></item>
61        /// <item><description><c>'detached'</c> - wait for element to not be present in DOM.</description></item>
62        /// <item><description>
63        /// <c>'visible'</c> - wait for element to have non-empty bounding box and no <c>visibility:hidden</c>.
64        /// Note that element without any content or with <c>display:none</c> has an empty bounding
65        /// box and is not considered visible.
66        /// </description></item>
67        /// <item><description>
68        /// <c>'hidden'</c> - wait for element to be either detached from DOM, or have an empty
69        /// bounding box or <c>visibility:hidden</c>. This is opposite to the <c>'visible'</c>
70        /// option.
71        /// </description></item>
72        /// </list>
73        /// </summary>
74        [JsonPropertyName("state")]
75        public WaitForSelectorState? State { get; set; }
76
77        /// <summary>
78        /// <para>
79        /// Maximum time in milliseconds, defaults to 30 seconds, pass <c>0</c> to disable timeout.
80        /// The default value can be changed by using the <see cref="IBrowserContext.SetDefaultTimeout"/>
81        /// or <see cref="IPage.SetDefaultTimeout"/> methods.
82        /// </para>
83        /// </summary>
84        [JsonPropertyName("timeout")]
85        public float? Timeout { get; set; }
86    }
87}
88
89#nullable disable
90
Full Screen

WebBasedGenerator.cs

Source: WebBasedGenerator.cs Github

copy
1using System;
2using System.Collections.Generic;
3using System.Data;
4using System.Diagnostics;
5using System.Globalization;
6using System.IO;
7using System.Linq;
8using System.Reflection;
9using System.Threading;
10using System.Threading.Tasks;
11using ImageMagick;
12using Microsoft.Playwright;
13using QuestPDF.Drawing;
14using QuestPDF.Fluent;
15using QuestPDF.Helpers;
16using QuestPDF.Infrastructure;
17using Svg.Skia;
18using Utf8Json;
19
20
21namespace Argumentum.AssetConverter
22{
23    public class WebBasedGenerator
24    {
25
26        private Stopwatch sw;
27        public WebBasedGeneratorConfig Config { get; set; }
28
29        public WebBasedGenerator(WebBasedGeneratorConfig config, Stopwatch objSw)
30        {
31            Config = config;
32            sw = objSw;
33
34        }
35     
36
37        public void Run()
38        {
39            sw = Stopwatch.StartNew();
40            //var harvestDictionary = HarvestImages();
41            var harvestDictionary = Task.Run(async () => await HarvestImages()).Result; 
42            var docImages = GenerateDocumentImages(harvestDictionary);
43            
44            GenerateDocuments(docImages);
45            //Console.WriteLine($"Generation finished. Total duration: {sw.Elapsed}");
46
47        }
48
49
50        async Task<Dictionary<string, CardSetHarvest>>  HarvestImages()
51        {
52
53            Dictionary<string, CardSetHarvest> harvestDictionary;
54            //var jsonHarvestName = Path.Combine(Environment.CurrentDirectory, "harvest.json");
55            //if (File.Exists(jsonHarvestName))
56            //{
57            //    using var configStream = File.OpenRead(jsonHarvestName);
58            //    harvestDictionary = JsonSerializer.Deserialize<Dictionary<string, CardSetHarvest>>(configStream);
59            //    Console.WriteLine($"Loaded Harvest {jsonHarvestName}");
60            //}
61            //else
62            //{
63
64            harvestDictionary = new Dictionary<string, CardSetHarvest>();
65            var usedCardSets = Config.Documents.Where(d=>d.Enabled).SelectMany(d => d.CardSets.Select(dc => dc.CardSetName)).Distinct()
66                .ToArray();
67            var targetCardSets = Config.CardSets.Where(c => usedCardSets.Contains(c.Name)).ToArray();
68            foreach (var configCardSet in targetCardSets)
69            {
70
71                var jsonHarvestName = configCardSet.GetHarvestSerializationName(Config);
72                if (File.Exists(jsonHarvestName))
73                {
74                    using var configStream = File.OpenRead(jsonHarvestName);
75                    var currentHarvest = JsonSerializer.Deserialize<CardSetHarvest>(configStream);
76                    Console.WriteLine($"Loaded Harvest {jsonHarvestName}: {sw.Elapsed}");
77                    harvestDictionary[configCardSet.Name] = currentHarvest;
78                }
79
80            }
81
82            if (harvestDictionary.Count < targetCardSets.Count())
83            {
84                //var options = new ChromeOptions();
85                //options.BinaryLocation = Config.ChromeBinaryPath;
86
87                var exitCode = Microsoft.Playwright.Program.Main(new[] { "install" });
88                if (exitCode != 0)
89                {
90                    throw new Exception($"Playwright exited with code {exitCode}");
91                }
92
93                using var playwright = await Playwright.CreateAsync();
94                await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
95                {
96                    Headless = false,
97                    //SlowMo = 50,
98                });
99
100                //using (var driver = new ChromeDriver(options))
101                //{
102                    try
103                    {
104                        //driver.Manage().Window.Minimize();
105                        ////js = (IJavaScriptExecutor)driver;
106                        ////vars = new Dictionary<String, Object>();
107                        //driver.Navigate().GoToUrl(Config.CardpenUrl);
108                        //driver.FindElement(By.Id("eg")).Click();
109
110
111                        var page = await browser.NewPageAsync();
112                        await page.GotoAsync(Config.CardpenUrl);
113
114
115
116
117                    Thread.Sleep(TimeSpan.FromSeconds(5));
118
119                        foreach (var configCardSet in targetCardSets)
120                        {
121                            if (!harvestDictionary.ContainsKey(configCardSet.Name))
122                            {
123                                var currentHarvest = new CardSetHarvest();
124                                var faces = await GenerateImages(page, configCardSet.FaceCardSetInfo);
125                                currentHarvest.Faces = faces;
126                                if (configCardSet.BackCardSetInfo.IsSet)
127                                {
128                                    var backs = await GenerateImages(page, configCardSet.BackCardSetInfo);
129                                    currentHarvest.Backs = backs;
130                                }
131
132                                var jsonHarvestName = configCardSet.GetHarvestSerializationName(Config);
133                                var strNewConfig = JsonSerializer.PrettyPrint(JsonSerializer.ToJsonString(currentHarvest));
134                                File.WriteAllText(jsonHarvestName, strNewConfig);
135                                Console.WriteLine($"Serialized Harvest {jsonHarvestName}: {sw.Elapsed}");
136
137
138                                harvestDictionary[configCardSet.Name] = currentHarvest;
139                            }
140
141
142                        }
143                    }
144                    catch (Exception e)
145                    {
146                        Console.WriteLine(e);
147                        throw;
148                    }
149                    //finally
150                    //{
151                    //    driver.Quit();
152                    //}
153                //}
154            }
155
156
157
158
159            //var strNewConfig = JsonSerializer.PrettyPrint(JsonSerializer.ToJsonString(harvestDictionary));
160            //File.WriteAllText(jsonHarvestName, strNewConfig);
161            //Console.WriteLine($"Serialized Harvest {jsonHarvestName}");
162            //}
163
164            return harvestDictionary;
165        }
166
167
168
169        Dictionary<DocumentConfig, List<CardImages>> GenerateDocumentImages(Dictionary<string, CardSetHarvest> harvestDictionary)
170        {
171            Dictionary<DocumentConfig, List<CardImages>> toReturn = new Dictionary<DocumentConfig, List<CardImages>>();
172
173            foreach (var configDocument in Config.Documents.Where(d=>d.Enabled))
174            {
175                List<CardImages> targetList;
176
177                if (!toReturn.TryGetValue(configDocument, out targetList))
178                {
179                    targetList = new List<CardImages>();
180                    toReturn[configDocument] = targetList;
181                }
182
183                foreach (var configCardSet in configDocument.CardSets)
184                {
185                    Console.WriteLine($"Generating card set images for {configDocument.DocumentName} - {configCardSet.CardSetName}: {sw.Elapsed}");
186
187
188
189                    var currentHarvest = harvestDictionary[configCardSet.CardSetName];
190                    var backImages = new Dictionary<string, MagickImage>();
191                    if (currentHarvest.Backs != null)
192                    {
193                        foreach (var currentHarvestBack in currentHarvest.Backs.Images)
194                        {
195                            var backName = $"{currentHarvestBack.Key.ToLowerInvariant()}" ;
196                            var backImageUrl = currentHarvestBack.Value;
197                            var backImage = configCardSet.LoadAndProcessImageUrl(true, Config, configDocument,  backName, backImageUrl, currentHarvest.Backs.Dpi);
198                            if (backName.Contains('-'))
199                            {
200                                backName = backName.Substring(backName.LastIndexOf('-'));
201                            }
202
203                            backImages[backName] = backImage;
204                        }
205                    }
206
207                    
208                    for (int i = 0; i < configCardSet.NbCopies; i++)
209                    {
210                        CardImages currentCard = null;
211                        foreach (var currentHarvestFace in currentHarvest.Faces.Images)
212                        {
213
214                            var faceName = $"{currentHarvestFace.Key.ToLowerInvariant()}";
215                            if (!configDocument.NoBack)
216                            {
217                                faceName = $"face_{faceName}";
218                            }
219                            var faceImageUrl = currentHarvestFace.Value;
220                            var faceImage = configCardSet.LoadAndProcessImageUrl(false, Config, configDocument, faceName, faceImageUrl, currentHarvest.Faces.Dpi);
221                            if (currentCard == null)
222                            {
223                                currentCard = new CardImages();
224                                targetList.Add(currentCard);
225                                //currentCard.Front = new MagickImage(faceImage);
226                                currentCard.Front = faceImage;
227                                if (configDocument.NoBack)
228                                {
229                                    currentCard = null;
230                                }
231                            }
232                            else
233                            {
234                                //currentCard.Back = new MagickImage(faceImage);
235                                currentCard.Back = faceImage;
236                                currentCard = null;
237                            }
238                            
239                            if (backImages.Count > 0)
240                            {
241                                if (backImages.Count == 1)
242                                {
243                                    //currentCard.Back = new MagickImage(backImages.Values.First());
244                                    currentCard.Back = backImages.Values.First();
245                                }
246                                else
247                                {
248
249                                    var targetBackName = backImages.Keys.First(bn => faceName.Contains(bn));
250                                    //currentCard.Back = new MagickImage(backImages[targetBackName]);
251                                    currentCard.Back = backImages[targetBackName];
252                                }
253                                currentCard = null;
254                            }
255                        }
256                    }
257                }
258
259
260
261            }
262
263
264
265            return toReturn;
266        }
267
268
269        private void GenerateDocuments(Dictionary<DocumentConfig, List<CardImages>> docImages)
270        {
271            Console.WriteLine($"Generation pdf documents: {sw.Elapsed}");
272            var pdfDirectory = Config.GetPdfsDirectory();
273
274            foreach (var docImageList in docImages)
275            {
276                var densityDirectory = Path.Combine(pdfDirectory, [email protected]".\density-{docImageList.Key.TargetDensity}\");
277                if (!Directory.Exists(densityDirectory))
278                {
279                    Directory.CreateDirectory(densityDirectory);
280                }
281
282                var targetFiles = new List<(string fileName, MagickImageCollection documentImages)>();
283                MagickImageCollection collec;
284                var baseName = Path.Combine(densityDirectory, docImageList.Key.DocumentName);
285                switch (docImageList.Key.DocumentFormat)
286                {
287                    case CardDocumentFormat.AlternateFaceAndBack:
288                        collec = new MagickImageCollection(docImageList.Value.SelectMany(s =>
289                        {
290                            return new[] { s.Front, s.Back };
291                        }));
292                       
293                        targetFiles.Add((baseName, collec));
294                        GeneratePdfsFromImages(targetFiles);
295                        break;
296                    case CardDocumentFormat.BackFirstOneDocPerBack:
297                        
298                        var indexInsert = baseName.LastIndexOf('.');
299                        var cardsPerBack = docImageList.Value.GroupBy(card => card.Back).ToArray();
300                        for (int backIndex = 0; backIndex < cardsPerBack.Count(); backIndex++)
301                        {
302                            var frontsAndBack = cardsPerBack[backIndex];
303                            var backThenFronts = new[] { frontsAndBack.Key }.Concat(frontsAndBack.Select(card => card.Front));
304                            collec = new MagickImageCollection(backThenFronts);
305                            var newName = $"{baseName.Substring(0, indexInsert)}-{backIndex+1}{baseName.Substring(indexInsert)}";
306                            targetFiles.Add((newName,collec));
307                        }
308                        GeneratePdfsFromImages(targetFiles);
309                        break;
310                    case CardDocumentFormat.PrintAndPlay:
311                        GeneratePrintAndPlay(baseName, docImageList.Key, docImageList.Value);
312                        break;
313                    default:
314                        throw new ArgumentOutOfRangeException();
315                }
316                
317            }
318        }
319
320        private const float InchToCentimetre = 2.54f;
321        private const float InchToPoints = 72;
322        private float MmToPointsFactor = 0.1f / InchToCentimetre * InchToPoints;
323
324        private void GeneratePrintAndPlay(string fileName, DocumentConfig docConfig, List<CardImages> images)
325        {
326
327            var pageSizeType = typeof(PageSizes);
328            var dynProp = pageSizeType.GetProperty(docConfig.PageSize, BindingFlags.Static | BindingFlags.Public);
329
330            var pageSize = (PageSize)  dynProp.GetValue(null);
331            var pageMarginMm = 7f;
332            //var imagePaddingMm = 2f;
333
334
335            var cardWidthPoints = ((float)docConfig.CardSets[0].FrontCards.WidthMM) * MmToPointsFactor;
336            var cardHeightPoints = ((float)docConfig.CardSets[0].FrontCards.HeigthMM) * MmToPointsFactor;
337
338            
339            var totalMarginPoints = 2 * pageMarginMm * MmToPointsFactor;
340            var contentWidthPoints = pageSize.Width - totalMarginPoints;
341            var contentHeightPoints = pageSize.Height - totalMarginPoints;
342
343            var nbColumns = (int) (contentWidthPoints / cardWidthPoints);
344            var nbRows = (int) (contentHeightPoints / cardHeightPoints);
345
346            var nbCardsPerPage = nbRows * nbColumns;
347            var nbPages = (int) Math.Ceiling((decimal) images.Count / (decimal) nbCardsPerPage);
348
349            var docMetadata = new DocumentMetadata()
350            {
351                ApplyCaching = true,
352                Author = "Argumentum",
353                Creator = "Argumentum",
354                Producer = "Argumentum",
355                Subject = "Jeu de carte sur l'argumentation",
356                Keywords = "Argumentation, rhétorique, arguments fallacieux, sophismes, éloquence",
357                Title = "Argumentum Print & Play"
358            };
359
360            Document.Create(container =>
361                {
362                    for (int pageIndex = 0; pageIndex < nbPages; pageIndex++)
363                    {
364                        var pageCards = images.Skip(pageIndex * nbCardsPerPage);
365                        if (pageIndex<nbPages-1)
366                        {
367                            pageCards = pageCards.Take(nbCardsPerPage);
368                        }
369                        //else
370                        //{
371                        //    Debugger.Break();
372                        //}
373
374                        var pageCardsArray = pageCards.ToArray();
375
376                        //var cardArray = pageCards.ToList().ToJaggedArray(nbColumns);
377                        if (!docConfig.NoBack)
378                        {
379                            GenerateCardsPage(container, docConfig, pageSize, pageMarginMm, nbColumns, pageCardsArray, cardWidthPoints, cardImages => cardImages.Back);
380                            pageCardsArray = pageCardsArray.ToJaggedArray(nbColumns).Select(row => row.Reverse().ToArray())
381                                .ToArray().Flatten();
382                        }
383                        
384                        GenerateCardsPage(container, docConfig, pageSize, pageMarginMm, nbColumns, pageCardsArray, cardWidthPoints, cardImages => cardImages.Front);
385                    }
386
387                    
388                })
389                .WithMetadata(docMetadata)
390                .GeneratePdf(fileName);
391            Console.WriteLine($"Generated pdf document {fileName}: {sw.Elapsed}");
392
393        }
394
395        private static void GenerateCardsPage(IDocumentContainer container, DocumentConfig docConfig, PageSize pageSize, float pageMarginMm,
396            int nbColumns, CardImages[] pageCardsArray, float cardWidthPoints, Func<CardImages, MagickImage> frontOrBack)
397        {
398           
399            container.Page(page =>
400            {
401                page.Size(pageSize);
402                page.Margin(pageMarginMm, Unit.Millimetre);
403                page.PageColor(Colors.White);
404                page.DefaultTextStyle(x => x.FontSize(20));
405
406                if (!string.IsNullOrEmpty(docConfig.Header))
407                {
408                    page.Header()
409                        .AlignCenter()
410                        .Height(pageSize.Height / 20)
411                        .Padding(pageSize.Width / 70)
412                        .Image(docConfig.Header, ImageScaling.FitHeight);
413                       
414                }
415
416
417                page.Content()
418                    .Padding(0)
419                    .AlignCenter()
420                    .AlignTop()
421                    .Column(c =>
422                    {
423
424                        c.Item()
425                            .AlignCenter()
426                            .AlignTop()
427                            .Grid(g =>
428                            {
429                                g.AlignCenter();
430                                g.Spacing(2, Unit.Millimetre);
431                                g.Columns(nbColumns);
432                                for (int cardIndex = 0; cardIndex < pageCardsArray.Length; cardIndex++)
433                                {
434                                    var gridCell = g.Item()
435                                        //.Border(0.2f, Unit.Millimetre)
436                                        .AlignCenter()
437                                        .AlignMiddle()
438                                        .Width(cardWidthPoints);
439                                    var pageCard = pageCardsArray[cardIndex];
440                                    if (pageCard != null)
441                                    {
442                                        MagickImage toPrint = frontOrBack(pageCard);
443
444
445                                        if (!string.IsNullOrEmpty(toPrint.FileName))
446                                        {
447                                            gridCell.Image(toPrint.FileName);
448                                        }
449                                        else
450                                        {
451                                            using (var memStream = new MemoryStream())
452                                            {
453                                                toPrint.Write(memStream);
454                                                gridCell.Image(memStream.ToArray());
455                                            }
456                                        }
457                                    }
458                                }
459                            });
460                    });
461
462
463                //page.Footer()
464                //    .AlignCenter()
465                //    .Text(x =>
466                //    {
467                //        x.Span("Page ");
468                //        x.CurrentPageNumber();
469                //    });
470            });
471        }
472
473
474        private void GeneratePdfsFromImages(List<(string fileName, MagickImageCollection documentImages)> targetFiles)
475        {
476            foreach (var targetFile in targetFiles)
477            {
478                targetFile.documentImages.Write(targetFile.fileName);
479                Console.WriteLine($"Generated pdf document {targetFile.fileName}: {sw.Elapsed}");
480            }
481        }
482
483
484        //private List<ImageMagick.MagickImage> GenerateImages(string exampleName)
485        private async Task<CardPenHarvest> GenerateImages(IPage driver, CardSetInfo cardSet)
486        {
487            var toReturn = new CardPenHarvest();
488
489            
490
491            switch (cardSet.CardSetType)
492            {
493                case CardSetType.ExampleByName:
494                    //driver.FindElement(By.Id("exampleList")).Click();
495                    //var playwright = Task.Run(async () => await Playwright.CreateAsync()).Result ;
496                    
497                    //var dropdown = driver.FindElement(By.Id("exampleList"));
498                    var dropdown = driver.Locator("#exampleList");
499                    if (!await dropdown.IsVisibleAsync())
500                    {
501                        var exampleButton = driver.Locator("#eg");
502                        await exampleButton.ClickAsync();
503                        //Thread.Sleep(TimeSpan.FromSeconds(5));
504                    }
505
506                    await dropdown.ClickAsync();
507                    Console.WriteLine($"Generating example {cardSet.ExampleName}: {sw.Elapsed}");
508                    //dropdown.FindElement(By.XPath($"//option[. = '{cardSet.ExampleName}']")).Click();
509                    await dropdown.SelectOptionAsync(cardSet.ExampleName);
510                    //Thread.Sleep(TimeSpan.FromSeconds(5));
511                    break;
512                case CardSetType.CustomJson:
513                    //driver.FindElement(By.Id("load")).Click();
514                    //var importInput= driver.FindElement(By.Id("import"));
515                    var importInput = driver.Locator("#import");
516                    if (!await importInput.IsVisibleAsync())
517                    {
518                        var exampleButton = driver.Locator("#load");
519                        await exampleButton.ClickAsync();
520                        Thread.Sleep(TimeSpan.FromSeconds(2));
521                    }
522                    
523                    var customFilePath = cardSet.CustomJsonFileName;
524                    if (!Path.IsPathFullyQualified(cardSet.CustomJsonFileName))
525                    {
526                        customFilePath = Path.Combine(Environment.CurrentDirectory, customFilePath);
527                    }
528                    Console.WriteLine($"Generating CardSet {customFilePath}: {sw.Elapsed}");
529                    await driver.SetInputFilesAsync("#import", customFilePath);
530                    Thread.Sleep(TimeSpan.FromSeconds(5));
531
532
533
534                    break;
535                default:
536                    throw new ArgumentOutOfRangeException();
537            }
538
539           
540            if (cardSet.PauseForEdits)
541            {
542                Console.WriteLine($"Chrome est en pause le temps de faire vos éditions.\n Appuyez sur une touche pour démarrer la génération");
543                Console.Read();
544            }
545            //var objIFrame = driver.FindElement(By.Id("cpOutput"));
546            var objIFrame = driver.FrameLocator("#cpOutput");
547
548
549            //var objSession = ((ChromiumDriver) driver).CreateDevToolsSession();
550
551
552            //driver.SwitchTo().Frame(objIFrame);
553            //Console.WriteLine($"Waiting for html display {sw.Elapsed}");
554
555            //new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(drv => drv.FindElement(By.TagName("card")));
556            var objCardTag = objIFrame.Locator("card");
557            //await objCardTag.WaitForAsync(new LocatorWaitForOptions(){State = WaitForSelectorState.Attached});
558            while (await objCardTag.CountAsync()==0)
559            {
560                Thread.Sleep(100);
561            }
562
563
564            //driver.SwitchTo().ParentFrame();
565
566            
567            //driver.FindElement(By.CssSelector(".image")).Click();
568            await driver.Locator(".image").ClickAsync();
569
570            Thread.Sleep(TimeSpan.FromSeconds(5));
571
572            //objIFrame = new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(drv => drv.FindElement(By.Id("cpOutput")));
573            //driver.SwitchTo().Frame(objIFrame);
574            Console.WriteLine($"Waiting for image display {sw.Elapsed}");
575            //new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(drv => drv.FindElement(By.TagName("card")));
576            //await objCardTag.WaitForAsync(new LocatorWaitForOptions() { State = WaitForSelectorState.Attached });
577            while (await objCardTag.CountAsync() == 0)
578            {
579                Thread.Sleep(100);
580            }
581
582            //var dpi = (long)driver.ExecuteScript("return dpi;");
583            //var dpi = await driver.EvaluateAsync("return dpi;");
584            //var dpi = await driver.EvaluateAsync("dpi");
585
586            var dpi = await driver.Locator("#dpi").InputValueAsync();
587
588
589            toReturn.Dpi = Convert.ToInt32(dpi);
590
591            //Func<IWebDriver, IWebElement> generateButtonLambda = (IWebDriver drv) => drv.FindElement(By.Id("generateButton"));
592            //var generateButton = new WebDriverWait(driver, TimeSpan.FromSeconds(5)).Until(drv => generateButtonLambda(drv));
593            var objGenerateButton = objIFrame.Locator("#generateButton");
594            await objGenerateButton.WaitForAsync(new LocatorWaitForOptions() { State = WaitForSelectorState.Attached });
595
596
597
598            //var zipButtoLambda = new Func<IWebDriver, IWebElement>((IWebDriver drv) => drv.FindElement(By.Id("zipButton")));
599
600            Thread.Sleep(TimeSpan.FromSeconds(1));
601
602            //var zipButton = zipButtoLambda(driver);
603            var zipButton = objIFrame.Locator("#zipButton"); ;
604            
605            Thread.Sleep(TimeSpan.FromSeconds(5));
606            //generateButton.Click();
607            await objGenerateButton.ClickAsync();
608            //Console.WriteLine($"Waiting for Generated images  {sw.Elapsed}");
609            //new WebDriverWait(driver, TimeSpan.FromSeconds(600)).Until(drv => zipButtoLambda(drv).Displayed && zipButtoLambda(drv).Enabled);
610
611            await zipButton.WaitForAsync(new LocatorWaitForOptions() { State = WaitForSelectorState.Attached  });
612            await zipButton.WaitForAsync(new LocatorWaitForOptions() { State = WaitForSelectorState.Visible,Timeout = 0 });
613            var zipHandler = await zipButton.ElementHandleAsync();
614            await zipHandler.WaitForElementStateAsync(ElementState.Enabled);
615
616            //Console.WriteLine($"images generated {sw.Elapsed}");
617            //var generatedImagesDiv = driver.FindElement(By.Id("cpImages"));
618            var generatedImagesDiv = objIFrame.Locator("#cpImages");
619
620            //var generatedImages = generatedImagesDiv.FindElements(By.TagName("img"));
621            var generatedImages = generatedImagesDiv.Locator("img");
622
623            var cardNames = new List<string>();
624
625            //var cardsHtml = driver.FindElements(By.TagName("card"));
626            var cardsHtml = objIFrame.Locator("card");
627            for (var idxCard = 0; idxCard < await cardsHtml.CountAsync(); idxCard++)
628            {
629                var strCardName = idxCard.ToString(CultureInfo.InvariantCulture).PadLeft(3, '0');
630                //var cardElement = cardsHtml[idxCard];
631                var cardElement = cardsHtml.Nth(idxCard);
632                //var cardCssName = cardElement.FindElements(By.ClassName("cardName"));
633                var cardCssName = cardElement.Locator(".cardName");
634                //if (cardCssName.Count > 0)
635                if (await cardCssName.CountAsync() > 0)
636                {
637                    //strCardName = cardCssName[0].GetAttribute("textContent").Trim('-');
638                    var currentCard = cardCssName.Nth(0);
639                    //strCardName = (await currentCard.GetAttributeAsync("textContent"))?.Trim('-');
640                    strCardName = (await currentCard.TextContentAsync())?.Trim('-').Replace(" ","_");
641                }
642                cardNames.Add(strCardName);
643            }
644
645            if (await generatedImages.CountAsync() != cardNames.Count)
646            {
647                throw new ApplicationException("not same number of generated cards and card names");
648            }
649
650            for (int i = 0; i < await generatedImages.CountAsync(); i++)
651            {
652                //toReturn.Images[cardNames[i]] = generatedImages[i].GetAttribute("src");
653                var currentGeneratedImage = generatedImages.Nth(i);
654                var currentCardName = cardNames[i];
655                toReturn.Images[currentCardName] = await currentGeneratedImage.GetAttributeAsync("src");
656            }
657
658            //driver.SwitchTo().ParentFrame();
659
660            return toReturn;
661        }
662
663
664
665    }
666}
667
668
669
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

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

Try LambdaTest

Most used method in LocatorWaitForOptions

Trigger LocatorWaitForOptions code on LambdaTest Cloud Grid

Execute automation tests with LocatorWaitForOptions on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

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

Allow Cookie
Sarah

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

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

Sarah Elson (Product & Growth Lead)