Tuesday, January 9, 2024

simple Trade using excel

 using UI2023.BaseClasses;
using UI2023.ComponentHelper;
using UI2023.PageObjects;
using UI2023.ParamObjectDTO;
using UI2023.Settings;
using UI2023.Utilities;
using ExcelDataReader;
using NUnit.Framework;
using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Threading;


/*using static System.Runtime.InteropServices.JavaScript.JSType;
using TechTalk.SpecFlow;*/


namespace UI2023.Testcases
{
    [TestFixture]
    public class Login_Logout : BaseClass
    {
        private ThreadLocal<IWebDriver> driver = new ThreadLocal<IWebDriver>();
        private LoginPage loginPage;


        [SetUp]
        public void Intiallize()
        {
            driver.Value = InitWebdriver();
            ExtentTestManager.CreateTest("LoginValidation");
            //    BrowserHelper.NavigateToUrl(".../ClientLogin.aspx", driver.Value);
            ReportLog.Pass("Successfully Navigated to Login Page");
            loginPage = ObjectRepository.LoginPage(driver.Value);
        }


        [Test]
        [Category("Regression")]
        [TestCaseSource(nameof(AddBankAccountsData))]
        public void Fxecute_PSR_Flow(CreateTransactionDTO data)
        {
            Console.WriteLine(data.buyAmount);
            try
            {
                loginPage.LoginToFX("sfl", "gayathrisfl", "Test@1234");


                if (loginPage.isNewDeviceLoginDetected())
                {
                    loginPage.newdeviceokbtn.Click();
                }


                loginPage.clickOnTransactionTab();
                //string FID=loginPage.CreateTask("BRL - BRAZILIAN REAL", "USD - UNITED STATES DOLLAR", "1000", "BRL 01", "Test");
                string FID = loginPage.CreateTask(data.buyCurrency, data.sellCurrency, data.buyAmount, data.deliveryinstruction, data.poptext);
                BrowserHelper.NavigateToUrl(".......Login.aspx", driver.Value);
                loginPage.LoginToFXhost("gayathri.jayaram", "Blackmail@1234");
                //string FID = Current["FID"];
                loginPage.TradeTabClick("4403662");
            }
            catch (Exception ex)
            {
                ReportLog.Fail("Click base64-img button to see error screenshot \n", CaptureScreenshotAndReturnModel("screenshot", driver.Value));
                ReportLog.Fail("Test Case Failed : Login and Logout is not successful -" + ex.Message);
                throw;
            }
        }


        /*    public static IEnumerable<CreateTransactionDTO> AddCreateTaskData()
             {
                 // Path to the Excel file
                 string workingDirectory = Environment.CurrentDirectory;
                 string filePath = Directory.GetParent(workingDirectory).Parent.Parent.FullName + "\\Utilities\\Testdata.xlsx";
                 string sheetName = "CreateTrade"; // Name of the sheet containing the test data


                 // Load the Excel file
                 using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
                 {
                     using (var reader = ExcelReaderFactory.CreateReader(stream))
                    {
                         // Read the test data from the specified sheet
                         DataSet dataSet = reader.AsDataSet();
                         DataTable dataTable = dataSet.Tables[sheetName];
                         bool isFirstRow = true;
                         List<CreateTransactionDTO> CreateTaskData = new List<CreateTransactionDTO>();


                         // Iterate through the rows of the table and create DTO objects
                         foreach (DataRow row in dataTable.Rows)
                         {
                             if (isFirstRow)
                             {
                                 isFirstRow = false;
                                 continue;
                             }


                             CreateTransactionDTO paymentData = new CreateTransactionDTO
                             {
                                 buyCurrency = row[0].ToString(),
                                 sellCurrency = row[1].ToString(),
                                 buyAmount = row[2].ToString(),
                                 sellAmount = row[3].ToString(),
                                 deliveryinstruction = row[4].ToString(),
                                 poptext = row[5].ToString(),
                             };


                             CreateTaskData.Add(paymentData);
                         }


                         return CreateTaskData;
                     }
                 }
             }*/


        public static IEnumerable<CreateTransactionDTO> AddBankAccountsData()
        {
            // Path to the Excel file
            string workingDirectory = Environment.CurrentDirectory;
            string filePath = Directory.GetParent(workingDirectory).Parent.Parent.FullName + "\\Utilities\\Testdata.xlsx";
            string sheetName = "CreateTrade"; // Name of the sheet containing the test data
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            // Load the Excel file
            using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
            {
                using (var reader = ExcelReaderFactory.CreateReader(stream))
                {
                    // Read the test data from the specified sheet
                    DataSet dataSet = reader.AsDataSet();
                    DataTable dataTable = dataSet.Tables[sheetName];
                    bool isFirstRow = true;
                    List<CreateTransactionDTO> createPaymentDataList = new List<CreateTransactionDTO>();


                    // Iterate through the rows of the table and create DTO objects
                    foreach (DataRow row in dataTable.Rows)
                    {
                        if (isFirstRow)
                        {
                            isFirstRow = false;
                            continue;
                        }


                        CreateTransactionDTO paymentData = new CreateTransactionDTO
                        {
                            buyCurrency = row[0].ToString(),
                            sellCurrency = row[1].ToString(),
                            buyAmount = row[2].ToString(),
                            sellAmount = row[3].ToString(),
                            deliveryinstruction = row[4].ToString(),
                            poptext = row[5].ToString()
                        };


                        createPaymentDataList.Add(paymentData);
                    }


                    return createPaymentDataList;
                }
            }
        }


        [TearDown]
        public void Cleanup()
        {
            if (driver.Value != null)
            {
                driver.Value.Quit();
                QuitDriverProcess();
            }
        }
    }
}
x


Friday, September 15, 2023

selenium c# methods

using GMRUI.Settings;
using NPOI.XSSF.UserModel;
using OfficeOpenXml;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using SeleniumExtras.WaitHelpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;

 

namespace GMRUI.ComponentHelper
{
    public class GenericHelper
    {
        public IWebDriver Driver;

 

        public GenericHelper(IWebDriver driver)
        {
            Driver = driver;
        }

 

        public Func<IWebDriver, bool> WaitForWebElementFunc(By locator)
        {
            return ((x) =>
            {
                if (x.FindElements(locator).Count == 1)
                    return true;
                return false;
            });
        }

 

        public Func<IWebDriver, IWebElement> WaitForWebElementInPageFunc(By locator)
        {
            return ((x) =>
            {
                if (x.FindElements(locator).Count == 1)
                    return x.FindElement(locator);
                return null;
            });
        }

 

        public WebDriverWait GetWebdriverWait(TimeSpan timeout)
        {
            Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1);
            WebDriverWait wait = new WebDriverWait(Driver, timeout)
            {
                PollingInterval = TimeSpan.FromMilliseconds(500),
            };
            wait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(ElementNotVisibleException));
            return wait;
        }

 

        public bool IsElemetPresent(By locator)
        {
            Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
            try
            {
                var X = Driver.FindElement(locator).Displayed;
                var Y = Driver.FindElements(locator).Count;
                return Driver.FindElements(locator).Count == 1 | Driver.FindElement(locator).Displayed;
            }
            catch (Exception)
            {
                return false;
            }
        }

 

        public bool IsElemetPresentDisp(IWebElement element)
        {
            try
            {
                return element.Displayed;
            }
            catch (NoSuchElementException)
            {
                return false;
            }
        }

 

        public bool IsElemetPresentExists(ISearchContext searchContext, By element)
        {
            try
            {
                return searchContext.FindElement(element).Displayed;
            }
            catch (NoSuchElementException)
            {
                return false;
            }
        }

 

        public bool IsElemetPresentDisplayed(IWebElement element)
        {
            try
            {
                //ObjectRepository.GenericHelper(driver.Value).ImplicitWait(10);
                return element.Displayed;
            }
            catch (Exception)
            {
                return false;
            }
        }

 

        public void setDriver(IWebDriver driver)
        {
            Driver = driver;
        }

 

        public void WaitforJSPageLoadComplete()
        {
            Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
            WebDriverWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(1));
            wait.Until(driver1 => ((IJavaScriptExecutor)Driver).ExecuteScript("return document.readyState").Equals("complete"));
        }

 

        public void WaitForAjaxComplete()
        {n
            IWait<IWebDriver> wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(45.00));
            wait.Until(d => (bool)(d as IJavaScriptExecutor).ExecuteScript("return jQuery.active == 0"));
        }

 

        public IWebElement GetElement(By locator)
        {
            if (IsElemetPresent(locator))
                return Driver.FindElement(locator);
            else
                throw new NoSuchElementException("Element Not Found : " + locator.ToString());
        }

 

        public bool WaitForWebElement(By locator, TimeSpan timeout)
        {
            Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1);
            var wait = GetWebdriverWait(timeout);
            var flag = wait.Until(WaitForWebElementFunc(locator));
            Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(ObjectRepository.Config.GetElementLoadTimeOut());
            return flag;
        }

 

        public IWebElement WaitForWebElementInPage(By locator, TimeSpan timeout)
        {
            Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1);
            var wait = GetWebdriverWait(timeout);
            var flag = wait.Until(WaitForWebElementInPageFunc(locator));
            Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(ObjectRepository.Config.GetElementLoadTimeOut());
            return flag;
        }

 

        public void ScrollToElement(IWebElement element)
        {
            try
            {
                ((IJavaScriptExecutor)Driver).ExecuteScript("arguments[0].scrollIntoView(true);", element);
            }
            catch (Exception)
            {
                //throw new NoSuchElementException("Element View Not Found : ");
            }
        }

 

        public void ClickUsingJS(IWebElement element)
        {
            try
            {
                ((IJavaScriptExecutor)Driver).ExecuteScript("arguments[0].click();", element);
            }
            catch (Exception)
            {
                throw new NoSuchElementException("Element Not Clicked :");
            }
        }

 

        public void SetValueUsingJS(IWebElement element, String value)
        {
            try
            {
                ((IJavaScriptExecutor)Driver).ExecuteScript($"arguments[0].value='{value}';", element);
            }
            catch (Exception)
            {
                throw new NoSuchElementException("Element Not Clicked :");
            }
        }

 

        public void SetAttibuteUsingJS(IWebElement element, String value)
        {
            try
            {
                ((IJavaScriptExecutor)Driver).ExecuteScript($"arguments[0].setAttribute('value','{value}');", element);
            }
            catch (Exception)
            {
                throw new NoSuchElementException("Element Not Clicked :");
            }
        }

 

        public void RefreshPage()
        {
            Driver.Navigate().Refresh();
        }

 

        public void ImplicitWait(int seconds = 60)
        {
            Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(seconds);
        }

 

        public void WaitforPageLoadCompletely(int time = 45)
        {
            WebDriverWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(time));
            wait.Until(driver1 => ((IJavaScriptExecutor)Driver).ExecuteScript("return document.readyState").Equals("complete"));
        }

 

        public void WaitForAnElementToBeClickable(IWebElement element, int seconds = 10)

 

        {
            try

 

            {
                DefaultWait<IWebDriver> fluentWait = new DefaultWait<IWebDriver>(Driver);

 

                fluentWait.Timeout = TimeSpan.FromSeconds(seconds);

 

                fluentWait.PollingInterval = TimeSpan.FromMilliseconds(1000);

 

                fluentWait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(StaleElementReferenceException));

 

                fluentWait.Message = "Element to be searched not found";

 

                fluentWait.Until(ExpectedConditions.ElementToBeClickable(element));
            }
            catch (Exception)
            {
                ImplicitWait(0);
                // Assert.IsTrue(element.Displayed,"Webelement is not displayed");
            }
        }

 

        public void WaitForAnElementToBeClickable1(IWebElement element)

 

        {
            DefaultWait<IWebDriver> fluentWait = new DefaultWait<IWebDriver>(Driver);

 

            fluentWait.Timeout = TimeSpan.FromMinutes(1);

 

            fluentWait.PollingInterval = TimeSpan.FromMilliseconds(300);

 

            fluentWait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(StaleElementReferenceException));

 

            fluentWait.Message = "Element to be searched not found";

 

            fluentWait.Until(ExpectedConditions.ElementToBeClickable(element));
        }

 

        public void ScrollToBottom()

 

        {
            ((IJavaScriptExecutor)Driver).ExecuteScript("window.scroll(0, document.body.scrollHeight)");
        }

 

        public void ScrollToTop()

 

        {
            ((IJavaScriptExecutor)Driver).ExecuteScript("window.scroll(0, document.body.scrollTop)");
        }

 

        public void WaitExplicitely(IWebElement element)
        {
            DefaultWait<IWebElement> wait = new DefaultWait<IWebElement>(element);
            wait.Timeout = TimeSpan.FromMinutes(1);
            wait.PollingInterval = TimeSpan.FromMilliseconds(250);
            Func<IWebElement, bool> condition = new Func<IWebElement, bool>((IWebElement ele) =>
            {
                if (element.Displayed && element.Enabled)
                {
                    return true;
                }

 

                return false;
            });
            wait.Until(condition);
        }

 

        public bool IsAlertPresent()
        {
            try
            {
                Driver.SwitchTo().Alert();
                return true;
            }
            catch (NoAlertPresentException)
            {
                return false;
            }
        }

 

        public void CloseAlert()
        {
            IAlert alert = Driver.SwitchTo().Alert();
            alert.Accept();
        }

 

        public void CancelAlert()
        {
            IAlert alert = Driver.SwitchTo().Alert();
            alert.Dismiss();
        }

 

        public decimal CustomRoundOff(decimal x)
        {
            decimal gmr = Math.Truncate(x * 100) / 100;
            decimal gmrDecPlaces = Math.Truncate(x * 1000) / 1000;
            decimal t = (gmrDecPlaces * 1000) % 10;
            if (t >= 6)
                gmr += 0.01m;
            return gmr;
        }

 

        public string ConvertToStringByCustomRoundOff(string value, int x = 3)
        {
            string result = decimal.Round(decimal.Parse(value), x).ToString();
            return result;
        }

 

        public string GetDate(string Date, string Format)
        {
            string input = Date;
            DateTime d;
            if (DateTime.TryParseExact(input, "MMM dd,yy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out d))
            {
                return d.ToString("mm.dd.yy");
            }

 

            return d.ToString("mm.dd.yy");
        }

 

        public string ConvertDateFormat(string Date, string Expected)
        {
            try
            {
                DateTime d = DateTime.Parse(Date);
                string x = d.ToString(Expected);
                return d.ToString(Expected);
            }
            catch (Exception)
            {
                return DateTime.Parse(Date).ToString(Expected);
            }
        }

 

        public string ConvertDateFormat(string Date)
        {
            String[] s = Date.Split('/');
            return string.Format("{0}.{1}.{2}", s[1].TrimStart('0').Trim(), s[0].TrimStart('0').Trim(), s[2].Trim());
        }

 

        public string GetDate(string ExpectedFormat)
        {
            try
            {
                DateTime d = DateTime.Parse(DateTime.Now.ToString());
                return d.ToString(ExpectedFormat);
            }
            catch (Exception)
            {
                return DateTime.Parse(DateTime.Now.ToString()).ToString(ExpectedFormat);
            }
        }

 

        public string GetNumericData(string text)
        {
            string value = Regex.Replace(text, "[A-Za-z ]", "");
            return value.Trim();
        }

 

        public string GetAlphaChars(string text)
        {
            string value = Regex.Replace(text, "[^a-zA-Z]", "");
            return value.Trim();
        }

 

        public string TrimLastCharacter(String str)
        {
            if (String.IsNullOrEmpty(str))
            {
                return str;
            }
            else
            {
                return str.TrimEnd(str[str.Length - 1]);
            }
        }

 

        public void OpenNewTab()
        {
            ((IJavaScriptExecutor)Driver).ExecuteScript("window.open();");
            Driver.SwitchTo().Window(Driver.WindowHandles.Last());
        }

 

        public string GetTPlus2DaysDate()
        {
            DateTime currentDate = DateTime.Now;
            DateTime tPlus2Date = currentDate.AddDays(2);

 

            // Check if the date is a weekend day
            while (tPlus2Date.DayOfWeek == DayOfWeek.Saturday || tPlus2Date.DayOfWeek == DayOfWeek.Sunday)
            {
                // If it is a weekend day, add another day
                tPlus2Date = tPlus2Date.AddDays(1);
            }
            return tPlus2Date.ToString("MMM dd yyyy");
        }

 

        public bool WaitForFileDownLoad(string fileName = "Confirmed.xlsx", string path = @"C:\Downloads", int timeout = 30)
        {
            //Wait for the file to download completely
            bool isFileDownloaded = false;

 

            while (timeout > 0 && !isFileDownloaded)
            {
                isFileDownloaded = Directory.GetFiles(path, fileName, SearchOption.AllDirectories).Length > 0;
                timeout--;
                Thread.Sleep(1000); //wait for 1 second
            }
            //Verify that the file has been downloaded successfully
            return isFileDownloaded;
        }

 

        public int GetRowsCountFromExcel(string fileName, string downloadPath = @"C:\Downloads")
        {
            /* //Read the downloaded Excel file and count the rows
             string filePath = Path.Combine(downloadPath, fileName);
             ExcelPackage excelPackage = new ExcelPackage(new FileInfo(filePath));
             ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets[0];
             int rowCount = worksheet.Dimension.Rows; */
            string filePath = Path.Combine(downloadPath, fileName);
            XSSFWorkbook workBook = new XSSFWorkbook(File.Open(filePath, FileMode.Open));
            var sheet = workBook.GetSheetAt(0);
            int count = sheet.LastRowNum + 1;
            //Clean up: delete the downloaded file
            FileDelete(filePath);
            return count;
        }

 

        public void FileDelete(string filePath)
        {
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
        }

 

        public void WaitUntilVisible(By locator, int seconds = 10)
        {
            DefaultWait<IWebDriver> fluentWait = new DefaultWait<IWebDriver>(Driver);
            fluentWait.Timeout = TimeSpan.FromSeconds(seconds);
            fluentWait.PollingInterval = TimeSpan.FromMilliseconds(250);
            /* Ignore the exception - NoSuchElementException that indicates that the element is not present */
            fluentWait.IgnoreExceptionTypes(typeof(NoSuchElementException));
            fluentWait.Message = "Element to be searched not found";
            fluentWait.Until(ExpectedConditions.ElementIsVisible(locator));
            fluentWait.Until(ExpectedConditions.ElementToBeClickable(locator));
        }

 

        public void WaitUntilInVisible(By locator, int seconds = 15)
        {
            DefaultWait<IWebDriver> fluentWait = new DefaultWait<IWebDriver>(Driver);
            fluentWait.Timeout = TimeSpan.FromSeconds(seconds);
            fluentWait.PollingInterval = TimeSpan.FromMilliseconds(250);
            /* Ignore the exception - NoSuchElementException that indicates that the element is not present */
            fluentWait.IgnoreExceptionTypes(typeof(NoSuchElementException));
            fluentWait.Message = "Element to be searched not found";
            fluentWait.Until(ExpectedConditions.InvisibilityOfElementLocated(locator));
        }

 

        public List<List<string>> ReadExcelFileData(string filePath)

 

        {
            List<List<string>> excelData = new List<List<string>>();

 

            FileInfo fileInfo = new FileInfo(filePath);

 

            using (ExcelPackage package = new ExcelPackage(fileInfo))

 

            {
                ExcelWorksheet worksheet = package.Workbook.Worksheets.FirstOrDefault();

 

                if (worksheet != null)

 

                {
                    int rowCount = worksheet.Dimension.Rows;

 

                    int columnCount = worksheet.Dimension.Columns;

 

                    for (int row = 1; row <= rowCount; row++)

 

                    {
                        List<string> rowData = new List<string>();

 

                        for (int col = 1; col <= columnCount; col++)

 

                        {
                            string cellValue = worksheet.Cells[row, col].Text;

 

                            rowData.Add(cellValue);
                        }

 

                        excelData.Add(rowData);
                    }
                }
            }

 

            return excelData;
        }

 

        public List<String> ReadExcelDataRow(string FilePath, int Row)
        {
            return ReadExcelFileData(FilePath)[Row];
        }

 

        public bool CheckFileExits(string FolderPath, string PartOfFileName)
        {
            string[] downloadedFiles = Directory.GetFiles(FolderPath);

 

            bool fileFound = false;
            foreach (string fileName in downloadedFiles)
            {
                if (Path.GetFileName(fileName).Contains(PartOfFileName))
                {
                    fileFound = true;
                    break;
                }
            }
            return fileFound;
        }

 

        public static bool AreListsEqual<T>(List<T> expectedList, List<T> actualList)
        {
            if (expectedList.Count != actualList.Count)
            {
                return false;
            }

 

            for (int i = 0; i < expectedList.Count; i++)
            {
                if (!EqualityComparer<T>.Default.Equals(expectedList[i], actualList[i]))
                {
                    return false;
                }
            }

 

            return true;
        }
    }
}

Thursday, September 14, 2023

draft

public void VerifyIndexNumberFacetFiltersResultsForViewables()
        {
            try
            {
                bool status = WaitUntilElementVisible(IndexNumberFacetFilter);
                if (status == true)
                {
                    int i = 0;
                step1: WaitUntilElementVisible(IndexNumberFacetFilter);
                    var IndexNumberFilters = _driver.FindElements(IndexNumberFacetFilter);
                    WaitUntilElementVisible(IndexNumberFacetFilterCount);
                    var IndexNumberFiltersCount = _driver.FindElements(IndexNumberFacetFilterCount);
                    //for (; i < BusinessUnitFilters.Count - 1;)
                    for (; i < 3;)
{
                        string text = IndexNumberFilters[i].Text;
                        string count = IndexNumberFiltersCount[i].Text;
                        IndexNumberFilters[i].Click();
                        Thread.Sleep(5000);
                        WaitUntilElementVisible(ResultCounter);
                        string resultCounter = _driver.FindElement(ResultCounter).Text;
                        Assert.IsTrue(resultCounter.Contains(count), "Result Count has mismatch for Index Number : " + text);
                        WaitUntilElementVisible(IndexNumberMetaDataTag);
                        var IndexNumberMetaDataTags = _driver.FindElements(IndexNumberMetaDataTag);
                        foreach (var list in IndexNumberMetaDataTags)
{
                            string TagName = list.Text;
                            Assert.IsTrue(TagName.Contains(text), "MetadataTag :" + TagName + " is not matching with Selected IndexNumber :" + text);

                        }

                        WaitUntilElementVisible(RemoveBreadcrumbsecondButton);
                        click(RemoveBreadcrumbsecondButton);
                        Thread.Sleep(3000);

                        i++;
                        goto step1;

                    }
                }

Wednesday, September 13, 2023

custom columns export verification

public void CheckCustomColumnsExcelDownloadRandom(string InputBoxValue)
        {
            WaitUntilElementVisible(ManageSavedQueriesButton);
            click(ManageSavedQueriesButton);
            WaitUntilElementVisible(ExportButton);
            click(ExportButton);
            SelectElement selectColumns = new SelectElement(_driver.FindElement(ExportColumns));
            List<string> CoulumnsToExport = new List<string>();
            var exportColumns = selectColumns.Options;
            foreach (var ele1 in exportColumns)
            {
                Console.WriteLine("List of Columns:" + ele1.Text);
                string firstValue = ele1.Text;
                CoulumnsToExport.Add(firstValue);
            }SelectElement selectElement = new SelectElement(_driver.FindElement(ExportOutputFormat));
            selectElement.SelectByText("XLSX");

            List<string> RandomColumnsToExport = new List<string>();
            Random random = new Random();
            for (int i = 1; i <= 3; i++)
            { 
                RandomColumnsToExport.Add(CoulumnsToExport[random.Next(0, CoulumnsToExport.Count)]); 

            }

            SelectRandomColumnsForExport(RandomColumnsToExport);

            WaitUntilElementVisible(ExportDownloadButton);
            click(ExportDownloadButton);

            string projectDir = Directory.GetCurrentDirectory();
            Console.WriteLine(projectDir);
            Assert.IsTrue(CheckIfFileExists(projectDir + "\\export_" + InputBoxValue + ".xlsx"));
public void SelectRandomColumnsForExport(List<string> RandomColumns)
        {

            Actions action = new Actions(_driver);
            action.KeyDown(Keys.Control);
            for (int i = 0; i < RandomColumns.Count; i++)
            {
                Console.WriteLine(RandomColumns[i]);
             action.Click(_driver.FindElement(By.XPath($"//option[.='{RandomColumns[i]}']"))); 
            }
            action.KeyDown(Keys.Control).Build().Perform();
        }

Monday, September 11, 2023

Excel read using epplus /json

Import license related line before you read excel file 



csharp
Copy code
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

public class ExcelReader
{
    public List<List<string>> ReadExcelFile(string filePath)
    {
        List<List<string>> excelData = new List<List<string>>();

        FileInfo fileInfo = new FileInfo(filePath);
        using (ExcelPackage package = new ExcelPackage(fileInfo))
        {
            ExcelWorksheet worksheet = package.Workbook.Worksheets.FirstOrDefault();

            if (worksheet != null)
            {
                int rowCount = worksheet.Dimension.Rows;
                int columnCount = worksheet.Dimension.Columns;

                for (int row = 1; row <= rowCount; row++)
                {
                    List<string> rowData = new List<string>();
                    for (int col = 1; col <= columnCount; col++)
                    {
                        string cellValue = worksheet.Cells[row, col].Text;
                        rowData.Add(cellValue);
                    }
                    excelData.Add(rowData);
                }
            }
        }

        return excelData;
    }


Call

LIST<string > colum =ReadExcelFile(string filePath)[0] 



Friday, September 8, 2023

csv header check

static void checkHeaders()
    {
        string[] providedHeaders = 
        {
            "Title", "Document Type", "Modified", "Department", "Authors", "Url",
            "Country", "City", "Subdivision", "File Type", "Product Type", "Language",
            "Index Number", "Inspection Type", "Account Number", "Business Title",
            "Visit Type", "Filename"
        };

        string csvPath = "/path/to/your/csv/file.csv"; // Replace with your actual file path
        
        // Read the first line to get the headers
        string firstLine = File.ReadLines(csvPath).FirstOrDefault();
        
        char detectedDelimiter = new[] { ';', ',', '\t' }.OrderByDescending(d => firstLine.Count(c => c == d)).First();

        // Split the headers using the detected delimiter and trim spaces
        string[] csvHeaders = firstLine.Split(detectedDelimiter).Select(h => h.Trim()).ToArray();

        // Assert that headers match
        Debug.Assert(csvHeaders.SequenceEqual(providedHeaders), "Headers do not match!");
        Console.WriteLine("Headers match successfully!");
    }

multiple drop down values selection using control click

// Assuming you have an HTML select element with multiple options
IWebElement multiSelectDropdown = driver.FindElement(By.Id("multiSelectDropdown"));

// To select multiple options, hold down the Control key while clicking
Actions actions = new Actions(driver);
actions.KeyDown(Keys.Control)
       .Click(multiSelectDropdown.FindElement(By.XPath("//option[@value='value1']")))
       .Click(multiSelectDropdown.FindElement(By.XPath("//option[@value='value2']")))
       .Click(multiSelectDropdown.FindElement(By.XPath("//option[@value='value3']")))
       .KeyUp(Keys.Control)
       .Build()
       .Perform();
=≠=====++++other way ======
IWebElement dropdown = driver.FindElement(By.Id("yourDropdownId"));
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;

// Replace "value1", "value2", etc. with the values of the options you want to select
string[] valuesToSelect = new string[] { "value1", "value2", "value3" };

foreach (string value in valuesToSelect)
{
    string script = $"arguments[0].querySelector(\"option[value='{value}']\").selected = true;";
    js.ExecuteScript(script, dropdown);
}