Thursday, April 10, 2014

Talking screenshot with selenium webdriver using c# with app configuration


Sample code for talking screenshot with selenium webdriver using c# with app configuration

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Support.UI;
using System;
using System.IO;

namespace ConsoleApplication5
{
    class Program
    {
        public static void Main(string[] args)
        {
            string website =                                                                     System.Configuration.ConfigurationSettings.AppSettings["url"];

            string pages =                                                                    System.Configuration.ConfigurationSettings.AppSettings["page_name"];

              string[] saparated_pages = pages.Split(',');

            //Specify browser driver path
            IWebDriver driver = new ChromeDriver(@"D:\");

            //Site Launch
            driver.Navigate().GoToUrl(website);

            //Getting screenshot
            Screenshot ss1=((ITakesScreenshot)driver).GetScreenshot();

            //Specify variable value as current time to set for filename
            var filename=DateTime.Now.ToString("MM-dd-yyyy,h-s-m tt");

            //Save the screenshot with specified location&image format
            ss1.SaveAsFile(@"D:\selenium_images\" filename+".png",
            System.Drawing.Imaging.ImageFormat.Png);

            for (int j = 0; j < 3; j++)
            {
                 driver.Navigate().GoToUrl(website+"/"+ saparated_pages[j]);
              Screenshot ss=((ITakesScreenshot)driver).GetScreenshot();
              var file_name=DateTime.Now.ToString("MM-dd-yyyy,h-s-m tt");
              ss.SaveAsFile(@"D:\selenium_images\" + file_name + ".png",                       System.Drawing.Imaging.ImageFormat.Png);
            }

            //close the browser
            driver.Close();
           
        }      
    }
}
  

//app config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="domain_name" value="http://www.google.com"/>
    <add key="page_name" value="imghp,photos,document"/>
    <add key="url" value="http://www.google.com"/>
  </appSettings>
</configuration>

To create the App Config as,

Step 1:Right the project name in solution explorer
Step 2:Add->New item
Step 3:choose Application configuration file in visual studio installed templates
Step 4:name the templates
Step 5:its open with

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>

Step 6:include the app settings where its keys and value as above program
Step 7:to call the app config as with "System.Configuration.ConfigurationSettings.AppSettings["url"]; "
where URL is the key.which retrieve the values from the particular key


No comments: