Friday, June 30, 2023

Generate text files

 using System.Reflection;


namespace TestProject1

{

    public class Tests

    {


  

       

            string content = @""




        [Test]

        public void Test1()

        {

            GenerateFinFiles(5);

            GenerateFilesWithContent(100);

            Console.WriteLine(content);

        }




/*

        [SetUp]

        public void Setup()

        {

            Console

            GenerateFilesWithContent(100);

        }


        [Test]

        public void Test1()

        {

            Assert.Pass();

            Console.WriteLine(MethodBase.GetCurrentMethod().Name);

        }


        [TearDown]

        public void tearDown()

        {

            Console.WriteLine(MethodBase.GetCurrentMethod().Name);

        }


*/

       

            

        


        static void GenerateFilesWithContent(int numFiles)

        {

            // Generate unique names

            string[] fileNames = GenerateUniqueNames(numFiles);


            // Generate content and write to files

            foreach (string fileName in fileNames)

            {

                string content = GenerateContent(fileName);

                File.WriteAllText(fileName, content);

            }


            Console.WriteLine($"Generated {fileNames.Length} files with unique names.");

        }


        static string[] GenerateUniqueNames(int numFiles)

        {

            string[] fileNames = new string[numFiles];

            for (int i = 0; i < numFiles; i++)

            {

                fileNames[i] = $"file_{i + 1}.fin";

            }

            return fileNames;

        }


        static string GenerateContent(string fileName)

        {

            string dynamicField1 = "Dynamic Field 1";

            string dynamicField2 = "Dynamic Field 2";

            string content = $"This is the content of {fileName} with dynamic field 1: {dynamicField1} and dynamic field 2: {dynamicField2}";

            return content;

        }



        static void GenerateFinFiles(int numFiles)

        {

            string folderPath = "C:\\MT103";

            //Directory.GetCurrentDirectory();

            int amount = 2000;            

            String Currency = "MXN";



            for (int i = 1; i <= numFiles; i++)

            {

                var x = amount + i;

                

                string fileName = $"{Currency}_file_{x}.fin";

                string filePath = Path.Combine(folderPath, fileName);

                string dynamicField1 = amount + 1.ToString();

                string dynamicField2 = amount+1.ToString();

                string content = $@"";


                File.WriteAllText(filePath, content);

            }


            Console.WriteLine($"Generated {numFiles} .fin files in the folder: {folderPath}");

        }


        static void GenerateFinFiles1(int numFiles)

        {

            string folderPath = "C:\\MT103";//Directory.GetCurrentDirectory();

            int amount = 2000;



            for (int i = 1; i <= numFiles; i++)

            {

                var x = amount + i;

                string fileName = $"MXN_file_{x}.fin";

                string filePath = Path.Combine(folderPath, fileName);

                string dynamicField1 = amount+1.ToString();

                string dynamicField2 = $"Dynamic Field 2 for file {i}";

            


                File.WriteAllText(filePath, content);

            }


            Console.WriteLine($"Generated {numFiles} .fin files in the folder: {folderPath}");

        }

    }


}


Tuesday, June 20, 2023

nunit with c#

To add extent reports to the existing code, you need to include the ExtentReports and ExtentTest libraries, initialize the ExtentReports object, and create ExtentTest instances for reporting the test status. Here's an updated version of the code with Extent Reports integration:

```csharp
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using AventStack.ExtentReports;
using AventStack.ExtentReports.Reporter;
using System.Threading;

namespace FacebookTests
{
    [TestFixture]
    [Parallelizable(ParallelScope.Fixtures)]
    public class FacebookBaseTest
    {
        protected IWebDriver driver;
        protected ExtentReports extent;
        protected ExtentTest test;

        [OneTimeSetUp]
        public void OneTimeSetup()
        {
            // Initialize ExtentReports with HTML reporter
            var htmlReporter = new ExtentHtmlReporter("TestReport.html");
            extent = new ExtentReports();
            extent.AttachReporter(htmlReporter);
        }

        [OneTimeTearDown]
        public void OneTimeCleanup()
        {
            // Flush the ExtentReports instance to generate the report
            extent.Flush();
        }

        [SetUp]
        public void Setup()
        {
            // Initialize ChromeDriver
            driver = new ChromeDriver();

            // Maximize the browser window
            driver.Manage().Window.Maximize();

            // Create a new ExtentTest for the current test
            test = extent.CreateTest(TestContext.CurrentContext.Test.Name);
        }

        [TearDown]
        public void Cleanup()
        {
            // Close the browser
            driver.Quit();

            // End the ExtentTest for the current test
            test.Log(Status.Info, "Test completed");

            // Get the result of the test and log it accordingly
            var result = TestContext.CurrentContext.Result.Outcome;
            if (result == ResultState.Success)
                test.Pass("Test Passed");
            else if (result == ResultState.Failure)
            {
                test.Fail("Test Failed");
                test.AddScreenCaptureFromPath(CaptureScreenshot());
            }
            else if (result == ResultState.Inconclusive || result == ResultState.Skipped)
                test.Skip("Test Skipped");
        }

        protected string CaptureScreenshot()
        {
            // Capture and save a screenshot of the current browser window
            var screenshot = ((ITakesScreenshot)driver).GetScreenshot();
            var screenshotPath = $"Screenshots/{TestContext.CurrentContext.Test.Name}.png";
            screenshot.SaveAsFile(screenshotPath, ScreenshotImageFormat.Png);
            return screenshotPath;
        }

        protected void WaitForElementDisplayed(By locator)
        {
            // Wait for an element to be displayed on the page
            var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
            wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(locator));
        }
    }

    public class FacebookPostTests : FacebookBaseTest
    {
        private LoginPage loginPage;
        private HomePage homePage;

        [SetUp]
        public void TestSetup()
        {
            // Initialize page objects
            loginPage = new LoginPage(driver);
            homePage = new HomePage(driver);
        }

        [Test]
        public void PostOnFacebookTest()
        {
            // Navigate to Facebook
            driver.Navigate().GoToUrl("https://www.facebook.com");

            // Perform login
            loginPage.Login("your_username", "your_password");

            // Post a message on Facebook
            homePage.PostStatus("Hello, Facebook!");

            // Wait for the post to be created
            WaitForElementDisplayed(By.XPath($"//*[contains(text(), 'Hello, Facebook!')]"));

            // Assert that the post was successfully created
            Assert.IsTrue(homePage.IsPost

Friday, June 16, 2023

read data from excel and parallel in c#

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace FacebookLoginTests
{
    [TestFixture]
    public class LoginTests
    {
        private ChromeDriver[] drivers;

        [OneTimeSetUp]
        public void Setup()
        {
            drivers = new ChromeDriver[4];

            // Start four Chrome instances
            for (int i = 0; i < 4; i++)
            {
                ChromeOptions options = new ChromeOptions();
                drivers[i] = new ChromeDriver(options);
            }
        }

        [OneTimeTearDown]
        public void Cleanup()
        {
            // Quit all Chrome instances
            foreach (var driver in drivers)
            {
                driver.Quit();
            }
        }

        [TestCaseSource(nameof(UserCredentialsData))]
        public void LoginTest(UserCredentials credentials)
        {
            Parallel.ForEach(drivers, (driver) =>
            {
                driver.Navigate().GoToUrl("https://www.facebook.com");
                LoginPage loginPage = new LoginPage(driver);
                HomePage homePage = loginPage.Login(credentials.Username, credentials.Password);

                // Assert the login was successful
                Assert.IsTrue(homePage.IsLoggedIn());
            });
        }

        private static IEnumerable<UserCredentials> UserCredentialsData()
        {
            // Define usernames and passwords
            yield return new UserCredentials("username1", "password1");
            yield return new UserCredentials("username2", "password2");
            yield return new UserCredentials("username3", "password3");
            yield return new UserCredentials("username4", "password4");
        }
    }

    // Data Model

    public class UserCredentials
    {
        public string Username { get; set; }
        public string Password { get; set; }

        public UserCredentials(string username, string password)
        {
            Username = username;
            Password = password;
        }
    }

    // Page Object Model (POM) classes

    public class LoginPage
    {
        private IWebDriver driver;
        private By emailInput = By.Id("email");
        private By passwordInput = By.Id("pass");
        private By loginButton = By.Id("loginbutton");

        public LoginPage(IWebDriver driver)
        {
            this.driver = driver;
        }

        public HomePage Login(string username, string password)
        {
            driver.FindElement(emailInput).SendKeys(username);
            driver.FindElement(passwordInput).SendKeys(password);
            driver.FindElement(loginButton).Click();

            return new HomePage(driver);
        }
    }

    public class HomePage
    {
        private IWebDriver driver;
        private By profileLink = By.XPath("//a[@title='Profile']");

        public HomePage(IWebDriver driver)
        {
            this.driver = driver;
        }

        public bool IsLoggedIn()
        {
            return driver.FindElement(profileLink).Displayed;
        }
    }
}

parallel execute of chrome in c#

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace FacebookLoginTests
{
    [TestFixture]
    public class LoginTests
    {
        private ChromeDriver[] drivers;

        [OneTimeSetUp]
        public void Setup()
        {
            drivers = new ChromeDriver[4];

            // Start four Chrome instances
            for (int i = 0; i < 4; i++)
            {
                ChromeOptions options = new ChromeOptions();
                drivers[i] = new ChromeDriver(options);
            }
        }

        [OneTimeTearDown]
        public void Cleanup()
        {
            // Quit all Chrome instances
            foreach (var driver in drivers)
            {
                driver.Quit();
            }
        }

        [TestCaseSource(nameof(UserCredentialsData))]
        public void LoginTest(UserCredentials credentials)
        {
            Parallel.ForEach(drivers, (driver) =>
            {
                driver.Navigate().GoToUrl("https://www.facebook.com");
                LoginPage loginPage = new LoginPage(driver);
                HomePage homePage = loginPage.Login(credentials.Username, credentials.Password);

                // Assert the login was successful
                Assert.IsTrue(homePage.IsLoggedIn());
            });
        }

        private static IEnumerable<UserCredentials> UserCredentialsData()
        {
            // Define usernames and passwords
            yield return new UserCredentials("username1", "password1");
            yield return new UserCredentials("username2", "password2");
            yield return new UserCredentials("username3", "password3");
            yield return new UserCredentials("username4", "password4");
        }
    }

    // Data Model

    public class UserCredentials
    {
        public string Username { get; set; }
        public string Password { get; set; }

        public UserCredentials(string username, string password)
        {
            Username = username;
            Password = password;
        }
    }

    // Page Object Model (POM) classes

    public class LoginPage
    {
        private IWebDriver driver;
        private By emailInput = By.Id("email");
        private By passwordInput = By.Id("pass");
        private By loginButton = By.Id("loginbutton");

        public LoginPage(IWebDriver driver)
        {
            this.driver = driver;
        }

        public HomePage Login(string username, string password)
        {
            driver.FindElement(emailInput).SendKeys(username);
            driver.FindElement(passwordInput).SendKeys(password);
            driver.FindElement(loginButton).Click();

            return new HomePage(driver);
        }
    }

    public class HomePage
    {
        private IWebDriver driver;
        private By profileLink = By.XPath("//a[@title='Profile']");

        public HomePage(IWebDriver driver)
        {
            this.driver = driver;
        }

        public bool IsLoggedIn()
        {
            return driver.FindElement(profileLink).Displayed;
        }
    }
}

Thursday, June 15, 2023

Reusable selenium methods

  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[] 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 void DeleteallCookies()

        {

            _driver.Manage().Cookies.DeleteAllCookies();

            Thread.Sleep(5000);

            RefreshPage();

        }


        public void SwitchToParent()

        {

            var windowids = _driver.WindowHandles;


            for (int i = windowids.Count - 1; i > 0;)

            {

                _driver.Close();

                i = i - 1;

                ImplicitWait();

                _driver.SwitchTo().Window(windowids[i]);

            }

            _driver.SwitchTo().Window(windowids[0]);

        }


        public void SwitchToParentWindow()

        {

            ImplicitWait(10);

            var windowids = _driver.WindowHandles;


            for (int i = windowids.Count - 1; i > 0;)

            {

                i = i - 1;

                ImplicitWait();

                _driver.SwitchTo().Window(windowids[i]);

            }

            _driver.SwitchTo().Window(windowids[0]);

        }


        public void SwitchToOtherWindow()

        {

            ImplicitWait(10);

            IReadOnlyCollection<string> windowids = _driver.WindowHandles;

            string Current = _driver.CurrentWindowHandle;


            foreach (var item in windowids)

            {

                if (!item.Equals(Current))

                {

                    _driver.SwitchTo().Window(item);

                }

            }

        }


        public void SwitchTotWindow(int w)

        {

            var windowids = _driver.WindowHandles;

            _driver.SwitchTo().Window(windowids[w]);

        }


        public void SwitchToFrame(By locator)

        {

            _driver.SwitchTo().Frame(_driver.FindElement(locator));

        }


        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

            File.Delete(filePath);

            return count;

        }


        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 deleteAllCookiesAndRefresh()

        {

            _driver.Manage().Cookies.DeleteAllCookies();

            _driver.Navigate().Refresh();

        }

Tuesday, June 13, 2023

appium

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.touch.offset.PointOption;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Point;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.net.MalformedURLException;
import java.net.URL;

public class NaukriLoginTest {

    private static AppiumDriver<MobileElement> driver;

    public static void main(String[] args) throws MalformedURLException {
        // Set the desired capabilities
        DesiredCapabilities caps = new DesiredCapabilities();
        caps.setCapability("deviceName", "Your_Device_Name");
        caps.setCapability("platformName", "Android");
        caps.setCapability("platformVersion", "Your_Android_Version");
        caps.setCapability("appPackage", "com.naukri.android");
        caps.setCapability("appActivity", "com.naukri.dashboard.home.HomeActivity");

        // Initialize the Appium driver
        driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), caps);

        // Perform the login steps
        MobileElement signInButton = findElementById("com.naukri.android:id/home_menu_signin");
        signInButton.click();

        MobileElement emailField = findElementById("com.naukri.android:id/txtLogin");
        emailField.sendKeys("your_email@example.com");

        MobileElement passwordField = findElementById("com.naukri.android:id/txtPassword");
        passwordField.sendKeys("your_password");

        MobileElement loginButton = findElementById("com.naukri.android:id/btnLogin");
        loginButton.click();

        // Verify successful login
        MobileElement userProfile = findElementById("com.naukri.android:id/menu_profile");
        if (userProfile.isDisplayed()) {
            System.out.println("Login successful!");
        } else {
            System.out.println("Login failed!");
        }

        // Scroll down
        scrollDown();

        // Scroll up
        scrollUp();

        // Scroll left
        scrollLeft();

        // Scroll right
        scrollRight();

        // Quit the driver
        driver.quit();
    }

    private static MobileElement findElementById(String id) {
        return driver.findElementById(id);
    }

    private static void scrollDown() {
        Dimension size = driver.manage().window().getSize();
        int starty = (int) (size.height * 0.8);
        int endy = (int) (size.height * 0.2);
        int startx = size.width / 2;
        driver.swipe(startx, starty, startx, endy, 1000);
    }

    private static void scrollUp() {
        Dimension size = driver.manage().window().getSize();
        int starty = (int) (size.height * 0.2);
        int endy = (int) (size.height * 0.8);
        int startx = size.width / 2;
        driver.swipe(startx, starty, startx, endy, 1000);
    }

    private static void scrollLeft() {
        Dimension size = driver.manage().window().getSize();
        int startx = (int) (size.width * 0.8);
        int endx = (int) (size.width * 0.2);
        int starty = size.height / 2;
        driver.swipe(startx, starty, endx, starty, 1000);