Taking screenshot of a specific web element in Selenium

6 Sep


While progressing with the automation testing I had a problem to take screenshots of a particular element in the web page. Selenium only allows you to take the screenshot of entire web page. But using some tweaks and c# techniques I made to take screen shot of a particular web element.


This is (mostly) for those who are doing their automation testing parts using c# and selenium.

Using the code

First we need to take the screen shot of entire web page using the GetScreenShot method of selenium web driver as below.

Screenshot screenshot = ((ITakesScreenshot)this.driver).GetScreenshot();
screenshot.SaveAsFile(filename, System.Drawing.Imaging.ImageFormat.Jpeg);

Then create a rectangle from the location , height and width of the specified html element. (This has to be obtained using FindElement() method of selenium by providing id or class name).

Image img = Bitmap.FromFile(uniqueName);
Rectangle rect = new Rectangle();

if (element != null)
    // Get the Width and Height of the WebElement using
    int width = element.Size.Width;
    int height = element.Size.Height;

    // Get the Location of WebElement in a Point.
    // This will provide X & Y co-ordinates of the WebElement
    Point p = element.Location;

    // Create a rectangle using Width, Height and element location
    rect = new Rectangle(p.X, p.Y, width, height);

Using this we are going to crop the screenshot as below and the result will be the screenshot specific web element.

Bitmap bmpImage = new Bitmap(img);
var cropedImag = bmpImage.Clone(rect, bmpImage.PixelFormat);

Full code as a method below:

/// <summary>
/// Captures the element screen shot.
/// </summary>
/// <param name="element">The element.</param>
/// <param name="uniqueName">Name of the unique.</param>
/// <returns>returns the screenshot  image </returns>
public Image CaptureElementScreenShot(HTMLElement element, string uniqueName)
    Screenshot screenshot = ((ITakesScreenshot)this.driver).GetScreenshot();
    screenshot.SaveAsFile(filename, System.Drawing.Imaging.ImageFormat.Jpeg);

    Image img = Bitmap.FromFile(uniqueName);
    Rectangle rect = new Rectangle();

    if (element != null)
        // Get the Width and Height of the WebElement using
        int width = element.Size.Width;
        int height = element.Size.Height;

        // Get the Location of WebElement in a Point.
        // This will provide X & Y co-ordinates of the WebElement
        Point p = element.Location;

        // Create a rectangle using Width, Height and element location
        rect = new Rectangle(p.X, p.Y, width, height);

    // croping the image based on rect.
    Bitmap bmpImage = new Bitmap(img);
    var cropedImag = bmpImage.Clone(rect, bmpImage.PixelFormat);

    return cropedImag;


Remember to set the Language of your code snippet using the Language drop down.

Use the “var” button to wrap Variable or class names in <code> tags like this.

Points of Interest

Based on your requirement you can extend the Image class and write Rotate (if you have a ny requirement to compare the images after rotation) and compare (if you want to compare two images) and use them on your automation scripts.

Introduction to ECMASCRIPT 2015 – ES6

2 Nov


ECMASCRIPT 2015 aka ES 6 is the new ECMA standard standardized by Ecma International in ECMA-262 and ISO/IEC 16262. It makes java script lovers happyūüôā . It adds lot of goodies to java script like classes, arrow functions,block scopes , const etc.

ECMASCRIPT is nothing but the standard. Almost all scripting languages including java script are created using ES (ES is using across this article for ECMASCRIPT) as core.

wiki link for history .

Browser Support

None of the browsers fully support ES 6. EDGE 13 supports 80% of ES 6 features and FF43 supports 72 %. You can check the complete list of browsers which support ES 6 here.

To overcome the browser support issue (only for time being) we can use transpilers to convert the ES6 code to ES5 and use them in your page. I am using babel transpiler in my examples to convert my ES6 code to ES5. There are many transpilers available. Have a look here .
What is new in ES6?

I would like to introduce some new goodies in ES 6 with examples in javascript.

1. Arrow functions

ES6 has arrow functions which has shorter syntax compared to normal function using the => syntax and are anonymous. They are syntactically similar to the related feature in C#, Java 8 and CoffeeScript.The synatx is:

// Basic syntax:
(parameters) => { statements }
(parameters) => expression
// equivalent to: => { return expression; }

In the example:


Thi will return squares of the given list of integer array. And the result is same as that of

[1, 2, 3, 4].map(function (x) {
return console.log(x * x);

The transpiled coud should be looks like this.

2. Constants

we can declare constants using the keyword const .

Eg: const pi=3.14;

3. Template Strings

The beauty of string templates like String.Format() in C# is available in ES6. A tag can be added to create customized strings. Also it is possible to create multi line string without using ‘\n’.

Use back ticks (`) defining template strings. The sample code contains different ways of implementation

// Multi line strings
var multilineString =`In JavaScript this is
not legal.`

// String interpolation
var name = “Bob”, time = “today”;
console.log(`Hello ${name}, how are you ${time}?`);

//Embeding calculations in string.
var taxPercentage = 10;
var price = 120;
console.log(`The tax is ${price*(taxPercentage/100)}`);

This will repalce the calculated value of price*(taxPercentage/100) in the string and return :

The tax is 12

function calculateTotal(str,amt){
var taxPercentage = 10;
return str+(amt+(amt*(taxPercentage/100)));
var amt=120;
var msgWithTax= calculateTotal `The total amount is ${amt}`

This will create a string by calling the calculateTotal function and replaces the tag with calcualted value and the result should be lik :

The total amount is ,132

4. Class

Yes, we can create class using the keyword class in java script. All java script lovers are happy to know js is now object oriented.ūüôā

In the example below. I am creating a class with name Bake which has a constructor which accepts a cake type. The class has a member function named getTheCake which gives you the cake you wants.

class Bake {
constructor(cake) {
this.cake = cake;
getTheCake() {
//Declaring objects of bake class
var a = new Bake(‘Plum cake’);
//Assigining the variable.
a.cake=’Choclate cake’;

Here the first function call gives you a plum cake and the second gives you a Choclate cake. Enjoy the cake or create you own flavor.

5. inheritance

Since we already got classes there should be inheritanceūüôā , yes inheritance also there in ES6 using the keyword extends

class BakeWithFlavour extends Bake{
console.log(`${this.cake} with ${this.flavour} flavour` );

Her BakewithFlavour class inherit from the Bake class . And its constructor calling the base constructor using super(cake).

var a = new BakeWithFlavour(‘Plum cake’,’choclate’);

Here the function call getFlavouredCake() will give you a Plum cake flavored with chocolate. Enjoy your pieceūüôā.

6. Static methods

Like c# or java we can create static methods in ES6 using the keyword static. And this methods can be called using the class name itself.

class Bake {
static getPlumCake(){
return ‘Plum cake’;



ES 6 supports modules for component definition which is to support the standards of both common js modules and AMD (Asynchronous Module Definition – The most popular implementation of this standard is RequireJS ) . The synatx includes the key words export and import :

// module.js
export function square(list[]) {

//—— main.js ——
import {square} from ‘Module’;
// or you can use import * from ‘module’ to import all the members in module
var list=[1,2,3,4,5];

If we traspile this code using babel we need common.js implementation. Because bable is using the common.js module model to transpile the code.

In examples it contain both ES6 file as well as the transpiled file .I have used the transpiled js files in all. Try to use the actual ES 6 js files depends on your browser and enjoy the brand new java script with ES6 standards.

Reference 1

Reference 2

Please find the examples in GitHub here

Automaticaly Printing RDLC in Asp.Net MVC 3

29 Mar

Download (Code Project)

Here i am explaining a small method which i am adopted for automatically printing an rdlc file in my Asp.Net MVC3 application.

In my Asp.Net MVC 3 application I had suffered with the report section. We are using the client definition (rdlc) of Reporting Service for report creation. But the things were stuck on one scenario where our client needs to automatically print the reports by specifying a particular printer name which is presented.

After a lot of googling I realized that it is a hard scenario. Finally we decided to achieve it with acrobat reader and java script to pdf. Requirement is that you must install the acrobat reader plugin in your browser.
The requirement is that there is a printer setting where we are setting a particular printer for a particular report by providing the IP address of the system. According to these settings a particular report must print through a printer which is provided in the settings table.

Using the code
First we designed the report using rdlc. The next step is converting the rdlc to pdf from the action method in the controller. Also we need to inject the javscript for automatically printing the report in acrobat viewer. For that with the help of  iTextSharp dll we converted the rdlc file into pdf at the same time we injected some javscript for automatic printing to the pdf.
You need to include the following namespaces which is in iTextSharp DLL
using iTextSharp.text.pdf;

using iTextSharp.text;

The action method is as follows

public void RecieptPrint(long inv_ReceiptID)


           LocalReport localReport = new LocalReport();

¬†¬†¬†¬†¬†¬†¬†¬† ¬† localReport.ReportPath = @”Reprt1.rdlc”;

          DataTable dt = DataSelect();

            The following code is for dynamically setting the data source to rdlc. I already wrote about this here

ReportDataSource reportDataSource = new ReportDataSource();

reportDataSource.Value = dt;

reportDataSource.Name = “DataSet1”;



string reportType = “PDF”;

string mimeType;                  string encoding;

string fileNameExtension = “pdf”;

//The DeviceInfo settings should be changed based on the reportType

string deviceInfo =@”<DeviceInfo>








¬†¬†¬†¬†¬† </DeviceInfo>”;
Warning[] warnings;
string[] streams;
byte[] renderedBytes;

Now we are going to converting the rdlc to byte array using the above device info for pdf . To know more about it click here

           renderedBytes= localReport.Render(
deviceInfo,out mimeType, out   encoding,               out   fileNameExtension,out streams,out warnings);

Next comes the important section. We are adding this byte array to our pdf file. Also we are injecting the javascript which did the automatic printing into the pdf.

var doc = new Document();

var reader = new PdfReader(renderedBytes);

using (FileStream fs = new FileStream(Server.MapPath(“~/Summary”+ Convert.ToString(Session[“CurrentUserName“]) + “.pdf“),¬†¬† FileMode.Create))


      PdfStamper stamper = new PdfStamper(reader, fs);

¬†¬†¬†¬†¬† string Printer =¬†¬†¬†¬† PrinterName(Convert.ToInt32(Session[“localOutletID“]));

// This is the script for automatically printing the pdf in acrobat viewer

stamper.JavaScript= “var pp = getPrintParams();pp.interactive =¬† pp.constants.interactionLevel.automatic;pp.printerName = ” + Printer + “;print(pp);\r”;






          In view using an iframe we can render this pdf and it will be printed automatically. Requirement is that you must install the acrobat reader plugin in your browser.

Points of Interest

If we saved that pdf instead of printing while opening it will be printed automaticlay.

SQL Query for geting all Stored Procedure under a schema

10 Dec

FROM DB_Name.information_schema.routines
WHERE routine_type = ‘PROCEDURE

Using this query we can get all the stored procedure under  SchemaName in DB_Name

Adding Report Datasource On Runtime to a rdlc file on ReportViewer

27 Jul

While using client report definition (rdlc) for reporting in a .net application we need to create a dataset for its datatsource. It may cause a problem of diiferent connections for each report are there in a single application . For avoiding  this we can dynamically set datasource for report during run time.

1.      For this first we need to add the rdlc File

2.Add a Dataset for designing the report

3.Add a table adapte r with corresponding stored procedure or query.

4. After creating the data adapter we can access this in our report definition(rdlc)

5. Design the rdlc file using this dataset. After designing remove tha dataset from the project.

We can dynamicaaly assign the datasource from our bussiness logic at runtime to the rdlc file. For this e need to add  MicrosoftReportViwer into our form.


Here we can  set the datasource to the rdlc file using the following code.

 BLL.Class obj= new BLL.Class();

 DataTable dtTest = obj.SelectData();


 reportViewer1.Visible = true;

 ReportDataSource rds = new ReportDataSource();


 reportViewer1.ProcessingMode = ProcessingMode.Local;

 LocalReport rep = reportViewer1.LocalReport;


¬†rep.ReportEmbeddedResource =“Report1.rdlc”;

¬†rds.Name = “DataSet1_Data”


reportViewer1 : Name of the MicrosoftReportViwer control

We can also pass report parameters to rdlc as follows

//Report parameter,

ReportParameter rp = new ReportParameter(“content”,”HELLO”);//(Param name,value)

this.reportViewer1.LocalReport.SetParameters(new ReportParameter[] { rp });


20 Jan

For getting month names between two dates we may use the following Query


SET @date1 = ‘2010-12-20’

SET @date2 = GETDATE();

WITH cte

AS (

SELECTdatename(month, @date1) AS [Month_Name], @date1 AS dat


SELECTdatename(month, DateAdd(Month, 1, dat)), DateAdd(Month, 1, dat) FROM cte

WHEREDateAdd(Month, 1, dat) < @date2


SELECT [Month_Name]




Query for Geting dependent tables of a stored procedure

17 Dec

In MS SQL Server 2008, you may get the table names dependents by a stored procedure using the following query


,(SELECT name FROM sys.schemas WHERE schema_id=t.schema_id) AS schemaName

FROM  sys.tables t

WHERE  t.object_id in (SELECT depid

FROM sys.sysdepends

WHERE id In (SELECT s.object_id FROM sys.procedures s WHERE name=’SPName‘))

SPName  is the name of  stored procedure.

Th output will be the table name and its schema. Happy querying ..ūüôā