Friday, December 19, 2014

What is the difference between $_ and @_ variables in Perl?

Both $_ and @_ are global variables.

In a subroutine, the array @_ pass the arguments to the given subroutine
Consider the example below,

sub print
{
foreach my $arg(@_) // @_ contains, abc, xyz, lmn, It collects from call and keeps them during execution
{
print "To Print =>$arg\n";
}
}

print('abc','xyz','lmn');

Output :
To Print =>abc
To Print =>xyz
To Print =>lmn

$_ is used as a variable for the loop

foreach(1..5)
{
  print "$_\n";
}

Output
1
2
3
4
5

Combining both the features

sub print
{
  foreach(@_)
  {
    print "You passed in $_ \n";
  }
}

print('abc','xyz','1','2','true');

Monday, December 15, 2014

Perl - How to Connect to DB and Perform Insert, Update, Delete, Commit, Rollback and other some other DBI functions



DBI stands for Database Independent Interface for Perl which means DBI provides an abstraction layer between the Perl code and the underlying database, allowing you to switch database implementations really easily.

The DBI is a database access module for the Perl programming language. It provides a set of methods, variables, and conventions that provide a consistent database interface, independent of the actual database being used.

How to Conect to DB with Perl
------------------------------

#!/usr/bin/perl

use DBI
use strict;

my $driver = "mysql";
my $database = "TestDataBase";
my $dsn = "DBI:$driver:database=$database";
my $userid = "scott";
my $password = "tiger";

my $dbh = DBI->connect($dsn, $userid, $password ) or die $DBI::errstr;

If the Database connection is successful then connect will return DBI handler for futher use.
Else returns the error errstr

How to insert record in to DB with Perl
------------------------------------------

my $sth = $dbh->prepare("INSERT INTO emp
                       (FIRST_NAME, LAST_NAME, SAL )
                        values
                       ('scott', 'james', 100)"); //Prepare the sql statement
$sth->execute() or die $DBI::errstr; //Execute the statement if successful continue else return errstr
$sth->finish(); //Release the connection
$dbh->commit or die $DBI::errstr; //Commit the changes done

or

$sth = $dbh->prepare(qq{
       INSERT INTO TEST_TABLE (FIRST_NAME, AGE) VALUES (?, ?)
       });
 $sth->execute("Joe", undef);

How to insert record and pass values during runtime
----------------------------------------------------

my $first_name = "john";
my $last_name = "poul";
my $SAL = 200
my $sth = $dbh->prepare("INSERT INTO TEST_TABLE
                       (FIRST_NAME, LAST_NAME, SAL )
                        values
                       (?,?,?)");
$sth->execute($first_name,$last_name,$sal)
          or die $DBI::errstr;
$sth->finish();
$dbh->commit or die $DBI::errstr;

How to select rows from DB using Perl
---------------------------------------

my $sth = $dbh->prepare("SELECT FIRST_NAME, LAST_NAME
                        FROM emp
                        WHERE AGE > 30");
$sth->execute() or die $DBI::errstr;

print "Number of rows found :" + $sth->rows;
while (my @row = $sth->fetchrow_array()) {
   my ($first_name, $last_name ) = @row;
   print "First Name = $first_name, Last Name = $last_name\n";
}
$sth->finish();

How to update DB records using Perl
------------------------------------

my $sth = $dbh->prepare("UPDATE TEST_TABLE
                        SET   AGE = AGE + 1
                        WHERE SAL > 200");
$sth->execute() or die $DBI::errstr;

print "Number of rows updated :" + $sth->rows;
$sth->finish();
$dbh->commit or die $DBI::errstr

How to delete DB records using Perl
-------------------------------------

$age = 30;
my $sth = $dbh->prepare("DELETE FROM TEST_TABLE
                        WHERE AGE = ?");
$sth->execute( $age ) or die $DBI::errstr;

print "Number of rows deleted :" + $sth->rows;
$sth->finish();
$dbh->commit or die $DBI::errstr

Get metadata from DB using Perl
--------------------------------
This will fetch available drivers

@ary = DBI->available_drivers;
@ary = DBI->available_drivers($quiet);

get all data sources
@ary = DBI->data_sources($driver);



Sunday, December 14, 2014

How to get coordinates or dimensions of web element with Python using Selenium Webdriver

driver = webdriver.Firefox()
e = driver.find_element_by_xpath("//someXpath")
location = e.location
size = e.size
print(location)
print(size)

{'y': 202, 'x': 165}
{'width': 77, 'height': 22}

Sunday, December 7, 2014

How to download files in Mozilla using Selenium Webdriver

FirefoxProfile firefoxProfile = new FirefoxProfile();

firefoxProfile.setPreference("browser.download.folderList",2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
firefoxProfile.setPreference("browser.download.dir","c:\\downloads");
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");

Here text/csv is a mime type, change this mime type depending on the file type you want to download

Popular mine types

PDF => application/pdf
Text file => text/plain
.exe => application/octet-stream
MS Doc => application/msword
xls => application/excel
.zip => application/x-compressed
.tgz => application/gnutar

How to download files in IE using Selenium Webdriver

public void clickAndSaveFileIE(WebElement element) throws AWTException, InterruptedException {

    Robot robot = new Robot();

    // Get the focus on the element..don't use click since it stalls the driver        
    element.sendKeys("");

    //simulate pressing enter          
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);

    // Wait for the download manager to open          
    Thread.sleep(2000);

    // Switch to download manager tray via Alt+N
    robot.keyPress(KeyEvent.VK_ALT);
    robot.keyPress(KeyEvent.VK_N);
    robot.keyRelease(KeyEvent.VK_N);
    robot.keyRelease(KeyEvent.VK_ALT);

    // Press S key to save          
    robot.keyPress(KeyEvent.VK_S);
    robot.keyRelease(KeyEvent.VK_S);
    Thread.sleep(2000);

    // Switch back to download manager tray via Alt+N
    robot.keyPress(KeyEvent.VK_ALT);
    robot.keyPress(KeyEvent.VK_N);
    robot.keyRelease(KeyEvent.VK_N);
    robot.keyRelease(KeyEvent.VK_ALT);

    // Tab to X exit key
    robot.keyPress(KeyEvent.VK_TAB);
    robot.keyRelease(KeyEvent.VK_TAB);

    robot.keyPress(KeyEvent.VK_TAB);
    robot.keyRelease(KeyEvent.VK_TAB);

    robot.keyPress(KeyEvent.VK_TAB);
    robot.keyRelease(KeyEvent.VK_TAB);

    // Press Enter to close the Download Manager
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);

}

How to download files in Chrome using Selenium Webdriver

//Get Chrome Driver
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
String downloadFilepath = "/path/to/download";

//Save Chrome Preferences in Hash Map
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);

//Save Chrome Opions
ChromeOptions options = new ChromeOptions();
HashMap<String, Object> chromeOptionsMap = new HashMap<String, Object>();
options.setExperimentalOptions("prefs", chromePrefs);
options.addArguments("--test-type");

//Set desired capability
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability(ChromeOptions.CAPABILITY, chromeOptionsMap);
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(ChromeOptions.CAPABILITY, options);

//Start Chrome Driver
WebDriver driver = new ChromeDriver(cap);