Monday, 20 July 2015

QTP REALTIME IMP 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 method 
This method works as same as GetCellData method.
''
Eg.: msgbox Browser("name:=qtp").WebTable("index:=0").CellText(1,1)

'
#2 CellTextByContext Method
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
msgboxBrowser("name:=qtp").WebTable("index:=0").CellTextByContext(1,1,"",";")
Code to retrieve the text after the delimiter
msgboxBrowser("name:=qtp").WebTable("index:=0").CellTextByContext(1,1,";")
'
#3 TextCellExist Method
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.
Eg.: msgbox Browser("name:=qtp").WebTable("index:=0").TextCellExist(1,1,"asiq")

Step-2


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 theGetRowWithCellText method 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)

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.

SetobjTable=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.



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.

If obj.ChildItem(1,1,"WebEdit",0).Exist(0) Then 
obj.ChildItem(1,1,"WebEdit",0).Set "QTP"
End If


To avoid this problem, use ChildItemCount method instead of ChildItemfor 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 and Exist method returns False.


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 method 
This method works as same as GetCellData method.
''
Eg.: msgbox Browser("name:=qtp").WebTable("index:=0").CellText(1,1)

'
#2 CellTextByContext Method
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
msgboxBrowser("name:=qtp").WebTable("index:=0").CellTextByContext(1,1,"",";")
Code to retrieve the text after the delimiter
msgboxBrowser("name:=qtp").WebTable("index:=0").CellTextByContext(1,1,";")
'
#3 TextCellExist Method
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.
Eg.: msgbox Browser("name:=qtp").WebTable("index:=0").TextCellExist(1,1,"asiq")

Beaware 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.
Setobj=Browser("name:=Google").Page("title:=Google").WebEdit("index:=1").Object
If Not obj.disabled Then
obj.Value ="qtp"
End If

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"")"

Resizing Bitmap using Dotnet Factory

SetoImage=DotNetFactory.CreateInstance("System.Drawing.Image","System.Drawing")

vstPath="C:\Sample Pictures\Water lilies.jpg" 'path of the bitmap to be resized.

SetoBitmap=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

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.

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 theGetRowWithCellText method 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)

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

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.

Setobj=Browser("name:=Google").Page("title:=Google").Object.getElementsByTagName("LABEL")(0)
vStrActualText= obj.innerText
vStrExpectedText="The Web"
If vStrActualText<>vStrExpectedText Then 


obj.innerHTML="<span style=""background-color: yellow"">"&vStrActualText&"</span>"
Browser("name:=Google").Page("title:=Google").highlight 

Browser("name:=Google").Page("title:=Google").CaptureBitmap"C:\Documents and Settings\Asiq\Desktop\TEST.PNG",True obj.innerHTML=vStrActualText

End If


If your text is mismatched in the webpage, the script captures the bitmap of the page as same as below with highlighting it,


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.

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.

SetobjTable=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.

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"),";")

SetobjArray=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

IfstrOuput=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

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.

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.

If obj.ChildItem(1,1,"WebEdit",0).Exist(0) Then 
obj.ChildItem(1,1,"WebEdit",0).Set "QTP"
End If


To avoid this problem, use ChildItemCount method instead of ChildItemfor 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 and Exist method returns False.

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?
If yes, then please try the below snippets.

Getting Functional Libraries List:
Msgbox Setting("TestFuncLibFilesList")

Getting Data Table's Path:
Msgbox Setting("DataTablePath")

Accessing Web Objects Using DOM Methods

Using 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

In the above line, I am setting value in the Google Search webedit.

Using 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


Using 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


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

Verifying Child Objects Using Contains Method

SetobjWebEdit=Browser("name:=Google").Page("title:=Google").WebEdit("name:=q").Object 

msgboxBrowser("name:=Google").Page("title:=Google").webTable("index:=0").Object.contains(objWebEdit)

If the webtable contains the web object, then the message box displays True.

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']
MsgboxgObjXmlOR.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

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 onapplication 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.

Subscribe  channel to get  latest video
https://www.youtube.com/channel/UC1EmncBu2maDiHNMNNqxw9g

No comments:

Post a Comment