Blog to understand automation concepts in QTP, Selenium Webdriver and Manual Testing concepts

Showing posts with label Advanced QTP. Show all posts
Showing posts with label Advanced QTP. Show all posts

Running JavaScript in UFT on Page

In UFT,  we can run java script on a page using RunScript method as shown below. This can be very useful to perform operation on a page/element in the page through Java script.


Browser(...).Page(...).runscript("javascript statement")

XPath Object Identification in UFT descriptive programming

UFT also supports XPATH and css together with descriptive programming, object repository and DOM for object Identification.

Xpath stands for Xml Path. Below are some XPath examples to be used with UFT. Xpath and css are most widely used object identification way in selenium also.


Xpath examples:

Id: 

Browser(...).Page(...).weblink("xpath:=//a[@id='linkuft']").click

Attribute Value:

Browser(...).Page(...).weblink("xpath:=//a[@Atttribute='goodclass']").click

text:

Browser(...).Page(...).weblink("xpath:=//a[text()='UFT']").click 

partial attribute value

Browser(...).Page(...).weblink("xpath:=//a[starts-with(@attribute,'goodclass']").click

Browser(...).Page(...).weblink("xpath:=//a[contains(@attribute,'goodclass']").click

Browser(...).Page(...).weblink("xpath:=//a[ends-with(@attribute,'goodclass']").click


To know details on what is CSS and XPath and how to capture CSS or xpath of an element. refer to

XPath and CSS for selenium/UFT

We can use tools like firebug/firepath or IE developer tool to identify the xpath/css of an element.

xpath is really useful when element is not identified diretly based on Object repository properties and used to
identify an element based on relative element existence based on other elements in the tree.

WebTables in UFT - 10 Key points

1. WebTable or html grid are integral part of html pages and a lot of application data is organised in WebTables. QTP provides different methods to interact with the webtable in the web application. In this remaining article, we will discuss key points to interact with the webtables. 
Below image shows how a webTable is divided into column and rows and data can be extracted from cell in the web table.


2. Verify if the table exist in the application
istbleExist=Browser("qaaqtp").Page("title:=.*").WebTable("name:= DataTable").exist

3. In case the table exist in the Page, we can get the count of rows and columns in the application as shown below:

iRowCnt=Browser("qaautmationqtp").Page("title:=.*").WebTable("name:= DataTable").RowCount
'' for each of the  row, get the column count for each row
For rownum=1 to iRowCnt
 iColCnt=Browser("qaautmationqtp").Page("title:=.*").WebTable("name:=DataTable").ColumnCount(rownum) 
 MsgBox iColCnt
Next

4. Now we know the number of rows and columns in the table, we can extract cell information using the code below:
CellData= Browser("qaautmationqtp").Page("title:=.*").WebTable("name:=DataTable").GetCellData(rownum,colcnt)

5. We can perform action on object of specific type in a cell in the webTable based on the cell
ibtnCnt=Browser("qaautmationqtp").Page("title:=.*").WebTable("name:=DataTable")
.ChildItemCount(4,3,"WebButton")
This will get the number of child items in a particular cell of particular type.

6. This will click on the 2nd  webbutton in row 4 and column 3 of the webtable.
Browser("qaautmationqtp").Page("title:=.*").WebTable("name:=DataTable").ChildItem(4,3,"WebButton",1).click

7. Using HTML DOM also, we can get count of objects in a webtable
ielemCnt = Browser("Google").Page("title:=.*").WebTable("name:=DataTable").object.getElementsbyTagName(strTagName).length

8. We can get row count of element based on the cell text as below:
irownum = object.GetRowWithCellText ("text to search",columnnum, startfromrownum)

9. We can work with webtable together with dynamic descriptive programming as shown below:
Set objDesc = Description.Create
objDesc("micclass").value = "WebElement"
objDesc("html tag").value = "TD"
Set childobjdesc=Browser("Google").Page("title:=.*").WebTable("name:=DataTable")ChildObjects(objDesc)

10. Using ChildItemCount and childItem, we can extract information from webTable as shown below:

Public Function findObjectinWebTable(strobjType,iRow,iCol)
 ''get child count of specific object type
 oChildCnt=Browser("qaautmationqtp").Page("title:=.*").WebTable("name:=DataTable").ChildItemCount(iRow,iCol,strobjType)
 If oChildCnt >0
  ''Perform action based on object type
  Set ChldItem = Browser("qaautmationqtp").Page("title:=.*").WebTable("name:=DataTable").ChildItem(iRow,iCol,strobjType,0)
 If (strobjType = "Link" or strobjType ="WebEdit") Then
  ChldItm.Click
  ElseIf(stobjType = "WebCheckBox") Then
  ChldItm.Set "ON"
 End If
End Function

Descriptive Programming in UFT : 10 Key points

1. Descriptive programming is describing the object properties in the code itself instead of defining an object in the object repository.

2. Descriptive programming has two flavors: 
 a.) Static DP
 b.) Dynamic DP

3. Static DP defines the object property in inline description in the Page tree structure as defined below:
''example 3.1) - In case all the object in the tree are defined as static DP
Browser("title:=Bing").Page("title:=Bing").WebEdit("name:=qb").Set "test automation"

''example 3.2) Multiple properties are used to uniquely identify an element,
 the properties are seperated by ,
Browser("title:=ng").Page("title:=ng").WebEdit("name:=qb", "type:=input").Set "test"


4. The structure of element in the page follows the tree structure as Browser --> Page --> WebElement.
We cannot define browser and page as descriptive programming, in case  last element in the tree(WebEdit, WebElement is defined from Object repository.

5. Dynamic description example is shown below:
Set objdescBR = description.Create
objdesc("title").value ="Google"
Set objdescPg = description.Create
objdescPg("title").value ="Google"
Set objdesc = description.Create
objdesc("micclass").value ="Link"
Set objLinks = Browser(objdescBR).Page(objdescPg).childobjects(objDesc)
Msgbox objLinks.count

6. Dynamic description is useful to perform similar action on group of elements. e.g: get the text of all the links in the page.

7. Set objLinks = Browser(objdescBR).Page(objdescPg).childobjects(objDesc) returns list of elements. This can be a list of links in the page or multiple checkbox
in the page.

8. We can access each element of group of element using objLinks(index) as shown below:
For i=0 to objLinks.count -1 to Step 1
 objLinks(i).GetRoProperty("name")
Next

9. Descriptive programming is very useful in case of:

9.1 - Common element definition used across a set of pages in the application. e.g: Canel, OK, New button
9.2 - In case of DP programming used in function libraries, the objects are defined in Function library and can be used in multiple tests.
9.3 - Performing same action with multiple elements with similar properties.
9.4 - Maintaining OR can be complex and OR size may grow considerably in the application. 
9.5 - Application is not ready. 
9.6 - Keyword driven framework.
9.7 - A good approach is to use a mix of Object Repository and Object repository and xpath definition.

10. Regular expression can be used together with Descriptive programming, which can again be part 
of another article 10 things to know, regular expression with descriptive programming.

Environment variable in UFT : 10 Key points

1. Definition - Environment variables are variables used across QTP Scripts/ all actions in a script/recovery scenario/function libraries in a UFT script.
Understand them as global variables for UFT Test Scripts.

2. Types of Environment Variables:
Environment variables are of 2 types: 
a. Built in Variables
b. User Defined Variables

3. Built -in variables are defined in QTP and can provide information on the QTP scripts and the operating system.

4. User Defined variables are again be divided into two types: 
       a. User Defined - Internal - defined at test level by adding a new environment parameter.
       b. User Defined - External - imported for an external xml file with parameters and values for parameters defined in the external file.




5. Steps to add user defined environment variables:

a.) In the test in which environment variable are to be added, Go to file -> Settings -> Environment.
b.) In variable type, select user defined. 
c.) Click on + icon, and add a new parameter with name and value.

6. To import from external file, check checkbox to load from external file and provide the path of the external file.

7. Environment variable for external file can be imported through code as shown below:

fileName = Environment.ExternalFileName

if (fileName = "") Then

    Environment.LoadFromFile("C:\testEnv.xml")

End If

8. Access and update environment variable in the script:


''Acessing an environment variable:

Testval =  Environment.Value("testing")

''Updating an user defined variable

Environment.Value("testing") = "testing2"

9. Example of environment variable xml file


<Environment>
 <Variable>
  <Name>Environment1</Name>
  <Value>ValueA</Value>
 </Variable>
 <Variable>
  <Name>Variable2</Name>
  <Value>ValueB</Value>
 </Variable>
</Environment>


10. Useful Reference: 


http://gareddy.blogspot.in/2010/12/qtp-environment-variables.html

http://qaautomationqtp.blogspot.in/2013/05/environment-variables-in-qtp.html

Summary

environment variable summary


VBScript code to convert Excel data to HTML format


This article explains the code to convert content of an excel file into html code. This can be useful for better representation of excel data in html format.

Code to convert Excel data to HTML format

''strWbk - Full path of the excel workbook
''strWsheetName - Name of the worksheet
'' strHTMLFile - Name of the html file with path
Public Function CreateHTMLFromExcel(strWbk,strWsheetName,strHTMLFile)
Set oExcel = Createobject("Excel.Application")
oExcel.visible = false
Set objExcelWB = oExcel.Workbooks.Open(strWbkPath)
Set objExcelWS = objExcelWB.Worksheets(strWsheetName)
'Getting the rows and column count
 strColumnCount = objExcelWS.UsedRange.Columns.Count
 strTotRows = objExcelWS.UsedRange.Rows.Count
strTable = "<table border=""""2"""">"
'Create html table based on content of the excel file
 For j=1 to strTotRows
  strTable = strTable & "<tr>"
  For i=1 to strColumnCount
    strData = Trim(objExcelWS.Cells(j,i))
    strTable= strTable & "<td>"& strData &"</td>"
  Next
  strTable =strTable & "</tr>"
 Next
 strTable = strTable & "</table>"
 set objFSO=Createobject("scripting.FileSystemObject")
 set objtxt = objFSO.createTextFile(strHTMLFile)
    objtxt.write(strTable)
'Closing the workbook
 objExcelWB.Close
 set objFSO =nothing
End Function

Ordinal Identifier in QTP

While learning the objects, QTP tries to identify objects based on the mandatory and assistive properties of the object. In case the above properties are insufficient to uniquely identify the object. QTP uses the ordinal identifier properties to uniquely identify the object together with the madatory and assistive properties.


There are three type of Ordinal Identifier in QTP which are assigned as numeric integer value for the object based on the order occurrence of object in the browser.


The three types of ordinal identifier are described below:



Ordinal Identifier

Description

 Index Based

Based on the object in the window, An index value is assigned to object based on existence in the source code. Index value starts from 0.

Location Based 

The Location property is based on location of object, works vertically from top to bottom and then from left to right. value starts from 0.

Creation Time

The Creation Time property is used for browser objects mainly and used to identify multiple browsers based on the time the browser/page was open. Value starts from 0

Properties for object identification in QTP

QTP learns the properties of test objects to uniquely identify the object at run time. There are predefined set of properties for object classes in each environment.


Object are classified as Object classes for each environment. For e.g. environment Standard Windows environment as shown below will have all the test object class defined and defined are the mandatory and assistive properties to identify the object. Also we can set smart identification On for the object and the default ordinal identifier.to identify the object. 


To have a look at Object Identification properties for an object, Navigate to Tools>Object Identifier.


Let us understand the object Identification Window:


1. Environment: Lists all the environment for which objects are defined.


2. Object Classes:
List all the controls available for the environment selected.


3. Mandatory Properties:
These are the properties QTP always learns for the test object class selected.


4. Assistive Properties: In case object is not uniquely identified using the mandatory properties, there are some assistive properties which are learned to uniquely identify the object.


5. Smart Identification
is false by default, but can be checked for identification.


6. Ordinal Identifer: In case object is not identified using the above properties , Ordinal identifier is used to identify the object

List of Regular Expression for UFT/QTP

Regular expression are used to match input text with the pattern provided by regular expression engine. A pattern consists of one or more character literals, operators, or constructs. Below table explains the different regular expression patterns to identify the input text matches the expected pattern


Regular expression are used to validate the input text provided with the expected pattern. e.g : validating date format is correct or telephone number  provided is in correct format.



Reg. Expression

Description

( .)

 A dot matches single character (.) eg test. will match dot followed by any single character.example: testa, test5 

 [ab]

Matches either of the character in the list. e.g 23[ab] will match both 23a or 23b but not 23r

[^ab]

Matches all the characters excluding the the character in the list. e.g 23[^ab] will not match both 23a or 23b but will match23r,235 or 23 followed by any character other

 \b

Matches a word at boundary. e.g test/b will match entest but not entester

 [x-y]

Matches a single character in the range. e.g 23[a-d] will match 23a,23b,23c,23d but not 23r

 [^x-y]

Matches a single character not in the range. e.g 23[^a-d] will not match 23a,23b,23c,23d but 23r

 \B

Matches a word not at boundary. e.g test/b will match entest but not entester

 \W

Matches any non-alphaNumeric character excluding underscore

 \w

Matches any alphaNumeric character including underscore

*

Wildcard character matching the multiple occurence of preceding character. e.g rat* will match ra, rat, rattt, ............i.e multiple occurence of preceeding character t in this example.

 .*

Wildcard character matching the multiple occurence of preceding character.Preceeding character is . in case, so ra.* will match any string starting with ra

+

Similar to * but atleast one occurence of the character should match.e.g : rat+ will match rat but not ra

 ?

 matches zero or one occurrences of the preceding character. For example: ra?t match rt or rat only

 |

Matches either of the character seperated by |.example nes(t|l)ey will match nestey or nesley.

 \d

Matches a digit character

\D

Matches a non- digit/numeric character

\

marks the next character as special character or a literal. e.g \n is for new line ; \\ for \ and \d for a digit character

^

matches the pattern at start of line. e.g: ^test will match testing, tester but not autotest.

 $

matches the pattern at end of line. e.g: test$ will match autotest but not tester.

 |

Matches either of the character seperated by |.example nes(t|l)ey will match nestey or nesley.

 {}

Matches the start and end of qualifier expression. e.g a{4,5} will match aaaa or aaaaa

Reference:  Regular Expression Language - Quick Reference

Code to get title of all open browsers in QTP/UFT

We can get titles of all the open browser open using descriptive programming in QTP as explained in the code below:


Function GettitleAllbrowsers()
GettitleAllbrowsers = ""
Set objBrowser = Description.Create
objBrowser("micclass").Value = "Browser"
''Get all browsers instances in ObjBrowserLst 
Set objBrowserLst= Desktop.ChildObjects(objBrowser)
''Get the count of all the browsers open
browsercnt = objBrowserLst.count
For i=0 to objBrowserLst.count-1  
'Store title of the Page in a variable 
GettitleAllbrowsers = GettitleAllbrowsers + ">"+objBrowserLst(i).GetROProperty("title") 
Next 
Set objBrowser = nothing
Set objBrowser = nothing
End Function


For further manipulating the browser details using descriptive programming. Please go through the below articles:


Code to close multiple browsers except Quality Center/ALM in UFT/QTP?

How to close the IE browsers and Internet Explorer not responding windows forecefully -VBScript

Types of Environment variables in QTP / UFT

Below are the types of environment variables in QTP


1) Built-in - Used to extract test specific and machine/OS information. E.g ActionName, LocalHostName and OS to name a few.


2) User-defined Internal - Defined for the test and available only to the test in which it is defined.


3) User-defined External - Can be used across tests and can be loaded from an external xml file dynamically at run time or at the test level.


More Details on this topic, click on Environment Variable Loading




Simulating Keyboard and mouse operations in UFT using settings.replay type

In QTP, We can replicate device events, i.e keyboard and mouse operation using the below line of code.

Setting.WebPackage("ReplayType") = 2

By default, value of the Setting is 1, in which UFT interacts with application using the browser through DOM.

Setting.WebPackage("ReplayType") = 1

In case, you are not able to perform click or operation on an element in the page, please give a try by providing setting:

 Setting.WebPackage("ReplayType") =2

Useful Batch file commands

Batch files help user to execute series of commands in the batch file. We can execute large number of commands in one go using bat file.

Some useful batch commands:

@echo off does not echo the text post the command and only displayes the execution result

@echo on the text post the command and only displays the execution result

Pause- the batch file execution is halted until further intervention of user by pressing keys.

CALL - calling one batch file from another batch file

cd -  Change directory

cls - clean the window

copy -copy files from source to destination

DIR - List of directory and files

ERASE - delete files

FC - Compares files
 
IF - Conditional statement

mkdir - Make a new directory/folder

move - move files or folder

ping - Check TCP/IP connection to a remote IP address

rmdir - remove folder/directory

SC - Managing services

set - manipulate environment variable 

taskkill - kills an active process

taslist - List active processes

REM - remark statement
Arguments %1….. – This is the first argument to be provided from the
 command prompt as parameter for the batch command.


Reference: http://www.robvanderwoude.com/batchcommands.php


Starting with batch files:

Let us take a simple example of using batch file to display Create a new file with extension as .bat. Suppose we need to compare two text files. The content of batch file for this will look like


@echo off

Fc %1 %2 /n>%3

Pause


To execute this bat file, we have to write in command prompt  as:

D:\new.bat d:\testsrc.txt d:\testdest.txt d:\testlog.txt

Manipulation XML using XPath for VBScript/UFT

This article explains how to extract information from an xml file based on the element xpath using Microsoft.XMLDOM and VBSript. You can try using the code as shown below.


''---------------------------------------------------------------------------------
'' Step 1 : Copy the content removing comments in a file and save the file
''----------------------------------------------------------------------------------

'' --------------File Content ------------------------------------------------------
''XMLTextFile = "<books><name>mybook</name><price>50</price><Author rating="high">matt</Author>
''<name>his book</name><price>150</price><Author rating="low">henry</Author>
''<name>twist</name><price>550</price><Author rating="high">henry</Author></books>"

''-------------Call the functions with Parameters------------------------------------
msgbox getXMLTextFileValue("d:\testdta.xml","//price")
msgbox getXMLTextFileValue("d:\testdta.xml","//Author[@rating='high']")
msgbox getxmlAttributeValue("d:\testdta.xml","//Author","rating")
call getAllNodeValues("d:\testdta.xml","//Author")
''-----------------------------------------------------------------------------------

'' Function 1 - Reading the node text
''Arguments - FileName and xpath of node

''-----------------------------------------------------------------------------------
function getXMLTextFileValue(XMLTextFile,NodeXpath)
Set objXML = CreateObject("Microsoft.XMLDOM")

objXML.async = False
objXML.resolveExternals = False
objXML.validateOnParse = False
getXMLTextFileValue = ""
boolxmlParse = objXML.load(XMLTextFile)
if(boolxmlParse) then
 objXML.setProperty "SelectionLanguage", "XPath"
 set objXML_node = objXML.selectSingleNode(NodeXpath)
        getXMLTextFileValue = objXML_node.text
 else
 msgbox "issue in xml file"
End If
End Function

''-----------------------------------------------------------------------------------

'' Function 1 - Reading the node attribute value
''Arguments - FileName and xpath of node. attribute Name of which value is to be returned

''-----------------------------------------------------------------------------------


function getxmlAttributeValue(XMLTextFile,NodeXpath, attributeName)
Set objXML = CreateObject("Microsoft.XMLDOM")

objXML.async = False
objXML.resolveExternals = False
objXML.validateOnParse = False
getxmlAttributeValue = ""
boolxmlParse = objXML.load(XMLTextFile)
if(boolxmlParse) then
 objXML.setProperty "SelectionLanguage", "XPath"
 set objXML_node = objXML.selectSingleNode(NodeXpath)
        getxmlAttributeValue = objXML_node.getAttribute(attributeName)
 else
 msgbox "issue in xml file"
End If
End Function

''-----------------------------------------------------------------------------------

'' Function 1 - Reading the value of all the matching nodes
''Arguments - FileName and xpath of node.

''-----------------------------------------------------------------------------------

function getAllNodeValues(XMLTextFile,NodeXpath)
Set objXML = CreateObject("Microsoft.XMLDOM")

objXML.async = False
objXML.resolveExternals = False
objXML.validateOnParse = False

boolxmlParse = objXML.load(XMLTextFile)
if(boolxmlParse) then
 objXML.setProperty "SelectionLanguage", "XPath"
 set objXML_node = objXML.selectNodes(NodeXpath)
        for each nodet in objXML_node
  msgbox nodet.text
 Next
End If
End Function

To view or not the test results in UFT

Once a test is executed in QTP/UFT, test results are displayed. UFT provides us the option to view the test results once the test execution completes. Follow following steps for the same.
  • Navigate to Options>General.
  • There is checkbox "View results when run session ends". In case the checkbox is checked, UFT results are launched automatically once the test execution completes. In case not checked, the results are not launched automatically once execution completes.


viewrunresults

Sorting excel data multiple times based on column Name using VBScript


''Input Information - Workbook file Name with path
''WorkSheet Name
'' Provide the sort criteria based on which data needs to be filtered seperated by |

WorkBookFile = "C:\\testing.xls"
SheetName = "testing"
MultipleSortCriteria = "TestName|TestClass|TestPath"
'' Define the constants to be used in the script
  Const xlYes = 1
  Const xlAscending = 1
  Const xlDescending = 2
  Set oXL = CreateObject("Excel.Application")
  Set oWB = oXL.WorkBooks.Open(WorkBookFile)
  Set oWS = oWB.Worksheets(SheetName)  
  Set oRnge = oWS.UsedRange
  ColCnt = oRnge.columns.count
  '' Create an array based on the sort criteria provided 
  aSrtCriteria = split(MultipleSortCriteria,"|")
  For i = ubound(aSrtCriteria) to 0 step -1
  ''Loop the times data needs to be sorted
   For j = 1 to ColCount step 1
    
    If (oWS.cells(1,j).value =aSrtCriteria(i)) Then
     '' Sort the data based on the column name
     Set oRngeSrt = oXL.Range(Chr(asc("A")- 1+j) & "1")
     oRnge.Sort oRngeSrt, xlDescending, , , , , , xlYes 
     oWB.save
      Exit For
    End If    
   Next
  Next
   oWB.Close
   oXL.Quit
   Set oWB = Nothing
   Set oXL = Nothing
 

VBScript Code to close the IE browsers and Internet Explorer not responding window


  • VBScript Code to close the IE browsers and Internet Explorer not responding window

Set WShell = CreateObject("WScript.Shell")
''This will close all the instances of task iexplore.exe.
''Parameter /f kills the process forcefully
WShell.Exec("taskkill /fi ""imagename eq iexplore.exe"" /f")
WScript.Sleep 100
''At time Internet explorer is not responding error is displayed
''The task has window title as internet explorer not responding.
''We can close the task based on window title with regular expression as Internet *
WShell.Exec("taskkill /fi ""WINDOWTITLE eq Internet*"" /f")
WScript.Sleep 100
''Once the window is closed, another window appear with similar title
'' which needs to be closed
WShell.Exec("taskkill /fi ""WINDOWTITLE eq Internet*"" /f")

  • VBScript Code to save the list of running tasks and save it in file abc.txt


''Below command will return the service for the process and save it in file abc.txt
  Set WShell = CreateObject("WScript.Shell")
''This will close all the instances of task iexplore.exe.
''Parameter /f kills the process forcefully
WShell.Exec("tasklist /fi /svc>test.txt")

ReConnecting to Remote sessions using group policy edit

In QTP/UFT automation suite execution,we may require to connect remotely to multiple machines through remote desktop connection for monitoring test execution, We may face issue in remote connection being disconnected due to network issues/remote sessions. 


ReConnecting to Remote sessions using group policy edit
To allow smooth test execution, we should reconnect to the remote sessions in case of any network disconnect. In this post, I will share what we can do to reconnect remote connection in case of session disconnect due to network issues and failures.

  • Using experience in Remote Desktop Connection

    • Go to Run>mstsc
    • In Remote Desktop connection window, Go to Experience Panel.
    • Select checkbox "Reconnect if the connection is dropped"
By default, a maximum  of twenty reconnection attempts are made at five second intervals.


  • Defining Group policy for Remote Desktop connection

    • Navigate to group policy for the machine

      • Navigate to run> gpedit.msc
      • Local group Policy editor Window is displayed.
      • Click on Administrative Templates\Windows Components\Remote desktop Services\Remote Desktop Session Host\Connections
ReConnecting to Remote sessions using group policy edit

  • Policy Settings

ReConnecting to Remote sessions using group policy edit

    • Automatic Reconnection- If policy setting is enabled, automatic reconnection is attempted for all clients running Remote Desktop Connection whenever their network connection is lost.
    • Configure keep-alive connection interval - This policy setting allows you to enter a keep-alive interval to ensure that the session state on the RD Session Host server is consistent with the client state. If you enable this policy setting, you must enter a keep-alive interval. The keep-alive interval determines how often, in minutes, the server checks the session state. The range of values you can enter is 1 to 999,999.

Code to close multiple browsers except Quality Center/ALM in UFT/QTP?

Below Code shows how to close all browsers except browser based on the title of the browser in UFT / QTP.


Function CloseAllOpenbrowsersExcept(browsertitle)
Set oBrowser = Description.Create
oBrowser("micclass").Value = "Browser"
''Get all browsers open 
Set oBrowserLst= Desktop.ChildObjects(oBrowser)
For i=0 to oBrowserLst.count-1  
'Verify the title of the browser and close the browser if it does not the title passed
'in the function
  If InStr(oBrowserLst(i).GetROProperty("title"), browsertitle) = 0 Then
    oBrowserLst(i).close  
  End If  
Next 
Set oBrowser = nothing
Set oBrowser = nothing
End Function


Similarly we can tweak the above code to close only a particular browser as shown below:


Function CloseOpenbrowserWithTitle(browsertitle)
Set oBrowser = Description.Create
oBrowser("micclass").Value = "Browser"
''Get all browsers open 
Set oBrowserLst= Desktop.ChildObjects(oBrowser)
For i=0 to oBrowserLst.count-1  
'Verify the title of the browser and close the browser if it does not the title passed
'in the function
  If InStr(oBrowserLst(i).GetROProperty("title"), browsertitle) <> 0 Then
    oBrowserLst(i).close  
  End If  
Next 
Set oBrowser = nothing
Set oBrowser = nothing
End Function


Similarly we can close all browsers by removing the condition to check for title in the above code.


Function CloseAllOpenbrowsers()
Set oBrowser = Description.Create
oBrowser("micclass").Value = "Browser"
''Get all browsers open 
Set oBrowserLst= Desktop.ChildObjects(oBrowser)
For i=0 to oBrowserLst.count-1  
'Verify the title of the browser and close the browser if it does not the title passed
'in the function
      oBrowserLst(i).close  
Next 
Set oBrowser = nothing
Set oBrowser = nothing
End Function

Solution - ActiveX component can't create object: 'TDApiOle80.TDConnection'

We can connect to ALM using 'TDApiOle80.TDConnection' object in VBscript as shown below:



Function CreateALMConnection(uRLALM,strUserName,strPassword,strDomain, strProject)
 Set objALMConnection = CreateObject("TDApiOle80.TDConnection")
        objQCConnection.InitConnectionEx uRLALM
        objQCConnection.Login strUserName, strPassword
        objQCConnection.Connect strDomain, strProject
  
  ''/* Write the required code for transaction with 
               '' ALM once the connection is created
   
  objQCConnection.Disconnect            
        objQCConnection.Logout
        objQCConnection.ReleaseConnection
        Set objQCConnection = Nothing
End Function 

Some of the useful code for interacting with ALM from VBScript can be found at below location:


Copying files from ALM to local machine


While running the script in 64 bit machine, error message 'ActiveX component can't create object: 'TDApiOle80.TDConnection' is displayed. In case you encounter such error, you can run the script from SysWow64 location in Windows as : 


C:\Windows\SysWOW64\cscript.exe scriptfilewithPath.vbs


From cscript.exe, the script will run successfully