Pages

Showing posts with label Tricky QTP Scripts. Show all posts
Showing posts with label Tricky QTP Scripts. Show all posts

Wednesday, November 6

Send Outlook Email (with text formatting) using QTP

Hello Friends!!

In this post we will quickly see how to send an outlook email.
I know, most of you all know how to send email using QTP, then why this post??

Well, here we will see how to use HTML code to format your email's body i.e. text style, font color, formatting etc. Here we go!!

Dim oOutlook, oEmail, vEmailTo, vEmailCC, vEmailBCC

vEmailTo = "catchall1@email.com"    'replace  this with your email id
vEmailCC = "catchall2@email.com"
vEmailBCC = "catchall3@email.com"
vEmailSubject = "Test Email from QTPschool.com"

Set oOutlook = CreateObject("Outlook.Application")
Set oEmail = oOutlook.CreateItem(0)

oEmail.To = vEmailTo
oEmail.CC = vEmailCC
oEmail.BCC = vEmailBCC
oEmail.Subject = vEmailSubject

oEmail.HTMLBody = "<HTML>"&_
"<Body>"&_
"<p Style=""background-color:red""><b>This text is bold and red background</b></p>"&_
"<p><strong>This text is strong</strong></p>"&_
"<p><em>This text is emphasized</em></p>"&_
"<p><Font color=""green""<i>This text is green and italic</Font></i></p>"&_
"<p><Font color=""red"" size = 16><small>This text is red and big!</small></Font></p>"&_
"<p>This is<sub> subscript</sub> and <sup>superscript</sup></p>"&_
"</Body>"&_
"</HTML>"

wait 2
oEmail.Send
wait 2

Set oEmail = Nothing
Set oOutlook = Nothing


'For more details on HTML code, please visit http://www.w3schools.com/html/html_formatting.asp

In case of any queries, please post your comments. Happy QTPing!!


Thursday, March 22

How to track execution time of the script in QTP

Hello Friends,

In this post, we'll see how to measure the total time taken by a test/script in execution.

It's easy to get execution time using Timer, but here we will measure the time and convert it to Hr-Min-Sec format. Let's see how-

Dim StartTime, EndTime
StartTime = Timer
'enter your script here
For I = 1 To 5
 wait 1
Next
EndTime = Timer
TimeTaken = EndTime - StartTime
msgbox TimeTaken

You have execution time stored in 'TimeTaken' variable but it is in milisecond format

Now, let's convert it to Hr-Min-Sec. It will clearly tell you how many seconds, minutes or hours (if any :) ) have been taken by the script. Following is the function to do the job for us. Just pass the 'TimeTaken' to it and chill :)


Function func_ExecutionTime(TimeTaken)
If TimeTaken>=3600 Then
 hr=int(TimeTaken/3600)
 rem1=int(TimeTaken mod 3600)
 str=hr&" hr "
 If rem1>=60 Then
  min=int(rem1/60)
  sec=int(rem1 mod 60)
  str=str&min&" min "&sec&" sec."
 else
  sec=rem1
  str=str&sec&" sec."
 End If
 Else If TimeTaken>=60 Then
 min=int(TimeTaken/60)
 sec=int(TimeTaken mod 60)
 str=str&min&" min "&sec&" sec."
else
 sec=TimeTaken
 str=str&sec&" sec."
End If
End If
func_ExecutionTime = str
End Function


How to call this function -

TimeTaken_HMS =  func_ExecutionTime(TimeTaken)
msgbox TimeTaken_HMS


If you have multiple actions in your test, you can measure the execution time for every individual action.


Post you comments for any queries/feedback.

Friday, January 27

Run application using QTP, if not running already!!

Hello Friends,

Sometimes we need to check whether any particular application is running or not, and if not, then run it.

In this post we are going to do that through QTP!!

Here we will check and run Internet Explorer, if not running already..


Dim flag, AllProcess, AppToRun
AppToRun = "iexplore.exe"
Flag = Flase
Set AllProcess = GetObject("winmgmts:")

For Each Process In AllProcess.InstancesOf("Win32_process")
    If (Instr ((Process.Name), AppToRun) = 1) Then
        Print "Internet Explorer is running.."
        Flag = Ture
        Exit For
    End If
Next


If Flag = Flase Then
    Print "Internet Explorer not is running.."
    SystemUtil.Run AppToRun
End If


You can do the same for any process/application. You just need to change the value of AppToRun variable. :)

Tuesday, June 21

Message box that will be closed automatically in QTP

Small code to display a message box that will close automatically in the given time without any click.

Dim msg
msg = "This message will automatically close in 10 second"
Set oShell = CreateObject("WScript.Shell")
oShell.Popup msg,10, "QTP School"

In above statement, there are three arguments - 

msg - the content/string of the message box
10 - the time in seconds
"QTP School" - the title of the message box

This is the output of the above code -


Tuesday, May 10

Database Connection using QTP

Hello Friends,

In this post, we'll see how to connect to database using QTP. We'll connect with database and retrieve values from the table/recordsets.


DataBase_Connection() creates a new connection to a database.

There are two arguments passed to this function -

1. sessionName - the name of the session (string)
2. connection_string - a connection string, for example the connection_string can be "DSN=SQLServer_Source;UID=SA;PWD=xyz123". Please note that the connection string will vary as per your database details.


Function DataBase_Connection(sessionName,connection_string)
    Dim oConnection
    on error Resume next
    ' Opening connection
    set oConnection = CreateObject("ADODB.Connection")
    If Err.Number <> 0 then
        DataBase_Connection= "Error :- " & CStr(Err.Number) & " " & Err.Description
        Err.clear
        Exit Function
    End If
 
    oConnection.Open connection_string
oConnection.CommandTimeout = 120  'modify this value if needed. 
    If Err.Number <> 0 then
        DataBase_Connection= "Error := " & CStr(Err.Number) & " " & Err.Description
        err.clear
        Exit Function
    End If
    set sessionName = oConnection
    DataBase_Connection = 0
End Function


We need another function to retrieve data from record set.

Function db_get_field_value( myrs , rowNum, colNum )
    dim curRow

    myrs.MoveFirst
    count_fields = myrs.fields.count-1
    If ( TypeName(colNum)<> "String" ) and ( count_fields < colNum ) then
        db_get_field_value = -1 'requested field index more than exists in recordset
    Else
        myrs.Move rowNum
        db_get_field_value = myrs.fields(colNum).Value
    End If
End Function

Now, let's do the actual thing :)

Con = <name of the session>
SQL="SELECT * FROM Your_Table"
con_string="DSN=SQLServer_Source;UID=SA;PWD=xyz123"

isConnected = DataBase_Connection (Con , con_string)

'Now check if connection is successful. Function will return zero if connection is successful.
If isConnected = 0 then
    'Execute your SQL statement
    set myrs = Con.Execute(SQL)


    'Retrieve values from the recordset
    print "val - row 0 col 0: " & db_get_field_value( myrs , 0 , 0 )
    print "val - row 0 col 1: " & db_get_field_value( myrs , 0 , 1 )
End If

Con.close
Set Con = Nothing 'Disconnect database

'Below is the example connection string for Oracle database
' strDBDesc ="(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=dev.uat.application.opp.devenv.domain.net)(PORT=1521)))(CONNECT_DATA=(SID=DBS)))"

 'strUserID = "user11"
 'strPassword = "pass11"
 'Conn_String="Provider=OraOLEDB.Oracle;Data Source=" & strDBDesc & ";User ID=" & strUserID & ";Password=" & strPassword & ";"
 
In case of any querirs, please leave your comments. Happy Automation :)

Tuesday, April 19

Running vbscript code without QTP

Hello friends!

Here we will see how to execute vbscipt code without having QTP on your machine!!

Really?? How??

Okey..

1. Just copy n paste below code to new notepad...


'To extract a number from alphanumeric text string
Dim mystring, myLength
mystring = "qtpschools567test12398ing"
myLength = Len(mystring)

For i = 1 To myLength
    If Asc(Mid(mystring, i, 1)) <> 32 Then
        If Asc(Mid(mystring, i, 1)) >= 48 And Asc(Mid(mystring, i, 1)) <= 57 Then
            myNumber = myNumber & Mid(mystring, i, 1)
        End If
    Else
        msgbox("no numeric")
    End If
Next

msgbox(myNumber)


2. Save file as "test.vbs" (with double quotes)
3. It'll display like this on your hard drive..
4. Now close the file and double click on the file icon.
and it's done!! :)

Please note that it'll work only if you don't have any object in your script.
In case of any queries, plz post your comments.

Saturday, April 9

How to right-click on any object using QTP

Hello Friends!
Following code demonstrate how to right click on a particular object using QTP.
We'll use DeviceRepaly object to do that..


Dim oDR
Set oDR=CreateObject("Mercury.DeviceReplay")
Set obj=Browser("name:=Yahoo.*").Page("title:=Yahoo.*").Webedit("name:=p")
obj.click
wait 3
x1=obj.GetroProperty("x")
y1=obj.GetroProperty("y")
oDR.MouseClick x1,y1,2


Please note that 2 in above line is for Right click. [0=left; 1=middle; 2=right]

Friday, March 4

Count number of files in a folder

Dim iFileCount, FolderName, vFiles, objFSO
iFileCount = 0
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set FolderName = objFSO.GetFolder("C:\Desktop") ' Folder Path
Set vFiles =FolderName.Files

For each vFile in vFiles
    Print vFile
    iFileCount = iFileCount + 1
Next
msgbox iFileCount






Above code will print names of all the file in given folder and display the total count of files.

Wednesday, March 2

Find the highest number in the array

'This code demonstrate how to find the highest number in a numaric array.
 
Dim num, i, Length1

num=array(34,12,98,43,89,49,56)
Length1 = UBound(num)    'Find the length of array

For i= 1 to Length1
 If (num(i) < num(0)) Then  'to find lowest number, just change it to >
    num(0)=num(i)
 End If
Next

MsgBox num(0) 'Highest Number

Tuesday, March 1

How to extract a number from alphanumeric text string?

Dim mystring, myLength
mystring = "abhikansh567st1239test"
myLength = Len(mystring)

For i = 1 To myLength
    If Asc(Mid(mystring, i, 1)) <> 32 Then
        If Asc(Mid(mystring, i, 1)) >= 48 And Asc(Mid(mystring, i, 1)) <= 57 Then
            myNumber = myNumber & Mid(mystring, i, 1)
        End If
    Else
        msgbox("no numeric")
    End If
Next
msgbox(myNumber)

Launch QTP with QC Connection and Add-ins using vbscript

Suppose you are working on an Java application and you are using Java add-in and say Oracle add-in. Also, you are running your test from QC. One way to do this is simply open QTP, select required add-ins, connect with QTP manually and then open your test by browsing to its location. This'll take about 10 mins, i beleive.
Yeah...!!! But what can I do?

Well, you can do a lot! In this post we'll see how to launch qtp with all required settings, add-ins, and connection with QC, and even open a particular test by default.

Everything is done in just one click... Sounds great??  Okie... here we go...!

Set App = CreateObject("QuickTest.Application") ' Create the Application object
App.SetActiveAddins Array("Web", "Java", "Oracle") 'Set the required Add-Ins
App.Launch ' Start QuickTest
App.Visible = True ' Make the QuickTest application visible
App.New ' Open a new test
'App.Open "D:\John\" '-  use this if you want to open existing test
If Not App.TDConnection.IsConnected Then
    App.TDConnection.Connect "http://<server url>","<domain name>","<project name>","<user name>","<password>",False ' remove <> brackets
End If
App.Options.Run.ViewResults = False
App.Test.Actions("Action1").ObjectRepositories.Add "[QualityCenter] Subject\john\Repository\Rep.tsr"
App.Test.Settings.Resources.Libraries.Add "[QualityCenter] Subject\john\Repository\Lib.vbs"
'App.Test.Actions("Action1").SetScript "'TestCaseId:  "&vbCrlf&"'TestCaseName:  "&vbCrlf&"'Description:  "&vbCrlf&"'Created By:  John"&vbCrlf&vbCrlf&vbCrlf&"'*******************************Prerequisites********************************"&vbCrlf &"'Application should be open and login"&vbCrlf &"'*******************************************************************************"

Set App = Nothing ' Release the Application object

In case of any queries, please leave your comments.