Sunday, November 28, 2010

Unknown QTP Webtable Methods

The below listed unknown QTP webtable methods were present in Astra LoadTest. But we are still able to use these methods in QTP. I would like to share this to you.

#1 CellText
This method works as same as GetCellData method.
Eg.: Msgbox Browser("name:=qtp").WebTable("index:=0").CellText(1,1)

#2 CellTextByContext
This method returns the text within a cell delimited by a character. We can retrieve the text before (or) after the delimiter using this method.
Eg.: Consider a cell having the text “Asiq;Ahamed”. Here “;’ is the delimiter

Code to retrieve the text before the delimiter
Msgbox Browser("name:=qtp").WebTable("index:=0").CellTextByContext(1,1,"",";")

Code to retrieve the text after the delimiter
Msgbox Browser("name:=qtp").WebTable("index:=0").CellTextByContext(1,1,";")

#3 TextCellExist

This method checks whether a text exists in a cell or not. It returns true, if the input text exists in the cell, else it returns false. Rather than using GetCellData method and then comparing the result with the input text, we can achieve it using this simple method.
Msgbox Browser("name:=qtp").WebTable("index:=0").TextCellExist(1,1,"asiq")
I hope this is useful to all.

Sunday, November 21, 2010

Beware of setting value in webedit using DOM

If you set value in a disabled webedit, QTP will throw the below error.


But do not enter value in webedit using DOM. The problem is: You can set value in web text box even it is disabled.
We have a work around for this.

Set obj=Browser("name:=Google").Page("title:=Google").WebEdit("index:=1").Object
If Not obj.disabled Then
obj.Value ="qtp"
End If
I always use DOM to retrieve text or count no. of objects. I hope this is helpful.

Friday, August 6, 2010

Adding Hyperlink In An Excel Sheet

Method #1

Set obj=CreateObject("Excel.Application")
obj.Visible=True

Set oWorkBooks=obj.WorkBooks.Open("C:\Desktop\Book1.xls")
Set oWorksheet=oWorkBooks.Worksheets(1)

With oWorksheet
.Hyperlinks.Add .Range("A1"),"http://qtpcodes.blogspot.com"
End With
Method #2

Set obj=CreateObject("Excel.Application")
obj.Visible=True

Set oWorkBooks=obj.WorkBooks.Open("C:\Desktop\Book1.xls")
Set oWorksheet=oWorkBooks.Worksheets(1)
sLink="http://www.qtpcodes.blogspot.com"

oWorksheet.Cells(1, 1).Value= "=HYPERLINK("&Chr(34)&sLink&Chr(34)&",""CLICK HERE"")"

Saturday, June 26, 2010

Resizing Bitmap using Dotnet Factory


Set oImage=DotNetFactory.CreateInstance("System.Drawing.Image","System.Drawing")
vstPath="C:\Sample Pictures\Water lilies.jpg" 'path of the bitmap to be resized.
Set oBitmap=DotNetFactory.CreateInstance("System.Drawing.Bitmap","System.Drawing",oImage.FromFile(vstPath),30,40)
vStResizedPath="C:\Sample Pictures\Water lilies1.jpg"
oBitmap.Save(vStResizedPath)'Save the resized bitmap.
Set oBitmap=Nothing
Set oImage=Nothing

Thursday, June 3, 2010

Reuse Your QTP Code

In this article, I am going to explain you how can we reuse the code which is written for web application.
In the below class, I have written function fnc_set to set value in a WebEdit.

Class FirstClass
Private VarBrowserObj
Private VarWebEditObj
Private VarSetValue
'**********Let Property*****************************************
Public Property Let fnc_VarSetValue(val)
VarSetValue=val
End Property
'**********Set Property****************************************
Public Property Set fnc_VarBrowserObj(val)
Set VarBrowserObj=val
End Property

Public Property Set fnc_VarWebEditObj(val)
Set VarWebEditObj=val
End Property
'**************Funtions and Procedures**********************
Public Function fnc_set
Browser(VarBrowserObj).WebEdit(VarWebEditObj).Set VarSetValue
End Function
End Class

Here, I am creating an object for the above class and setting up values and objects for class properties.

Public objClass
'Creating object for class
Set objClass=new FirstClass

'Calling Let to assign value for VarSetValue property
objClass.fnc_VarSetValue="QTP"


'Calling Set property method for Browser object
Dim objBrowser:Set objBrowser=Description.Create()
objBrowser("name").Value="Google"
Set objClass.fnc_VarBrowserObj=objBrowser


'Calling Set property method for WebEdit object
Dim objWebEdit:Set objWebEdit=Description.Create()
objWebEdit("name").Value="q"
Set objClass.fnc_VarWebEditObj=objWebEdit

'Calling fnc_set function for Web operation
objClass.fnc_set

You may think that the above class can be used only for web application. But we are able to use for other application also.

'Calling Let to assign value for VarSetValue property
objClass.fnc_VarSetValue="mercury"

'Calling Set property method for Dialog object
Dim objDialog:Set objDialog=Description.Create()
objDialog("text").Value="Login"
objDialog("micclass").Value="Dialog"'Here is the trick, you need to inlcude micclass property along with main property.
Set objClass.fnc_VarBrowserObj=objDialog

'Calling Set property method for WinEdit object
Dim objWinEdit:Set objWinEdit=Description.Create()
objWinEdit("attached text").Value="Agent Name:"
objWinEdit("micclass").Value="WinEdit"
Set objClass.fnc_VarWebEditObj=objWinEdit

objClass.fnc_set 'Setting value in winedit with same function.

Monday, May 31, 2010

Overriding GetRowWithCellText Method

GetRowWithCellText method finds the specified text in a webtable and returns the number of the first row found.
If you want to find all matches in a webtable, then we have to override the GetRowWithCellText method using RegisterUserFunc as below,
RegisterUserFunc "WebTable","GetRowWithCellText","NewGetRowWithCellText"

Function NewGetRowWithCellText(obj,val1,val2,val3)
Dim v_st_returnText
Set objRow=obj.Object.getElementsByTagName("TR")
If val2<>0 Then val2=val2-1
If val3<>0 Then val3=val3-1
For i=val3 to objRow.Length-1
If val1=Trim(objRow(i).getElementsByTagName("TD")(val2).InnerText) Then
If v_st_returnText="" Then
v_st_returnText=Cstr( i+1)
Else
v_st_returnText=Cstr( i+1)+","+v_st_returnText
End If
End If
Next
NewGetRowWithCellText=v_st_returnText
End Function

Msgbox Browser("name:=QTP Codes").Page("title:=QTP Codes").WebTable("index:=0").GetRowWithCellText("Cell3",1,1)

Saturday, May 15, 2010

Quitting Excel Workbooks Using Getobject

Let’s consider that we have opened two excel workbooks using CreateObject. If you want to quit those two workbooks, try the below snippet.
Function fnc_CreateExcel
Set objNewExcel=CreateObject("Excel.Application")
objNewExcel.Visible=True
objNewExcel.Workbooks.Add
Set objNewExcel=Nothing
End Function

Call fnc_CreateExcel'Creating Book1
Call fnc_CreateExcel'Creating Book2

Call fnc_Quit_Excel("Book1")'Quitting Book 1
Call fnc_Quit_Excel("Book2")'Quitting Book 2

Function fnc_Quit_Excel(v_St_ExcelName)
Set objExcel=GetObject(v_St_ExcelName).Application'Getting Excel Object using Book name
objExcel.Quit
Set objExcel=Nothing
End Function

Friday, April 30, 2010

Capturing Bitmap When Text Is Mismatched

Whenever a text in a webpage is mismatched, you may use QTP report event to report the failure.
You can try the below snippet along with report event, the code captures and highlights the mismatched text in the webpage.
Set obj=Browser("name:=Google").Page("title:=Google").Object.getElementsByTagName("LABEL")(0)
vStrActualText= obj.innerText
vStrExpectedText="The Web"
If vStrActualText<>vStrExpectedText Then
obj.innerHTML=""&vStrActualText&""
Browser("name:=Google").Page("title:=Google").highlight
Browser("name:=Google").Page("title:=Google").CaptureBitmap "C:\TEST.PNG",True
obj.innerHTML=vStrActualText
End If
If your text is mismatched in the webpage, the script captures bitmap of the page.

Saturday, April 17, 2010

Finding Disabled Radio Buttons

The below snippet finds disabled radio button from a webradiogroup using DOM.
Set obj= Browser("name:=Google").Page("title:=Google").Object.getElementsByName("meta")
For i=0 to obj.Length-1
If obj(i).Type="radio" and obj(i).Disabled="True" Then
Msgbox "Radio " &i+1& " is disabled" 'This msgbox indicates the disabled radio button.
End if
Next

Changing Screen Resolution at Runtime

So far I have not found a code for changing screen resolution at runtime using vb script. If anyone finds that, please post it.

An alternative solution, we can go for third party tool like Qres and MultiRes. These tools can be operated using QTP at runtime.

Download Links:
Qres:
http://home.no/aksoftware/
MultiRes: http://www.entechtaiwan.com/util/multires.shtm

If you know any other tool(s), please don’t hesitate to include in the comment section.

Tuesday, March 30, 2010

Do You Want To View Your Web Table's Structure?

Do you want to view your web table's structure? If the answer is Yes, then try the below snippet.
Set objTable=Browser("name:=Google").Page("title:=Google").WebTable("name:=q").Object
strTRCount=objTable.getElementsByTagName("TD").Length-1
For i=0 to strTRCount
objTable.getElementsByTagName("TD")(i).style.borderstyle="solid"
objTable.getElementsByTagName("TD")(i).style.borderwidth="2px"
objTable.getElementsByTagName("TD")(i).style.bordercolor="#98bf21"
Next
Try the above code with Google page, you will get the output as below.

Now, you are able to view all the cells of the webtable.

Saturday, March 27, 2010

How To Check Elements In A Weblist Are In Alphabetical Order


arrCtry=Split(Browser("name:=QTP").Page("title:=QTP").WebList("name:=select1").GetROProperty("all items"),";")

Set objArray=DotNetFactory.CreateInstance("System.Collections.ArrayList","")

For i=0 to Ubound(arrCtry)
If arrCtry(i)<>"--Choose One--" Then
objArray.Add(arrCtry(i))
End If
Next

objArray.Sort()
objArray.Insert 0,"--Choose One--"

For j=0 to Ubound(arrCtry)
strOuput=strOuput+objArray(j)
strOuput=strOuput+";"
Next

If strOuput=Browser("name:=QTP").Page("title:=QTP").WebList("name:=select1").GetROProperty("all items")+";" Then
Msgbox "The Weblist's values are sorted in alphabetical order"
Else
Msgbox "The Weblist's values are not sorted in alphabetical order"
End If
I hope the above snippet is useful.

Sunday, March 14, 2010

Use WMI Code Creator Tool for Quick WMI Scripting

Are you searching for WMI codes? Or do you want to know about WMI classes and properties?

Microsoft has created an application to reduce our WMI scripting time. That is WMI Code Creator. This is a free tool from Microsoft. You can download it from the below link,

http://www.microsoft.com/downloads/details.aspx?FamilyID=2cc30a64-ea15-4661-8da4-55bbc145c30e&displaylang=en

This tool reduces our WMI scripting time.
If anyone uses this tool, please include your comments. It may encourage QTP developers to opt this tool for quick WMI scripting.

Friday, March 12, 2010

Working with ChildItem and ChildItemCount methods

Consider a webtable has one row and two columns and the second column contains a webedit.
If you run the below code, Exist method will be passed and the value will be set into webedit.

If obj.ChildItem(1,2,"WebEdit",0).Exist(0) Then
obj.ChildItem(1,2,"WebEdit",0).Set "QTP"
End If
Suppose, if you run the code for negative condition (I.e. You are going to look for webedit in the first column where it does not exist), you will get an error as same as below.
To avoid this problem, use ChildItemCount method instead of ChildItem for the above criteria.

If obj.ChildItemCount(1,1,"WebEdit")>0 Then
obj.ChildItem(1,1,"WebEdit",0).Set "QTP"
End If
Now, you do not get the error for negative case.

Tuesday, February 23, 2010

Generating Random Data

Do you want to generate random data for your test? Try the below methods.
Method #1:

Set objRandm = CreateObject("Scriptlet.TypeLib")
strGUID = objRandm.Guid
Msgbox strGUID

Method #2:

Set oGuid=DotNetFactory.CreateInstance("System.Guid","mscorlib")
Set oConvert=DotNetFactory.CreateInstance("System.Convert","mscorlib")

temp= oConvert.ToBase64String(oGuid.NewGuid().ToByteArray())
temp=Left(temp,22)
temp=Replace(temp,"/", "_")
strRandm=Replace(temp,"+", "-")
Msgbox strRandm
This method is as same as previous one, but length of the string is shorter.
Method #3:

Msgbox hex(( ( (timer+rnd(1)) *100) + int(rnd(1)*16)*&hf0000 ) mod &h100000 )
The above code generates semi-unique random strings.

Getting Attached Functional Libraries' And Data Table's Path

Do you want to get the attached functional libraries' and data table's path? Try the below snippets.

Getting Functional Libraries List:
Msgbox Setting("TestFuncLibFilesList")
Getting Data Table's Path:
Msgbox Setting("DataTablePath")

Wednesday, February 17, 2010

Accessing Web Objects Using DOM Methods

ElementFromPoint Method
x=Browser("name:=Google").Page("title:=Google").WebEdit("name:=q").GetROProperty("x")
y=Browser("name:=Google").Page("title:=Google").WebEdit("name:=q").GetROProperty("y")
Browser("name:=Google").Page("title:=Google").Object.elementFromPoint(x,y).Value="QTP" 'Sets value in web edit using coordinates

GetElementsByTagName Method
Set obj= Browser("name:=Google").Page("title:=Google").Object.getElementsByTagName("INPUT")
inCount=obj.Length-1
For i=0 to inCount
If obj(i).Name="q" and obj(i).Type="text" Then
Browser("name:=Google").Page("title:=Google").Object.getElementsByTagName("INPUT")(i).Value="QTP" 'Sets value in web edit using tag name.
End If
Next

GetElementsByName Method
Set obj= Browser("name:=Google").Page("title:=Google").Object.getElementsByTagName("INPUT")
inCount=obj.Length-1
For i=0 to inCount
If obj(i).Name="q" and obj(i).Type="text" Then
Browser("name:=Google").Page("title:=Google").Object.getElementsByName(obj(i).Name)(0).Value="QTP" 'Sets value in web edit using element's name.
End If
Next

GetElementByID Method
Browser("name:=Google").Page("title:=Google").Object.getElementByID("XXXX").Value="QTP" 'Sets value in web edit using element's ID

Verifying Child Object Existence Using Contains Method
Set objWebEdit=Browser("name:=Google").Page("title:=Google").WebEdit("name:=q").Object
msgbox Browser("name:=Google").Page("title:=Google").webTable("index:=0").Object.contains(objWebEdit)'If the webtable contains the specified child object, then Contains method will return True.

Friday, February 5, 2010

XML DOM and Xpath Snippets

In this article I am going to explain about the XML DOM methods and Xpath queries.

The Example XML Document Used For This Article



#1: Finding Elements by Attributes
If you want to access the name of the employee two, write attribute filter condition in your xpath query.
/Employees/Employee[@id='002']

Code:
gStrOrPath="C:\ Test.xml"'Path of your XML
Set gObjXmlOR = CreateObject( "Microsoft.XMLDOM")
gObjXmlOR.Async = "False"
gObjXmlOR.Load(gStrOrPath)
StrXQuery="/Employees/Employee[@id='002']" ' Attribute filter condition in your Xpath query
Msgbox gObjXmlOR.documentElement.selectSingleNode(StrXQuery).Text


The msgbox displays the child element’s text (I.e. Peter).

#2: Finding Elements with Text
Here I have written Xpath query to find the employee Peter’s gender using his name.
/Employees/Employee/name[.='Peter']

Code:
StrXQuery ="/Employees/Employee/name[.='Peter']" ' Text filter condition
Msgbox gObjXmlOR.documentElement.selectSingleNode(StrXQuery). Attributes.getNamedItem("gender").Text


The msgbox displays Sam’s gender as in the XML.

#3: Checking an Element has child or not
To find an element has child or not, then use XML Dom hasChildNodes method.
As per the example XML document, I am finding the employee node has child or not.

StrXQuery="/Employees/Employee[@id='002']
Msgbox gObjXmlOR.documentElement.selectSingleNode(StrXQuery).hasChildNodes


#4: Checking Errors in XML

Set gObjXmlOR = CreateObject("Microsoft.XMLDOM")
gObjXmlOR.async = False
gObjXmlOR.load("Test.xml")
If gObjXmlOR.parseError.errorCode <> 0 Then
MsgBox("Parse Error line " & gObjXmlOR.parseError.line & ", character " & _
gObjXmlOR.parseError.linePos & vbCrLf & gObjXmlOR.parseError.srcText)

End If

Friday, January 29, 2010

Kill QTP Using Your Mobile Phone

If you want to kill QTP when you are not in your work place, then try the below technique. But you need MS Outlook in your remote PC and mobile phone with GPRS.

Step 1:

Create a VBS file with the below code and save it wherever you want it in your PC,

Option Explicit

Dim objWMIService, objProcess, colProcess

Dim strComputer, strProcessKill

strComputer = "."

strProcessKill = "'QTPro.exe'"

Set objWMIService = GetObject("winmgmts:" _

& "{impersonationLevel=impersonate}!\\" _

& strComputer & "\root\cimv2")

Set colProcess = objWMIService.ExecQuery _

("Select * from Win32_Process Where Name = " & strProcessKill )

For Each objProcess in colProcess

objProcess.Terminate()

Next

WScript.Quit


Step 2:

Open notepad, paste the below code and save it as bat file (I.e. .bat format)

C:\WINDOWS\system32\cscript.exe "C:\Documents and Settings\Administrator\Desktop\testbat.vbs"

Make sure to mention your VBS file’s location in your bat file.


Step 3:

Open Outlook and select Tools->Rules and Alerts…



Click on New Rule

Select ‘Check messages when they arrive’ option and click on ‘Next’ button.

Select the checkbox as same as below and click on ‘specific words’ link.

*Type any text in the below indicated textbox, click Add button and press OK. Here I have typed ‘Start Script’ and this is also my email's subject. This is case sensitive. While sending email ‘Start Script’ text should be your email’s subject.

Select start application checkbox as same as below and click on application link. Then you have to browse the bat file which you have just created in the Step 2: and click on Finish button.

And finally you will see the new rule in Rules and Alerts window as same as below and click on ‘Apply’ button.

Now you are ready to kill your QTP from remote place. Just send an email to your email address through your mobile phone. Note: Your MS Outlook application should be in active mode in your remote PC.

*The email’s subject should match with your rule specified word.

After sending the e-mail, QTP exe will be killed from your remote PC.


Please let me know if you face any issues.

Saturday, January 23, 2010

Make Your QTP Script Talk

Make your QTP script talk to you. Try the below code, the script will tell you the current iteration number. Before running the script, please switch on your PC's speakers.

Set oVoice = CreateObject("sapi.spvoice")
oVoice.Speak "Iteration "&Environment.Value("TestIteration")
Set oVoice =Nothing


Reference: http://en.wikipedia.org/wiki/Microsoft_Speech_API

Sending An Email Using QTP DOT Net Factory

Sending HTML formatted e-mail using QTP DOT Net factory. In the below code I have used Gmail account. You may try with other accounts also.

Dim vStUserName,vStPassword,vStServerName

vStUserName="Gmail Account Username"'Enter your Gmail Account User Name
vStPassword="Gmail Account Password"'Enter Your Gmail Account Password
vStServerName="smtp.gmail.com"'Gmail SMTP Server Name

vStFromAddress="FromAddress@gmail.com"'Enter valid From Address
vStToAddress="ToAddress@yahoo.com"'Enter Valid To Address

Set oCredentials=DotNetFactory.CreateInstance("System.Net.NetworkCredential","System",vStUserName,vStPassword)
Set oSMTPClient=DotNetFactory.CreateInstance("System.Net.Mail.SmtpClient","System",vStServerName)
Set oMessage=DotNetFactory.CreateInstance("System.Net.Mail.MailMessage","System")
Set oFromAddress =DotNetFactory.CreateInstance("System.Net.Mail.MailAddress","System",vStFromAddress)

oMessage.From=oFromAddress
oMessage.To.Add vStToAddress

oMessage.IsBodyHtml=True'If your message to be formatted with HTML, then make this property value as True or else False.
oMessage.Subject = "GMail Test"'Subject of your email
oMessage.Body = " This is the test text for Gmail email"

oSMTPClient.Port = 587
oSMTPClient.Credentials=oCredentials
oSMTPClient.EnableSSL = True
oSMTPClient.Send(oMessage)

'Kill All the objects
Set oMessage=Nothing
Set oFromAddress=Nothing
Set oCredentials=Nothing
Set oSMTPClient=Nothing

Thursday, January 21, 2010

Screen Capture Of Lengthy Web page using Snag IT Scroll Method and QTP

If you have SnagIT and QTP together in your machine, then you will be able to take screen capture of a lengthy web page.

Try the below code and you should have both QTP and SnagIT in your machine. If you don't have SnagIT, please download the trial version of SnagIT and try the code.

Function Capture_Scroll_Image
Set objShell = CreateObject("WScript.Shell")
Set oSnag = CreateObject("SNAGIT.ImageCapture")


oSnag.Input = 1
oSnag.Output = 2
oSnag.OutputImageFile.FileNamingMethod = 2
oSnag.OutputImageFile.Directory = "C:\Documents and Settings\Desktop"'Make sure to specify your file path where you need to save your screen capture file.


oSnag.EnablePreviewWindow = False
oSnag.AutoScrollOptions.AutoScrollMethod=3
oSnag.OutputImageFile.LoadImageDefaults 5
oSnag.Capture()


wait(2)


objShell.SendKeys "{ENTER}"


Do Until oSnag.IsCaptureDone
Loop


Set
oSnag=Nothing

Set objShell=Nothing
End Function

SystemUtil.Run "Iexplore.exe","http://www.google.co.in"

Browser("name:=Google").Page("title:=Google").WebEdit("name:=q").Set "QTP"
Browser("name:=Google").Page("title:=Google").WebButton("name:=Google Search").Click
Browser("name:=QTP - Google Search").Sync


Call Capture_Scroll_Image'Calling the function to capture lengthy web page

Browser("name:=QTP - Google Search").Close


After running the script you will get the lengthy screen capture of the web page as same as below.


Adding Your Own QTP Tip Of The Day

If you want to add your own organization tip for QTP instead of predefined tips which are displayed in QTP start up page, then go to C:\Program Files\Mercury Interactive\QuickTest Professional\dat and open the Tips text file. In this file you can add your organization or training centers tips.

For example: I want to instruct the user to save all your scripts in D: drive.

After adding the tip for the above instruction in the Tip file, you can see the tip as same as below in your QTP start up page,



Friday, January 15, 2010

Balloon Tool Tip Trick in QTP Instead Of Automatic Timeout Message Box

If you are using automatic timeout msgbox in your QTP Script(s), then please switch over to Balloon Tool Tip. It is much better than VB script or WSH timeout message boxes.

For instance: If you want to know the current iteration number while running your scripts, then you may use automatic timeout msgbox using the below code.

Start_Time=Time

Set WshShell = CreateObject("WScript.Shell")
wshShell.Popup "Current Iteration No. "&Environment.Value("TestIteration"), 5 'Next step will not run until the time-out expires

SystemUtil.Run "Iexplore.Exe","
http://www.google.co.in"
Browser("name:=Google").Page("title:=Google").WebEdit("name:=q").Set "QTP"
Browser("name:=Google").Page("title:=Google").WebButton("name:=Google Search").Click


End_Time=Time
Msgbox Hour(End_Time-Start_Time) & ":" & Minute(End_Time-Start_Time) & ":" & Second(End_Time-Start_Time)


The above code has one drawback. When the msgbox is invoked, next step will not run until the specified msgbox's time-out expires.

Try the same scenario using Balloon Tool Tip code. The current iteration number will be displayed in System Tray and the script will not be stopped to display the tool tip.

icon_Path="C:\Documents and Settings\Desktop\6.ico" 'Choose any Icon file path from your PC. Make sure the file format should be .Ico.
Set oNtfy=DotNetFactory.CreateInstance("System.Windows.Forms.NotifyIcon","System.Windows.Forms")
Set oToolTip =DotNetFactory.CreateInstance("System.Windows.Forms.ToolTipIcon","System.Windows.Forms")
Set oIcon=DotNetFactory.CreateInstance("System.Drawing.Icon","System.Drawing",icon_Path)


Function fn_BalloonToolTip(vIterationNo)
oNtfy.Icon=oIcon
oNtfy.BalloonTipIcon=oToolTip.Info
oNtfy.Visible=True

oNtfy.Text = "QTP Info." 'Balloon Tool Tip Text Name
oNtfy.BalloonTipTitle = "Current Iteration No" 'Balloon Tool Tip Title
oNtfy.BalloonTipText="Current Iteration No. "&vIterationNo
oNtfy.ShowBalloonTip(5000) 'This line displays current iteration No in system Tray
End Function

Function fn_Kill_Balloon 'This function kills all the objects.
oNtfy.Dispose() 'After calling this method you will not see the balloon icon in system tray
Set oIcon =Nothing
Set oTool =Nothing
Set oNtfy=Nothing
End Function


Start_Time=Time
Call fn_BalloonToolTip(Environment.Value("TestIteration")) 'Calling balloon tool tip function


SystemUtil.Run "Iexplore.Exe","
http://www.google.co.in"
Browser("name:=Google").Page("title:=Google").WebEdit("name:=q").Set "QTP"
Browser("name:=Google").Page("title:=Google").WebButton("name:=Google Search").Click


Call fn_Kill_Balloon'Calling kill function

End_Time=Time

Msgbox Hour(End_Time-Start_Time) & ":" & Minute(End_Time-Start_Time) & ":" & Second(End_Time-Start_Time)

After invoking the fn_BalloonToolTip function, you will see the Balloon Tool Tip in your system tray as same as below,




In previous WScript code, the QTP script is waited until the msgbox timeout expires. Here QTP script will not wait for Balloon Tool Tip to be closed. The tool tip will remain in the system tray unless/until you call the fn_Kill_Balloon

I hope this technique will be useful for others also.

Please let me know if you have any questions in this.

Saturday, January 9, 2010

Working With Screen Capture in QTP

Converting PNG to JPG format

I have seen one question in Advanced QTP forum, that is the user needed to capture screenshot in JPG format instead of PNG.
QTP cannot capture snapshot(s) as JPG format, but we have an option to convert it using DOT Net Factory. I hope this code will be useful for all QTP users. So I have posted this in my blog.

Here is the code to convert from PNG to JPG

sImagePath="C:\Documents and Settings\TEMP\Desktop\cap.png"'Make sure to mention your destination path for snapshot

Desktop.CaptureBitmap sImagePath'Capturing as PNG format

Call ConvertJPG(sImagePath)

Function ConvertJPG(sBmpPath)

Set oBmp=DotNetFactory.CreateInstance("System.Drawing.Bitmap","System.Drawing",sBmpPath)
Set oDir=DotNetFactory.CreateInstance("System.IO.Path","mscorlib")
Set oFile=DotNetFactory.CreateInstance("System.IO.File","mscorlib")

oBmp(sBmpPath)

sNewFile = oDir.GetDirectoryName(sBmpPath)
sNewFile = sNewFile&"\" & oDir.GetFileNameWithoutExtension(sBmpPath)
sNewFile = sNewFile&"." &"JPG"
oBmp.Save(sNewFile)'Saving as JPG format

oBmp.Dispose()
oFile.Delete(sBmpPath)'Deleting the previous PNG file.

Set oDir=Nothing
Set oFile=Nothing
Set oBmp=Nothing
End Function

Tuesday, January 5, 2010

Working with Hashtable using QTP DOT Net Factory

Hashtable is similar to a Dictionary object. It stores values in key-item pairs. Hashtable can be implemented in QTP using DOT Net factory with .net framework mscorlib assembly.

The below line creates an instance of the Hashtable.

Set oHash=DotNetFactory.CreateInstance("System.Collections.Hashtable","mscorlib")

Now we are ready to work with Hashtable methods and properties in QTP.


Adding an element:
Syntax: Object.Add key, value

Example:
Set oHash=DotNetFactory.CreateInstance("System.Collections.Hashtable","mscorlib")
oHash.Add 1,"QTP"


Removing all elements:
Syntax: Object.Clear
Example: oHash.Clear
'This line clears all the elements in the Hashtable object

Counting Property:
The count property returns number of items in the hastable.
Msgbox oHash.Count


For more information about Hashtable, please navigate the below links,
http://msdn.microsoft.com/en-us/library/4yh14awz(VS.80).aspx
http://en.wikipedia.org/wiki/Hash_table
http://www.itl.nist.gov/div897/sqg/dads/HTML/hashtab.html

Saturday, January 2, 2010

Querying Text File

Most of the QTP developers are using delimited text file instead of datatable and data can be retrieved by using FileSystemObject. This is a good idea, but it has limitations which are listed in MSDN by Myer as follows,


No filtering. The nice thing about databases is that you can issue a query like "Select * From Logfile Where Result = 'Error'" and you'll get back only those records where the Result field is equal to error. That can't be done with the FileSystemObject. You might want only the records where Result is equal to Error, but you'll still have to read through the entire file, from top to bottom, checking the value of the Result field each time. That's not necessarily slower (the FileSystemObject is actually pretty darn fast), but it does make your code a bit trickier to write.

Difficulty in calculating statistics. Suppose you have a directory of some kind, and you'd like to count the number of people in each of your departments. With a database, you can issue a single query that will return that information in a flash. With the FileSystemObject, well, no such luck. Instead, you'll have to examine each record, and then use an array or a Dictionary object to manually tally up the number of people in each department. This will work, but it's tedious to code (and even more tedious if you have to change that code somewhere down the road).

One and done. Another problem with the FileSystemObject is that it's a one-way street, and a dead-end street to boot. What does that mean? Well, suppose you use the FileSystemObject to read through a text file and calculate a statistic of some kind. Now you want to read through it a second time, and calculate a second statistic. Oops, with the FileSystemObject there's no turning back: Once you get to the end of the file, you're done. You can't loop back through your file. Instead, you'll have to close the file and re-open it. Are there ways to work around this? Sure, but that's even more code you'll have to write.

Difficulty in getting at the individual fields. When you use the ReadLine method to read in a line from a text file, you get, well, a line from a text file. In other words, you'll get back something that looks like this:

Now we are able to overcome these obstacles by using Microsoft.Jet.OLEDB.4.0.

Step1: Create a text file as shown below and save it as CSV format at any location.

LastName,FirstName,MiddleInitial
Myer,Ken,W
Poe,Deborah,L

Step 2: Execute the code (Make sure to specify your text file's location in your code)
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H0001

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

'You need to specify the name of the folder where the text file is stored. Note that you must use a trailing \ in the folder name. In the sample script below, the path is C:\Databases.
strPathtoTextFile = " C:\Databases"

objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & strPathtoTextFile & ";" & _
"Extended Properties=""text;HDR=YES;FMT=Delimited"""

'In your Microsoft® SQL query, specify the name of the text file you want to work with (in this example, PhoneList.csv).
objRecordset.Open "SELECT * FROM PhoneList.csv", _
objConnection, adOpenStatic, adLockOptimistic, adCmdText

Do Until objRecordset.EOF
Msgbox "Name: " & objRecordset.Fields.Item("LastName")
Msgbox "Department: " & _
objRecordset.Fields.Item("FirstName")
Msgbox "Extension: " & objRecordset.Fields.Item("MiddleInitial")
objRecordset.MoveNext
Loop

Enjoy!!!!!!!!!!!!!
Source: MSDN