asp.net-coreautomationeppluspuppeteer-sharp

Handling Dialog or Alert Box with Puppeteer Sharp


I am using Puppeteer Sharp and Epplus library on Asp.net core to perform some Automation on a website.

Scenario: Using Epplus I am reading data from an excel File and saving those data into local variables. Then, I am going to example.com/login to login with the login info. After performing login. I am looping through all the rows in the excel sheet to perform following operations:

Now, the issue is when the DOB, name, ID is correct, after clicking VERIFY button No Alert box/ Dialog box is shown Only The Verify Button's parent element's style becomes Display: None and Update Button's parent element 's style become Display:block. But If the information is incorrect then after clicking the VERIFY button A Browser Alert is shown saying 'There is a Mismatch in {x} data'.

This is the code I have written,

[HttpPost]
        public async Task<IActionResult> Uploader(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                // Handle invalid file upload.
                return View("Index");
            }

            var executablePath = "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe";
            ExcelPackage package;  // Declare package here

            try
            {
                using var stream = new MemoryStream();
                await file.CopyToAsync(stream);
                package = new ExcelPackage(stream);  // Initialize package

                var worksheet = package.Workbook.Worksheets[1];
                int rowCount = worksheet.Dimension.Rows;

                var browser = await Puppeteer.LaunchAsync(new LaunchOptions
                {
                    Headless = false,
                    IgnoreHTTPSErrors = true,
                    ExecutablePath = executablePath
                });
                var page = await browser.NewPageAsync();
                var userId = "XXXXXX";
                var password = "xxxxxx";

                await page.GoToAsync("SomeURL");
                await page.TypeAsync("input[name=userid]", userId);
                await page.TypeAsync("input[name=password]", password);
                await page.ClickAsync(".login100-form-btn");
                await Task.Delay(3000);

                // await Task.Delay(1000);

                for (int row = 2; row < rowCount; row++)
                {
                    var name = worksheet.Cells[row, 5].Value?.ToString();
                    var dob = worksheet.Cells[row, 6].Value?.ToString();
                    var nid = worksheet.Cells[row, 7].Value?.ToString();
                    var url = worksheet.Cells[row, 3].Value?.ToString();

                    if (name == null)
                    {
                        break;
                    }

                    await page.GoToAsync(url);
                    await Task.Delay(1000);
                    await page.TypeAsync("input[name=name]", name);
                    await page.TypeAsync("input[name=dob]", dob);
                    await page.TypeAsync("input[name=id]", id);
                    var cellNumber = "H" + row;

                    worksheet.Cells[cellNumber].Value = "Verified";
                    bool dialogAccepted = false;

                    page.Dialog += async (sender, e) =>
                    {
                        if (e.Dialog != null && !dialogAccepted)
                        {
                            await e.Dialog.Accept();
                            dialogAccepted = true;
                        }


                    };




                    await page.ClickAsync("#verify_button_button");
                    await page.WaitForTimeoutAsync(1000);
                    await Task.Delay(3000);


                    if (dialogAccepted)
                    {
                        worksheet.Cells[cellNumber].Value = "Not Verified";
                       
                    }

                    //var button = await page.QuerySelectorAsync("#update_button");
                    //var displayStyle = await button.EvaluateFunctionAsync<string>("element => getComputedStyle(element).display");

                    //if (displayStyle == "block") {
                    //    worksheet.Cells[cellNumber].Value = "Verified";

                    //}

                    //if (button != null)
                    //{
                    //    string initialText = await button.EvaluateFunctionAsync<string>("element => element.textContent");
                    //    await button.ClickAsync();
                    //    await page.WaitForTimeoutAsync(1000);

                    //    string updatedText = await button.EvaluateFunctionAsync<string>("element => element.textContent");

                    //    if (initialText == updatedText)
                    //    {
                    //     worksheet.Cells[cellNumber].Value = "Not Verified";

                    //    }

                    //}
                }

                await browser.CloseAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Automation failed.");
                return View("Error");
            }

           
            package.Save();
            string savePath = @"FilePath";
            System.IO.File.WriteAllBytes(savePath, package.GetAsByteArray());

            return RedirectToAction("UploadFile", "Excel");
        }

Now, the issue with my code is When the Data inputted is valid it is still looking for a dialog or alert which does not appear when the data is valid. Is there any way in puppeteer sharp to check wether the AlertBox is present or not?


Solution

  • Since, in terms of correct data there is no alert/Dialog showing and only in terms of incorrect data the alert is shown . The Alert/Dialog box is dependent on whether submitted data is correct/incorrect. With my previous code, I was getting PuppeteerSharp.MessageException: Protocol error (Page.handleJavaScriptDialog): No dialog is showing exception in terms of correct data submission and as a result my code was getting terminated without performing the complete automation. So, here how I tried to fix it. I simply used a try catch block to catch the exception and it worked.

     page.Dialog += async (sender, e) =>
                        {
                            try
                            {
                                await e.Dialog.Dismiss();
                            }
                            catch (Exception dialogEx)
                            {
                                _logger.LogError(dialogEx, "Error handling dialog.");
                            }
                        };