Wednesday, December 23, 2009

QTP Functions

Function to launch the application
-----------------------------------
Function Launch
SystemUtil.CloseProcessByName "Iexplore.exe"
SystemUtil.Run "Iexplore.exe","https://www. Google.com"
End Function
------------------------------------------------------------
'@Function created for fetch the data from Excel Sheet
Function f_GetExcelData(byVal strSheetName,byVal strFile,byRef ObjADORecordSet)
f_GetExcelData=False
'@Open the Database connection
Set gObjConnection = CreateObject("ADODB.Connection")
'@Connection string
gCnstExcelConnString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source="""& strFile &""";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"""
gObjConnection.Open gCnstExcelConnString
strQuery = "SELECT * FROM [" & strSheetName & "$]"
'@Open the record set
Set ObjADORecordSet = CreateObject("ADODB.Recordset")
ObjADORecordSet.Open strQuery, gObjConnection
If Not ObjADORecordSet.EOF Then
ObjADORecordSet.MoveFirst
End If
f_GetExcelData=True
End Function
--------------------------------------------------------
fnGetDriveLetter
' ---------------
' This function returns drive letter on which the test is stored
'******************************************************************************************
Function fnGetDriveLetter()
Dim fso
On error resume next
Set fso = CreateObject("Scripting.FileSystemObject")
fnGetDriveLetter = fso.GetDriveName(Envrionment("TestDir"))
End Function

'******************************************************************************************
'fnCloseAllBrowsers()
' ---------------
' This function closes all open browser instances
'******************************************************************************************
Function fnCloseAllBrowsers()

On error resume next

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colProcessList = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = 'iexplore.exe'")

For Each objProcess in colProcessList
objProcess.Terminate()
Next
End Function


'******************************************************************************************
'fnCloseProcess(strProcessName)
' ---------------
' This function closes all running instances for given process name
' strProcessName - Name of the Process
'******************************************************************************************
Function fnCloseProcess(strProcessName)
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = '" & strProcessName & "'")
For Each objProcess in colProcessList
objProcess.Terminate()
Next
End Function



'******************************************************************************************
'fnDB_connect
' ---------------
' The function creates a new connection session to a database.
' curSession - the session name (string)
' connection_string - a connection string
' for example the connection_string can be "DRIVER={Microsoft ODBC for Oracle};UID=matrix;PWD=matrix1;SERVER=tst10mwp;"
'******************************************************************************************
Function fnDB_connect( byRef curSession ,connection_string)
dim connection
on error Resume next
' Opening connection
set connection = CreateObject("ADODB.Connection")
If Err.Number <> 0 then
fnDB_connect = "Error # " & CStr(Err.Number) & " " & Err.Description
err.clear
Exit Function
End If
connection.Open connection_string
If Err.Number <> 0 then
fnDB_connect = "Error # " & CStr(Err.Number) & " " & Err.Description
err.clear
Exit Function
End If
set curSession=connection
fnDB_connect=0
End Function

'********************************************************************************************
' db_disconnect
' ---------------------
' The function disconnects from the database and deletes the session.
' curSession - the session name (string)
'********************************************************************************************

Function fnDB_disconnect( byRef curSession )
curSession.close
set curSession = Nothing
End Function
''************************************************************************************************
' db_get_rows_count_SQL
' ------------------------------------
' The function returns the number of rows that are the result of a given SQL statement
' curSession - the session name (string)
' CountSQL - SQL statement
''******************************************************************************************
Function fnDB_get_rows_count_SQL( byRef curSession ,SQLQuery )
Dim cur_rs, rsVal
set cur_rs = curSession.Execute(SQLQuery)
rsVal = cur_rs.fields(0).value
fnDB_get_rows_count_SQL = rsVal
End Function
''################################################################################
''FUNCTION NAME : functionReadFromExcelSheet
''DESCRIPTION : Used to retreive a value from an excel sheet
''PARAMETERS : Location of the Excel sheet, Name of the sheet (Sheet number), Row Number, Column Number

''################################################################################
function fnReadFromExcelSheet(location, sheetno, row, col)
Dim indicator
'Binding into Excel object.
On Error Resume Next
Set ob= CreateObject("Excel.Application") ' Create the Excel Object
If Err.Number <> 0 Then
Exit Function
End If
' Binding into Excel object.
On Error Resume Next
ob.WorkBooks.Open location ' opens the excel sheet
If Err.Number <> 0 Then
Exit Function
End If
On Error Resume Next
Set sheet= ob.ActiveWorkbook.Worksheets(sheetno) 'sets the sheet
If Err.Number <> 0 Then
Exit Function
End If
Dim cellData
cellData = sheet.Cells(row, col).Value ' capturing the required value in a variable
ob.ActiveWorkbook.Close ' close the work book
ob.Application.Quit ' quits Excel
fnReadFromExcelSheet = cellData ' the function returns the value here

end Function
'#######################################################################################
'### FUNCTION NAME : fnOpenExcelSheet
'###
'### DESCRIPTION : Opens the Excel File
'###
'### PARAMETERS : Location of the Excel File
'###
'####################################################################################

Function fnOpenExcelSheet(strFilePath)

Dim strExcelPath, objExcel
Dim intRows
On Error Resume Next
' Create Excel Application Object
Set objExcel = CreateObject("Excel.Application")
' Err Handling for Excel Application Object Creation
If Err.Number <> 0 Then
On Error GoTo 0
WScript.Echo "Excel Application not found."
WScript.Quit
End If
objExcel.Visible = True
On Error Resume Next
' Open Excel Sheet in Application Object
objExcel.WorkBooks.Open strFilePath
' Err Handling for Opening Excel Sheet in Application Object
If Err.Number <> 0 Then
On Error GoTo 0
WScript.Echo "Error Opening File : " & strFilePath
WScript.Quit
End If

End Function

'******************************************************************************************
' fnGetFTPFile
' ---------------
' This function retrieves the specified file from remote FTP server
' This function use FTP commands to retrieve the file
' Arguments
' strFtpURL - URL of the FTP Server
' strUserName - User Name to logon to FTP server
' strPassword - Login Password
' strRemoteDirPath - Directory Path on FTP server where file is located
' strFileName - File Name
' strLocalDirPath - Local Directory Path where retrived file be saved
'
'******************************************************************************************
Function fnGetFTPFile(strFtpURL, strUserName, strPassword, strRemoteDirPath , strFileName, strLocalDirPath)

On Error Resume Next
Dim objShell, objFSO, objBatFile
'Create Shell object to execute batch file
Set objShell = CreateObject("Wscript.Shell")
'Create File System Object to Create a batch file
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Create a batch file
Set objBatFile = objFSO.CreateTextFile("c:\ftpdwnld.bat", True)
'Add FTP commands to batch file
objBatFile.WriteLine("open " & strFTPURL )
objBatFile.WriteLine(strUserName)
objBatFile.WriteLine(strPassword)
objBatFile.WriteLine("cd " & strRemoteDirPath)
objBatFile.WriteLine("get " & strFileName)
objBatFile.WriteLine("close")
objBatFile.WriteLine("quit")
objBatFile.Close
' Fire batch file on shell object
objShell.Run "cmd /k cd " & strLocalDirPath & " & ftp -s:c:\ftpdwnld.bat",0 'Remove last argument if you want see actual process

Set objShell = Nothing
Set objFSO = Nothing
End Function


'******************************************************************************************
' fnQueryExcelData
' ---------------
' This function retrieves SELECT query results from Excel Workbook and returns the results
' in a two dimensional array
' Arguments
' strFilePath - File Path of Excel WorkBook
' strSQL - Select Query
' Note - While Specifying select query give sheet name from where you want to retrieve data
' Give sheet name as [Sheet1$] or [ar_journal_details$]
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' Results = fnQueryExcelData("C:\Automation\Project\MWP\PMC\TestData\ar_journal_details.xls","select * from [Sheet1$] where Description='Ind Serv # 318'")
'
' For intCnt = 0 To Ubound(Results) - 1
' MsgBox "Description " & Results(intCnt,0) & VbCrLf & _
' "Account " & Results(intCnt,1) & VbCrLf & _
' "PO Number " & Results(intCnt,6)
' Next
'******************************************************************************************

Function fnQueryExcelData(strFilePath, strSQL,ByRef objRecordset)
Dim objConn, objRs, arrResultSet(), RowCount, FieldCount, Row, Col
'On Error Resume Next
Set objCon = CreateObject("ADODB.Connection")
Set objRs = CreateObject("ADODB.Recordset")
'Open Connection Object
'Note - If you are using Excel 2000 then ExtendedProperties Value will be Excel8.0;HDR=Yes
' If you are using Excel XP then ExtendedProperties Value will be Excel9.0;HDR=Yes
' If you are using Excel 2003 then ExtendedProperties Value will be Excel10.0;HDR=Yes
objCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source="& strFilePath & ";" & _
"Extended Properties=""Excel 8.0;HDR=Yes"""
objRs.Open strSQL, objCon
Set objRecordset = objRs
Set objCon = Nothing
Set objRs = Nothing
End Function


'#######################################################################################
'### FUNCTION NAME : fnWriteToExcelSheet
'###
'### DESCRIPTION : Writes the Result to an excel sheet
'###
'### PARAMETERS : Location of the excel sheet, The Sheet name, Data to be written, row no, column no
'###
'####################################################################################


Function fnWriteToExcelSheet(location,sheetno,data,row,col)

Dim strExcelPath, objSheet, intRow, objExcel
Dim strName1, strName2, strName3, strName4, strName5, objUser

' Binding into Excel object.
On Error Resume Next
Set objExcel = CreateObject("Excel.Application")
If Err.Number <> 0 Then
On Error GoTo 0
Wscript.Echo "Excel application not found."
Wscript.Quit
End If
On Error GoTo 0

' Spreadsheet file location
strExcelPath = location

' Opening a specified spreadsheet and select the first worksheet.

On Error Resume Next
objExcel.WorkBooks.Open strExcelPath

If Err.Number <> 0 Then
On Error GoTo 0
Wscript.Echo "Excel opened already.."
Wscript.Quit
End If
On Error GoTo 0
set objSheet = objExcel.ActiveWorkbook.Worksheets(sheetno)
'' On Error Resume Next
' If Err.Number <> 0 Then
' On Error GoTo 0
' Wscript.Echo "Excel application not found."
' Wscript.Quit
'End If
'On Error GoTo 0

objSheet.Cells(row,col).Value=data





' Close workbook and quit Excel.
objExcel.ActiveWorkbook.save
objExcel.ActiveWorkbook.Close
objExcel.Application.Quit

' Clean up.
Set objExcel = Nothing
Set objSheet = Nothing
Set objUser = Nothing
Set strExcelPath = Nothing
End Function



''################################################################################
''FUNCTION NAME : functionReadFromExcelSheetForRange
''DESCRIPTION : Used to retreive a value from an excel sheet
''PARAMETERS : Location of the Excel sheet, Name of the sheet (Sheet number), starting Row, Ending Row, Starting Column Number, Ending Column Number
''################################################################################
function fnReadFromExcelSheetForRange(location, sheetno, row_start, row_end,col_start,col_end)
Dim indicator
'Binding into Excel object.
On Error Resume Next
Set ob= CreateObject("Excel.Application") ' Create the Excel Object
If Err.Number <> 0 Then
Exit Function
End If
' Binding into Excel object.
On Error Resume Next
ob.WorkBooks.Open location ' opens the excel sheet
If Err.Number <> 0 Then
Exit Function
End If
On Error Resume Next
Set sheet= ob.ActiveWorkbook.Worksheets(sheetno) 'sets the sheet
If Err.Number <> 0 Then
Exit Function
End If
'Dim cellData
'cellData = sheet.Cells(row, col).Value ' capturing the required value in a variable
For i = row_start to row_end
For j = col_start To col_end
fnReadFromExcelSheetForRange = fnReadFromExcelSheetForRange & trim(sheet.Cells(i, j).Value) ' the function returns the value here
Next
Next

ob.ActiveWorkbook.Close ' close the work book
ob.Application.Quit ' quits Excel
end Function




'******************************************************************************************
' subMyClick
' ----------
' This sub procedure cliks the link in the MWP application's main page
' Arguments
' obj: the page object being passed
' Element1: Links which need to be clicked
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' Browser("Matrix10 Applications").Page("Matrix10 Applications").subMyClick("My Desk,Projects,Projects")
' OR
' set obj = Browser("Matrix10 Applications").Page("Matrix10 Applications")
' Call subMyClick("My Desk,Projects,Projects")
'******************************************************************************************

Sub subMyClick(obj,Element1)
If InStr(Element1,",") <> 0 Then
Element = Split(Element1,",")
For i = 0 To Ubound(Element)
If i = 0 Then
If trim(Element(i)) <> "" Then
obj.WebElement("innertext:=" & trim(Element(i)),"Index:=0").Click(1)
End If
ElseIf i = UBound(Element) Then
If trim(Element(i)) <> "" Then
Page("index:=0").WebElement("class:=menu-item","innertext:="& trim(Element(i))).Click(1)
End If
Else
If trim(Element(i)) <> "" Then
Page("index:=0").WebElement("class:=menu-label","innertext:="& trim(Element(i))).Click(1)
End If
End If
wait(1)
Next
Else
obj.WebElement("innertext:="& Element1,"Index:=0").Click
End If

End Sub

RegisterUserFunc "Page", "subMyClick", "subMyClick"


'#######################################################################################
'### FUNCTION NAME : MaximizeBrowser
'###
'### DESCRIPTION : It maximizes the IE Browser
'###
'### PARAMETERS : Browser name
'###
'####################################################################################

' Register the Maximize function on the browser object
RegisterUserFunc "Browser", "Maximize", "MaximizeBrowser"

' This function takes a browser object
' and maximizes it
Sub MaximizeBrowser( ByRef Browser )
' Variable to hold the window handle
Dim s_handle

' Retrieve the window handle of the given browser
s_handle= Browser.GetROProperty("hWnd")

' Use that handle to reference a window object,
' then maxamize that object
Window("hWnd:="&s_handle).Maximize
End Sub


'#######################################################################################
'### FUNCTION NAME : fnClearExcelSheetValues
'###
'### DESCRIPTION : Clears results and remarks for excel sheet
'###
'### PARAMETERS : Location of the excel sheet, The Sheet name, starting row no, end row no, columne no
'###
'####################################################################################

Function fnClearExcelSheetValues(strFilePath,strSheetName,valStartRow,valEndRow,intCol)

Dim strExcelPath, objSheet, intRow, objExcel
Dim intRows
On Error Resume Next
' Create Excel Application Object
Set objExcel = CreateObject("Excel.Application")
' Err Handling for Excel Application Object Creation
If Err.Number <> 0 Then
On Error GoTo 0
WScript.Echo "Excel Application not found."
WScript.Quit
End If
On Error Resume Next
' Open Excel Sheet in Application Object
objExcel.WorkBooks.Open strFilePath
' Err Handling for Opening Excel Sheet in Application Object
If Err.Number <> 0 Then
On Error GoTo 0
WScript.Echo "Error Opening File : " & strFilePath
WScript.Quit
End If
' Clear Results/ Remarks from Given Rows and Cell
For intRow = valStartRow To valEndRow
objExcel.WorkSheets(strSheetName).Cells(intRow,intCol)= vbNullString
Next

' Close workbook and quit Excel.
objExcel.ActiveWorkbook.Save
objExcel.Application.Quit

' Clean up.
Set objExcel = Nothing
End Function



'******************************************************************************************
' fnCheckText
' -----------
' This function checks if the specified text is present in the specified column of the webtable
' Arguments
' obj: the table object to get the text from
' ColHeader: Name of the Column
' text: the text to be searched in the table
' This function returns a boolean value i.e. a True or a False value
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' a = Browser("Matrix10 Applications").Page("Matrix10 Applications").Frame("listDisplay").WebTable("Type").fnCheckText("Number", "A0411116")
' OR
' set table = Browser("Matrix10 Applications").Page("Matrix10 Applications").Frame("listDisplay").WebTable("Type")
' a = fnCheckText(table, "Number", "A0411116")
'******************************************************************************************

Function fnCheckText(obj, colHeader, text)

fnCheckText = False
stat = "fail"
If obj.Exist Then
For iRow = 1 to obj.rowcount()
For iCol = 1 to obj.ColumnCount(iRow)
strCellValue = trim(obj.GetCellData(iRow, iCol))
If strCellValue = trim(colHeader) Then
stat = "pass"
Exit For
End If
Next
If stat = "pass" Then
Exit For
End If
Next

If stat = "pass" Then
For iRow1 = (iRow + 1) to obj.rowcount()
strCellValue = trim(obj.GetCellData(iRow1, iCol))
If strCellValue = trim(text) Then
fnCheckText = True
Exit Function
End If
Next
End If
End If

End Function

RegisterUserFunc "WebTable", "fnCheckText", "fnCheckText"



'******************************************************************************************
' fnGetObject
' -----------
' This function retrieves an object from a target column if the specified text is present in
' the source column of the webtable. This function returns an object which can be manipulated to the users needs
' Arguments
' obj: the table object to get the text from
' sourceColHeader: Name of the Source Column
' text: the text to be searched in the table
' targetColHeader: Name of the target Column
' className: The object's class (className property) as returned by the Object Spy of QTP.
' index: set to 0 unless more than one objects of the same type are present in the same cell. In that case use index to
' select the appropriate object.
'
'
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' set lnk = Browser("Matrix10 Applications").Page("Matrix10 Applications").Frame("listDisplay").WebTable("Type").fnGetObject("Number", "R0411116", "Number", "Link", 0)
' lnk.Click
' OR
' set webChkBox = Browser("Matrix10 Applications_2").Page("Matrix10 Applications").Frame("pagecontent").WebTable("Name").fnGetObject("Name", "T00008295 ", "", "WebCheckBox", 0)
' webChkBox.Set "ON"
' OR
' set table = Browser("Matrix10 Applications").Page("Matrix10 Applications").Frame("listDisplay").WebTable("Type")
' set lnk = fnGetObject(table,"Number", "R0411116", "Number", "Link", 0)
' lnk.Click
'******************************************************************************************

Function fnGetObject(obj, sourceColHeader, text, targetColHeader, className, index)

stat = "fail"
If obj.Exist Then
For iRow = 1 to obj.rowcount()
For iColSource = 1 to obj.ColumnCount(iRow)
strCellValue = trim(obj.GetCellData(iRow, iColSource))
If strCellValue = trim(sourceColHeader) Then
stat = "pass"
Exit For
End If
Next
If stat = "pass" Then
Exit For
End If
Next

If stat = "pass" Then
For iColTarget = 1 to obj.ColumnCount(iRow)
strCellValue = trim(obj.GetCellData(iRow, iColTarget))
If strCellValue = trim(targetColHeader) Then
stat = "pass"
Exit For
Else
stat = "fail"
End If
Next
End If

For iRow1 = (iRow + 1) to obj.rowcount()
strCellValue = trim(obj.getcelldata(iRow1, iColSource))
If strCellValue = trim(text) and stat = "pass" Then
set object = obj.ChildItem(iRow1, iColTarget, className, index)
set fnGetObject = object
Exit Function
End If
Next
End If

If fnGetObject = "" Then
WScript.Echo "No objects were found with the required properties"
WScript.Quit
End If

End Function

RegisterUserFunc "WebTable", "fnGetObject", "fnGetObject"


'******************************************************************************************
' fnCheckActionItemsDisabled
' --------------------------
' This function checks if the specified WebElements in the Action toolbar menu are disabled or not.
' This function returns a boolean value.
' Arguments
' obj: the Frame object which contains the action toolbar
' strElement: Name of the toolbar which needs to be clicked to access the menu eg. Actions.
' strDisabled: WebElement whose disabled property needs to be validated. Pass the name of the WebElement.
' If More than one WebElement's properties needs to be validated then pass the arguments in the form of an array.
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' If Browser("Matrix10 Applications").Page("Matrix10 Applications").Frame("listHead").fnCheckActionItemsDisabled ("Actions",Array("Delete")) Then
' status = "pass"
' End If
' OR
' If Browser("Matrix10 Applications").Page("Matrix10 Applications").Frame("listHead").fnCheckActionItemsDisabled ("Actions","Delete") Then
' status = "pass"
' End If
'******************************************************************************************

Function fnCheckActionItemsDisabled (obj, strElement, strDisabled)
on error Resume next

If Err.Number <> 0 then
Exit Function
End If
subActionToolBarClick obj,strElement
fnCheckActionItemsDisabled = fnCheckMenuItems (Array(), strDisabled, Array())

End Function

RegisterUserFunc "Frame", "fnCheckActionItemsDisabled", "fnCheckActionItemsDisabled"


'******************************************************************************************
' fnCheckActionItemsEnabled
' -------------------------
' This function checks if the specified WebElements in the Action toolbar menu are Enabled or not.
' This function returns a boolean value.
' Arguments
' obj: the Frame object which contains the action toolbar
' strElement: Name of the toolbar which needs to be clicked to access the menu eg. Actions.
' strEnabled: WebElement whose Enabled property needs to be validated. Pass the name of the WebElement.
' If More than one WebElement's properties needs to be validated then pass the arguments in the form of an array.
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' If Browser("Matrix10 Applications").Page("Matrix10 Applications").Frame("listHead").fnCheckActionItemsEnabled ("Actions",Array("Create New...")) Then
' status = "pass"
' End If
' OR
' If Browser("Matrix10 Applications").Page("Matrix10 Applications").Frame("listHead").fnCheckActionItemsEnabled ("Actions","Create New...") Then
' status = "pass"
' End If
'******************************************************************************************

Function fnCheckActionItemsEnabled (obj, strElement, strEnabled)
on error Resume next

If Err.Number <> 0 then
Exit Function
End If
subActionToolBarClick obj,strElement
fnCheckActionItemsEnabled = fnCheckMenuItems (strEnabled,Array(), Array())

End Function

RegisterUserFunc "Frame", "fnCheckActionItemsEnabled", "fnCheckActionItemsEnabled"

'******************************************************************************************
' subActionToolBarClick
' ---------------------
' This sub procedure takes the action toolbar and the individual menu items to be clicked as inputs and clicks them.
' Arguments
' obj: the Frame object which contains the action toolbar
' strElement: Name of the toolbar which needs to be clicked to access the menu and the WebElement which needs
' to be clicked eg. "Actions","Create New...".
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' Browser("Matrix10 Applications").Page("Matrix10 Applications").subActionToolBarClick "My Desk,Projects,Programs"
' Browser("Matrix10 Applications").Page("Matrix10 Applications").Frame("listHead").subActionToolBarClick "Actions,Create New..."
'******************************************************************************************

Sub subActionToolBarClick(obj,strElement)
on error Resume next

If Err.Number <> 0 then
Exit Sub
End If
arrElement = Split(strElement,",")

For iCnt = 0 To Ubound(arrElement)
strIndElement = trim(arrElement(iCnt))
If iCnt = 0 Then
If trim(strIndElement) <> "" Then
obj.WebElement("class:=text-button.*","innertext:="& strIndElement).Click
End If
Else
If trim(strIndElement) <> "" Then
Page("index:=0").WebElement("class:=menu-label","innertext:="& strIndElement).Click
End If
End If
Next

End Sub

RegisterUserFunc "Page", "subActionToolBarClick", "subActionToolBarClick"
RegisterUserFunc "Frame", "subActionToolBarClick", "subActionToolBarClick"


'******************************************************************************************
' fnCheckMenuItems
' ----------------
' This function checks if the specified WebElements in the Action toolbar menu are Enabled, Disabled
' or do they have sub menu's.
' This function returns a boolean value.
' Arguments
' strEnabled: WebElement whose Enabled property needs to be validated. Pass the name of the WebElement.
' strDisabled: WebElement whose Disabled property needs to be validated. Pass the name of the WebElement.
' strElement: Name of the sub menu Items which need to be validated i.e. items which have sub menus eg. Programs or Products.
' If More than one WebElement's properties needs to be validated then pass the arguments in the form of an array.
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' Browser("Matrix10 Applications_2").Page("Search: Saved Searches").Frame("searchHead").WebElement("utilMenuArrow").Click
' If fnCheckMenuItems("Saved Searches", Array(),Array("Program","Products","Labs")) Then
' status = "pass"
' End If
'******************************************************************************************

Function fnCheckMenuItems(strEnabled, strDisabled, strElement)

If Not IsArray(strEnabled) Then
strEnabled = Array(strEnabled)
End If

If Not IsArray(strDisabled) Then
strDisabled = Array(strDisabled)
End If

If Not IsArray(strElement) Then
strElement = Array(strElement)
End If
For Each strIndividualItem in strEnabled
If Page("index:=0").WebElement("class:=menu-item","innertext:="& strIndividualItem).Exist(0) Then
fnCheckMenuItems = True
Else
fnCheckMenuItems = False
Exit Function
End If
Next
For Each strIndividualItem in strDisabled
If Page("index:=0").WebElement("class:=menu-item-disabled","innertext:="& strIndividualItem).Exist(0) Then
fnCheckMenuItems = True
Else
fnCheckMenuItems = False
Exit Function
End If
Next

For Each strIndividualItem in strElement
If Page("index:=0").WebElement("class:=menu-item submenu","innertext:="& strIndividualItem).Exist(0) Then
fnCheckMenuItems = True
Else
fnCheckMenuItems = False
Exit Function
End If
Next

End Function



'******************************************************************************************
' fnSelectChangeOwner
' -------------------
' This function takes the tree structure i.e. Product family's Tree, Product Owner description as
' present in the application and the product owner's user ID as inputs and selects the appropriate Product Owner
' This function returns a boolean value.
' Arguments
' strProductFamily: The tree structure of the Product family to be selected e.g. "Test Family,Test Type,Test Sub Type".
' strProductOwner: Product Owner who is to be selected as present in the application e.g. Change Owner - IndSys TestUser030.
' strChangeOwnerUserId: User Id of the product owner e.g. 920800030.
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' Msgbox Browser("MatrixOne").Page("MatrixOne").Frame("pagecontent").fnSelectChangeOwner ("Test Family,Test Type,Test Sub Type","Change Owner - IndSys TestUser030","920800030")
' OR
' If Browser("MatrixOne").Page("MatrixOne").Frame("pagecontent").fnSelectChangeOwner ("Test Family,Test Type,Test Sub Type","Change Owner - IndSys TestUser030","920800030") Then
' status = "pass"
' End If
'******************************************************************************************

Function fnSelectChangeOwner (obj,strProductFamily,strProductOwner,strChangeOwnerUserId)

arrProductFamily = Split(strProductFamily, ",")
stat = ""
For iCnt = LBound(arrProductFamily) To UBound(arrProductFamily)
set objTab = obj.Object.all.Tags("TABLE")
If iCnt = 0 Then
iCnt1 = 0
For Each Element in objTab
If trim(Element.getAttribute("innertext")) = trim(arrProductFamily(iCnt)) Then
obj.WebTable("index:="&iCnt1).ChildItem(1,1,"Image",0).Click
stat = "pass"
wait(10)
Exit For
End If
iCnt1 = iCnt1 + 1
Next
Else
If stat = "pass" Then
set objTab = obj.Object.all.Tags("TABLE")
stat = ""
iCnt1 = 0
For Each Element in objTab

If trim(Element.getAttribute("innertext")) = trim(arrProductFamily(iCnt)) Then
For iCnt2 = 0 To obj.WebTable("index:="&iCnt1).ChildItemCount(1,1,"Image") - 1
If trim(obj.WebTable("index:="&iCnt1).ChildItem(1,1,"Image",iCnt2).GetRoProperty("file name")) = "utilTreeLineLastClosed.gif" or _
trim(obj.WebTable("index:="&iCnt1).ChildItem(1,1,"Image",iCnt2).GetRoProperty("file name")) = "utilTreeLineNodeClosed.gif" Then 'Open the Node
obj.WebTable("index:="&iCnt1).ChildItem(1,1,"Image",iCnt2).Click
stat = "pass"
wait(10)
Exit For
Else
stat = ""
End If
Next
End If
If stat = "pass" Then
Exit For
End If
iCnt1 = iCnt1 + 1
Next
End If
End If
Next
If stat = "pass" Then
set objTab = obj.Object.all.Tags("TABLE")
stat = ""
iCnt1 = 0
For Each Element in objTab
If trim(obj.WebTable("index:="&iCnt1).GetRoProperty("visible")) = "True" Then
If trim(Element.getAttribute("innertext")) = trim(strProductOwner) Then
Set objRadio = obj.WebTable("index:="&iCnt1).ChildItem(1,1,"WebRadioGroup",0)
For iCnt2 = 0 To iCnt1
objRadio.Select "#"& iCnt2
If InStr(objRadio.GetRoProperty("html id"),trim(strChangeOwnerUserId)) <> 0 Then
stat = "pass"
Exit For
End If
Next
End If
End If
If stat = "pass" Then
Exit For
End If

iCnt1 = iCnt1 + 1
Next
End If

If stat = "pass" Then
fnSelectChangeOwner = True
Else
fnSelectChangeOwner = False
End If

End Function

RegisterUserFunc "Frame", "fnSelectChangeOwner", "fnSelectChangeOwner"


'******************************************************************************************
' fnCheckHighlighted
' ------------------
' This function takes the text as input and checks it it is highlighted ot not
' This function returns a boolean value.
' Arguments
' strElement: The text which needs to be verified e.g. "Dashboards".
' strColorCode: The Background color e.g. "#bbd0e5".
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' Msgbox Browser("Matrix10 Applications").Page("Matrix10 Applications").Frame("treeDisplay").WebTable("TestSayDo").fnCheckHighlighted("Dashboards","#bbd0e5")
' OR
' If Browser("Matrix10 Applications").Page("Matrix10 Applications").Frame("treeDisplay").WebTable("TestSayDo").fnCheckHighlighted("Dashboards","#bbd0e5") Then
' status = "pass"
' End If
'******************************************************************************************

Function fnCheckHighlighted (obj, strElement, strColorCode)
fnCheckHighlighted = False
iRow_Count = obj.RowCount
For iCnt = 1 To iRow_Count - 1
For iCnt1 = 0 to obj.ColumnCount(iCnt) - 1
If trim(obj.Object.Rows(iCnt).Cells(iCnt1).innertext) = trim(strElement) Then
If trim(obj.Object.Rows(iCnt).Cells(iCnt1).CurrentStyle.BackgroundColor) = strColorCode Then
fnCheckHighlighted = True
Exit Function
End If
End If
Next
Next
End Function

RegisterUserFunc "WebTable", "fnCheckHighlighted", "fnCheckHighlighted"






'******************************************************************************************
' subCreateFile
' -------------
' This function creates a text file which has the lowest value file name in the root folder
' (or Drive) of the QTP script.
' Arguments
' This sub does not need any arguments
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' subCreateFile
'******************************************************************************************

Sub subCreateFile()

folde = Left(trim(Environment("TestDir")),3)
set fso = CreateObject("Scripting.fileSystemObject")
set fold = fso.getFolder(folde)
fileCount = fold.files.count
redim fNames(fileCount)
cFcount = 0
for each file in fold.files
cFcount = cFcount + 1
fNames(cFcount) = lcase(file.name)
next
for tName = 1 to fileCount
for nName = (tName + 1) to fileCount
if strComp(fNames(tName),fNames(nName),0)=1 then
buffer = fNames(nName)
fNames(nName) = fNames(tName)
fNames(tName) = buffer
end if
next
next
flag = "true"
For i = 1 to fileCount
If flag = "true" and fNames(i) <> "" Then
a = fNames(i)
flag = "false"
Exit For
End If
next
If trim(a) = "" Then
a = "aaa.txt"
End If
If InStr(a,".") <> 0 Then
b = "_" & Split(a,".")(0) & ".txt"
Else
b = "_" & a & ".txt"
End If
set fso = CreateObject("Scripting.FileSystemObject")
set myFile = fso.CreateTextFile(folde & b, True)
myFile.WriteLine "This is a test file."
myFile.Close
set fso = Nothing
set fold = Nothing
erase fNames

End Sub



'******************************************************************************************
' fnCheckInFile
' -------------
' This function checks in a file which has the lowest value file name, present in the root
' drive of the QTP script folder. This function returns a boolean value.
' Arguments
' obj: the Java Applet which checks in the file
' This function returns a boolean value i.e. a True or a False value
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' a = Browser("Browser").Page("Matrix10 Applications_3").Frame("pagecontent").JavaApplet("InterfaceApplet").fnCheckInFile()
' OR
' set javaApplet = Browser("Browser").Page("Matrix10 Applications_3").Frame("pagecontent").JavaApplet("InterfaceApplet")
' a = fnCheckInFile(javaApplet)
'******************************************************************************************

Function fnCheckInFile (obj)
fnCheckInFile = False
'##################### Create a collection of Java Objects ##############
obj.JavaDialog("index:=0").JavaList("attached text:=Look In :").Select Left(trim(Environment("TestDir")),3)
wait(10)
Set oJavaObj = Description.Create
oJavaObj("toolkit class").Value = "ge.indsys.applet.DrawCan"
set arrJavaObj = obj.JavaDialog("index:=0").ChildObjects(oJavaObj)
'Find out the size of the array needed to store the Java Objects
rows = 0
cols = 0
temp = 0
For i = 0 To arrJavaObj.Count - 1
x = arrJavaObj(i).GetROProperty("x")
y = arrJavaObj(i).GetROProperty("y")
If y = 0 Then
temp = y
End If
If y = 0 Then
cols = cols + 1
End If
If y <> temp Then
rows = rows + 1
temp = y
End If
Next
Redim arr_canvas(rows,cols - 1)
'Fill the array with the Java Objects
rows = 0
cols = 0
y_prev = ""
x_prev = ""
For i = 0 To arrJavaObj.Count - 1
x = arrJavaObj(i).GetROProperty("x")
y = arrJavaObj(i).GetROProperty("y")
If y <> y_prev Then
y_prev = y
rows = rows + 1
cols = 0
End If
If x <> x_prev Then
x_prev = x
cols = cols + 1
End If
Set arr_canvas(rows - 1,cols - 1) = arrJavaObj(i)
Next
'Click all the elements in the array one by one and exit when the select button is enabled
flag = "false"
For y_col = 0 To cols - 1
For x_row = 0 To rows -1
arr_canvas(x_row,y_col).Click 0,0,"LEFT"
If obj.JavaDialog("index:=0").JavaButton("label:=Select").GetROProperty("enabled") Then
obj.JavaDialog("index:=0").JavaButton("label:=Select").Click
flag = "true"
Exit For
End If
Next
If flag = "true" Then
fnCheckInFile = True
Exit For
End If
Next
Erase arr_canvas

End Function

RegisterUserFunc "JavaApplet", "fnCheckInFile", "fnCheckInFile"



'******************************************************************************************
' fnCheckTextColNum
' -----------------
' This function checks if the specified text is present in the specified column of the webtable
' Arguments
' obj: the table object to get the text from
' ColNumber: Column Number
' text: the text to be searched in the table
' This function returns a boolean value i.e. a True or a False value
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' a = Browser("Matrix10 Applications").Page("Matrix10 Applications").Frame("listDisplay").WebTable("Type").fnCheckTextColNum(2, "A0411116")
' OR
' set table = Browser("Matrix10 Applications").Page("Matrix10 Applications").Frame("listDisplay").WebTable("Type")
' a = fnCheckTextColNum(table, 1, "A0411116")
'******************************************************************************************

Function fnCheckTextColNum(obj, ColNumber, text)

fnCheckTextColNum = Fail
stat = "fail"
If obj.Exist Then
For iRow = 2 to obj.rowcount()
strCellValue = trim(obj.GetCellData(iRow, ColNumber))
If strCellValue = trim(text) Then
fnCheckTextColNum = True
Exit Function
End If
Next
End If

End Function

RegisterUserFunc "WebTable", "fnCheckTextColNum", "fnCheckTextColNum"


'******************************************************************************************
' fnVerifyRadioProp
' -----------------
' This function checks the specified property of the individual radio button in a web radio group
' Arguments
' obj: the object to get the radio group from
' propToIdentify: Property needed to identify the individual radio button uniquely
' propToCheck: The Property which needs to be verified
' valToIdentify: The value of the Property which helps in radio button identification
' valToCheck: The value of Property which needs to be verified
' This function returns a boolean value i.e. a True or a False value
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' a = Browser("Search Popup Screen").Page("Search Popup Screen").Frame("searchBody").fnVerifyRadioProp(obj, "value","disabled","yes", True)
' OR
' set objFrame = Browser("Search Popup Screen").Page("Search Popup Screen").Frame("searchBody")
' a = fnVerifyRadioProp(objFrame, "value","disabled","yes", True)
'******************************************************************************************

Function fnVerifyRadioProp(obj, propToIdentify,propToCheck,valToIdentify,valToCheck)
fnVerifyRadioProp = False
Dim arrInputObj
Set arrInputObj = obj.Object.all.tags("INPUT")
For Each Element in arrInputObj
If Element.getAttribute("type") = "radio" Then
If Element.getAttribute(propToIdentify) = valToIdentify Then
If Element.getAttribute(propToCheck) = valToCheck Then
fnVerifyRadioProp = True
Exit For
End If
End If
End If
Next
Set arrInputObj = Nothing
End Function

RegisterUserFunc "Frame", "fnVerifyRadioProp", "fnVerifyRadioProp"
RegisterUserFunc "Page", "fnVerifyRadioProp", "fnVerifyRadioProp"


'******************************************************************************************
' fnCheckTextVerticalHeader
' -------------------------
' This function checks if the specified text is present in the specified row of the webtable where the header
' of the webtable is vertical. Eg: Change Requests Information, Test Requests Information, etc.
' Arguments
' obj: the table object to get the text from
' rowHeader: Name of the row
' text: the text to be searched in the table
' This function returns a boolean value i.e. a True or a False value
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' a = Browser("R0605874").Page("R0605874").Frame("pagecontent").WebTable("Change Requests Information").fnCheckTextVerticalHeader("Initiator","IndSys TestUser021")
' OR
' set table = Browser("R0605874").Page("R0605874").Frame("pagecontent").WebTable("Change Requests Information")
' a = fnCheckTextVerticalHeader(table, "Initiator","IndSys TestUser021")
'******************************************************************************************

Function fnCheckTextVerticalHeader(obj, rowHeader, text)

fnCheckTextVerticalHeader = False
If obj.Exist Then
For iRow = 1 to obj.rowcount()
For iCol = 1 to obj.ColumnCount(iRow)
strCellValue = trim(obj.GetCellData(iRow, iCol))
If strCellValue = trim(rowHeader) Then
If trim(obj.GetCellData(iRow, iCol + 1)) = trim(text) Then
fnCheckTextVerticalHeader = True
Exit Function
End If
End If
Next
Next
End If

End Function

RegisterUserFunc "WebTable", "fnCheckTextVerticalHeader", "fnCheckTextVerticalHeader"



'************************************************************************************************************
' fnSetDate
' ---------
' This function checks sets the specified date in the calendar.
' Arguments
' obj: the table object to get the text from
' dateAlreadySelected: The date which was already selected. Send in "" if it was not selected previously.
' days: Number of days by which you would like to move the specied date
' month: Number of months by which you would like to move the specied date
' years: Number of years by which you would like to move the specied date
' imageObj: The calendar object which needs to ble clicked
' This function returns the date which has been set
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------------------------
' newDate = Browser("MatrixOne").Page("MatrixOne").Frame("pagecontent").Image("calendar").fnSetDate(0,0,0,"")
'*************************************************************************************************************

Function fnSetDate(obj, days, months, years,dateAlreadySelected)

'Click on the calendar image
Obj.Click
wait(2)
Set obj = fnGetPageOrFrame(obj)

If dateAlreadySelected = "" Then
currentDate = Day(date)
currentYear = Year(date)
currentMonth = Month(date)
Else
currentDate = Day(dateAlreadySelected)
currentYear = Year(dateAlreadySelected)
currentMonth = Month(dateAlreadySelected)
End If
'If the date needs to be set to today's date, just click on the day to be selected
If days = 0 and months = 0 and years = 0 Then
If WeekDay(day(Date) & "/" & month(Date) & "/" & year(Date)) <> 1 Then
If obj.WebElement("innerhtml:= " & currentDate & " ").Exist(0) Then
obj.Link("innerhtml:= " & currentDate & " ").Click
Else
obj.Link("innertext:=" & currentDate).Click
End If
fnSetDate = MonthName(Month(Date), true) & " " & day(Date) & ", " & year(Date)
Exit Function
Else
obj.WebElement("innerhtml:=" & currentDate).Click
fnSetDate = MonthName(Month(Date), true) & " " & day(Date) & ", " & year(Date)
Exit Function
End If
End If
'Determine new date based on input parameters
newDate = DateAdd("yyyy", years, Date)
newDate = DateAdd("m", months, newDate)
newDate = DateAdd("d", days, newDate)

'Get new year, month and date
yearToSet = Year(newDate)
monthToSet = MonthName(Month(newDate))
dayToSet = Day(newDate)

yearsToAdd = yearToSet - currentYear

'Set the new month
obj.Image("html id:=changeMonth").Click
If monthToSet <> currentMonth Then
obj.WebElement("innerhtml:= " & monthToSet & " ").Click
Else
obj.WebElement("innerhtml:=" & monthToSet).Click
End If
'Set the year taking into account that you cannot jump more than 3 years ahead
If yearToSet <> currentYear Then
If yearsToAdd <= 3 Then
obj.Image("html id:=changeYear").Click
obj.WebElement("innerhtml:= " & yearToSet & " ").Click
Else
While yearsToAdd > 3
yearToSet = currentYear + 3
yearsToAdd = yearsToAdd - 3
obj.Image("html id:=changeYear").Click
obj.WebElement("innerhtml:= " & yearToSet & " ").Click
currentYear = yearToSet
Wend
If yearsToAdd > 0 Then
yearToSet = currentYear + yearsToAdd
obj.Image("html id:=changeYear").Click
obj.WebElement("innerhtml:= " & yearToSet & " ").Click
End If
End If
End If
'Set the day
If WeekDay(dayToSet & "/" & monthToSet & "/" & yearToSet) <> 1 Then
If obj.Link("innerhtml:= " & dayToSet & " ").Exist(0) Then
obj.Link("innerhtml:= " & dayToSet & " ").Click
Else
obj.Link("innertext:=" & dayToSet).Click
End If
Else
obj.WebElement("innerhtml:=" & dayToSet).Click
End If

'Return the new date
fnSetDate = MonthName(Month(newDate), True) & " " & day(newDate) & ", " & year(newDate)
End Function

RegisterUserFunc "Image", "fnSetDate", "fnSetDate"



'*********************************************************************************************************
' fnGetPageOrFrame
' ----------------
' This function traverses through the hierarchy of the object being passed and retrieves the parent object
' Arguments
' obj: the table object to get the text from
' This function returns the Page or Frame Object
' Example - Following is the Example Code
' --------------------------------------------------------------------------------------------
' set imageObj = Browser("MatrixOne").Page("MatrixOne").Frame("pagecontent").Image("calendar")
' Set objFrame = fnGetPageOrFrame(imageObj)
'**********************************************************************************************************

Function fnGetPageOrFrame(ByVal obj)
micClass = obj.GetROProperty("micclass")
While micClass <> "Page" and micClass <> "Frame" and micClass <> ""
Set obj = obj.GetTOProperty("parent")
micClass = obj.GetROProperty("micclass")
Wend
Set fnGetPageOrFrame = obj
End Function



'*********************************************************************************************************
' fnGetBrowser
' ------------
' This function traverses through the hierarchy of the object being passed and retrieves the Browser object
' Arguments
' obj: the table object to get the text from
' This function returns the Page or Frame Object
' Example - Following is the Example Code
' --------------------------------------------------------------------------------------------
' set imageObj = Browser("MatrixOne").Page("MatrixOne").Frame("pagecontent").Image("calendar")
' Set objFrame = fnGetBrowser(imageObj)
'*********************************************************************************************************

Function fnGetBrowser(ByVal obj)
micClass = obj.GetROProperty("micclass")
While micClass <> "Browser" and micClass <> ""
Set obj = obj.GetTOProperty("parent")
micClass = obj.GetROProperty("micclass")
Wend
Set fnGetBrowser = obj
End Function


'***************************************************************************************************************
' subClickAndWaitTillWindowClose
' ------------------------------
' This sub procedure clicks on the object being passed and waits till the window is closed
' Arguments
' obj: the object which needs to be clicked
' bWait: Boolean value which determines if the script needs to wait till the window is closed or not
' intTimeout: Time in seconds. The script waits for the window to be closed in the specified time.
' If the window is not closed till then, the script moves on.
' Example - Following is the Example Code
' --------------------------------------------------------------------------------------------------------------
' Browser("MatrixOne").Page("MatrixOne").Frame("pagefooter").Link("Done").subClickAndWait True,30
'****************************************************************************************************************

Sub subClickAndWaitTillWindowClose(obj,bWait,intTimeout)
obj.Click
Set obj = fnGetBrowser(obj)
If bWait = False Then
Exit Sub
End If
hwnd = obj.GetROProperty("hwnd") 'Retrieve the window handle of the given browser
For i = 0 to intTimeout
If Not Window("hwnd:=" & hwnd).Exist(0) Then
Exit Sub
End If
wait(1)
Next
End Sub

RegisterUserFunc "Image", "subClickAndWait", "subClickAndWaitTillWindowClose"
RegisterUserFunc "Link", "subClickAndWait", "subClickAndWaitTillWindowClose"


'********************************************************************************************************************************
' fnSelectByText
' --------------
' This function selects the radiobutton based on the text being passed
' Arguments
' obj: the radio group object which needs to be selected
' strText: The text adjacent to the option which needs to be selected
' Example - Following is the Example Code
' ------------------------------------------------------------------------------------------------------------------------------
' Msgbox Browser("MatrixOne_2").Page("MatrixOne").Frame("pagecontent").WebRadioGroup("selected").fnSelectByText("Refrigeration")
' OR
' set oRadioGroup = Browser("MatrixOne_2").Page("MatrixOne").Frame("pagecontent").WebRadioGroup("selected")
' a = fnSelectByText (obj, "Refrigeration")
'********************************************************************************************************************************

Function fnSelectByText (obj, strText)
fnSelectByText = False
Set objParent = obj.GetTOProperty("parent")
strRadName = obj.GetROProperty("name")
Set objRadioButtons = objParent.Object.GetElementsByName(strRadName)
iCnt = 0
For each Element in objRadioButtons
strName = Element.getAdjacentText("afterEnd")
If trim(strText) = trim(strName) Then
obj.Select "#" & iCnt
fnSelectByText = True
Exit For
End If
iCnt = iCnt + 1
Next
End Function

RegisterUserFunc "WebRadioGroup", "fnSelectByText", "fnSelectByText"


'***********************************************************************************
' subWait
' -------
' This sub procedure waits till the object is ready
' Arguments
' obj: the object which needs to be loaded completely
' Example - Following is the Example Code
' ---------------------------------------------------------------------
' Browser("MatrixOne_2").Page("MatrixOne").Frame("pagecontent").subWait
'**********************************************************************************

Sub subWait(obj)
While (Not obj.WaitProperty("attribute/readyState", "complete", 4))
wait(2)
Wend
End Sub

RegisterUserFunc "Frame", "subWait", "subWait"
RegisterUserFunc "Page", "subWait", "subWait"
RegisterUserFunc "Image", "subWait", "subWait"
RegisterUserFunc "Link", "subWait", "subWait"




'******************************************************************************************
' fnCheckTextInDifferentColumns
' -----------------------------
' This function checks the text in the target column if the specified text is present in
' the source column of the webtable. This function returns a boolean value.
' Arguments
' obj: the table object to get the text from
' sourceColHeader: Name of the Source Column
' text: the text to be searched in the source column of the table
' targetColHeader: Name of the target Column
' strTargetText: the text to be searched in the target column of the table
'
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' a = Browser("Matrix10 Applications").Page("Matrix10 Applications").Frame("listDisplay").WebTable("Type").fnCheckTextDiff("Number", "R0411116", "Name", "Test")
' OR
' set table = Browser("Matrix10 Applications").Page("Matrix10 Applications").Frame("listDisplay").WebTable("Type")
' Msgbox fnCheckTextDiff(table,"Number", "R0411116", "Name", "Test")
'******************************************************************************************
Function fnCheckTextInDifferentColumns(obj, sourceColHeader, strSourceText, targetColHeader, strTargetText)
fnCheckTextInDifferentColumns = False
stat = "fail"
If obj.Exist Then
For iRow = 1 to obj.rowcount()
For iColSource = 1 to obj.ColumnCount(iRow)
strCellValue = trim(obj.GetCellData(iRow, iColSource))
If strCellValue = trim(sourceColHeader) Then
stat = "pass"
Exit For
End If
Next
If stat = "pass" Then
Exit For
End If
Next

If stat = "pass" Then
For iColTarget = 1 to obj.ColumnCount(iRow)
strCellValue = trim(obj.GetCellData(iRow, iColTarget))
If strCellValue = trim(targetColHeader) Then
stat = "pass"
Exit For
Else
stat = "fail"
End If
Next
End If

For iRow1 = (iRow + 1) to obj.rowcount()
strCellValue = trim(obj.getcelldata(iRow1, iColSource))
If strCellValue = trim(strSourceText) and stat = "pass" Then
If trim(obj.GetCellData(iRow1, iColTarget)) = trim(strTargetText) Then
fnCheckTextInDifferentColumns = True
Exit Function
End If
End If
Next
End If

End Function

RegisterUserFunc "WebTable", "fnCheckTextDiff", "fnCheckTextInDifferentColumns"


'******************************************************************************************
' fnGetObjectVerticalHeader
' -------------------------
' This function retrieves the specified object which is present in the specified row of the webtable where the header
' of the webtable is vertical. Eg: Change Requests Information, Test Requests Information, etc.
' Arguments
' obj: the table object to get the text from
' rowHeader: Name of the row
' text: the text to be searched in the table
' className: The object's class (className property) as returned by the Object Spy of QTP.
' index: set to 0 unless more than one objects of the same type are present in the same cell. In that case use index to
' select the appropriate object.
' This function returns the object.
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' a = Browser("R0605874").Page("R0605874").Frame("pagecontent").WebTable("Change Requests Information").fnGetObjectVerticalHeader("Initiator","WebElement",0)
' OR
' set table = Browser("R0605874").Page("R0605874").Frame("pagecontent").WebTable("Change Requests Information")
' a = fnGetObjectVerticalHeader("Initiator","WebElement",0)
'******************************************************************************************
Function fnGetObjectVerticalHeader(obj, rowHeader, className, index)

fnGetObjectVerticalHeader = False
If obj.Exist Then
For iRow = 1 to obj.rowcount()
For iCol = 1 to obj.ColumnCount(iRow)
strCellValue = trim(obj.GetCellData(iRow, iCol))
If strCellValue = trim(rowHeader) Then
If obj.ChildItemCount(iRow, iCol + 1,classname) > 0 Then
set fnGetObjectVerticalHeader = obj.ChildItem(iRow, iCol + 1,classname,index)
Exit Function
End If
End If
Next
Next
End If

End Function

RegisterUserFunc "WebTable", "fnGetObjectVerticalHeader", "fnGetObjectVerticalHeader"



'******************************************************************************************
' fnCheckSheets
' -------------
' This function checks if the specified tabs are present in the excel sheet or not
' Arguments
' strFilePath: The Excel Sheet path
' oDict: Dictionary object which contains the sheet names
' This function returns a boolean value.
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' a = Array("Instructions","Capitalization Guidelines","4BLOCK","Reference","EFFORT","Backup","DCRR Model","tax rates_depr schedule","FX rates","SII_Load","SII","File1","Version")
' set oDict = fnDictBuild(a)
' strFilePath = "D:\Automation\Project\MWP\QTP_Scripts\PMC\MWP_PMC_GEL TCO 4-Block_Create SII project_TP\Master 4 Blocker with complete data.xls"
' Msgbox fnCheckSheets(strFilePath,oDict)
'******************************************************************************************
Function fnCheckSheets(strFilePath,oDict)
fnCheckSheets = False
Set objExcel = CreateObject("Excel.Application")
objExcel.Workbooks.Open strFilePath
Set shee = objExcel.Sheets
ReDim arrSheets(shee.Count - 1)
i = 0
For Each Element In shee
arrSheets(i) = trim(Element.Name)
i = i + 1
Next
Set oDict1 = fnDictBuild(arrSheets)
a = oDict1.Keys
b = oDict.Keys
status = "Pass"
For i = 0 To (oDict.Count - 1)
For j = 0 To (oDict1.Count - 1)
If trim(oDict.Item(b(i))) = trim(oDict1.Item(a(j))) Then
status = "Pass"
fnCheckSheets = True
Exit For
Else
status = "Fail"
End If
Next
If status = "Fail" Then
fnCheckSheets = False
Exit For
End If
Next
objExcel.Application.Quit
Set objExcel = Nothing
End Function



'******************************************************************************************
' fnDictBuild
' -----------
' This function builds a dictionary object from an array
' Arguments
' aArray: The array from which the dictionary object needs to be built
' This function returns the dictionary object.
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' a = Array("Instructions","Capitalization Guidelines","4BLOCK","Reference","EFFORT","Backup","DCRR Model","tax rates_depr schedule","FX rates","SII_Load","SII","File1","Version")
' set oDict = fnDictBuild(a)
'******************************************************************************************
Function fnDictBuild(aArray)
Dim oDict
Set oDict = CreateObject("Scripting.Dictionary")
If isArray(aArray) Then
ItemKey = 0
For Each sString in aArray
ItemKey = ItemKey + 1
oDict.Add ItemKey, sString
Next
End If
set fnDictBuild = oDict
End Function



'******************************************************************************************
' fnCheckExcelFontColor
' ---------------------
' This function checks the font color in the specified cell of the Excel Sheet
' Arguments
' strFilePath: The path of the excel file and the name of the excel sheet
' sheetno: Name of the sheet in which the cell is present
' intRow: Row number of the cell whose font color needs to be checked
' intColumn: Column number of the cell whose font color needs to be checked
' Color: Expected font color
' This function returns a Boolean Value
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' sheetno = "4BLOCK"
' intRow = 3
' intColumn = 3
' strFilePath = "D:\Automation\Project\MWP\QTP_Scripts\PMC\MWP_PMC_GEL TCO 4-Block_Create SII project_TP\Master 4 Blocker with complete data.xls"
' Msgbox fnCheckBackGroundColor(strFilePath,sheetno,intRow,intColumn,RGB(255,0,0))
'******************************************************************************************
Function fnCheckExcelFontColor(strFilePath,sheetno,intRow,intColumn,Color)
fnCheckExcelFontColor = False
Set objExcel = CreateObject("Excel.Application")
On Error Resume Next
objExcel.Workbooks.Open strFilePath
On Error Resume Next
set objSheet = objExcel.ActiveWorkbook.Worksheets(sheetno)
colo = objSheet.Range(Chr(64 + intColumn) & intRow).Font.Color
If colo = Color Then
fnCheckExcelFontColor = True
End If
objExcel.ActiveWorkbook.Close
objExcel.Application.Quit
Set objExcel = Nothing
End Function



'******************************************************************************************
' fnMax
' -----
' This function finds out the maximum value in a given set.
' Arguments
' someArray: Array of elements
' DataType: Data type of the elements. The possible values are Date, Integer, Long and Double
' This function returns the maximum value
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' Msgbox fnMax(Array("11/20/2005","1/31/2005","6/10/2005","9/18/2005","10/21/2005","10/13/2005"),"Date")
'******************************************************************************************
Function fnMax(someArray,DataType)
Dim i, x, y
Select Case DataType
Case "Date"
y = CDate(someArray(0))
Case "Integer"
y = CInt(someArray(0))
Case "Long"
y = CLng(someArray(0))
Case "Double"
y = CDbl(someArray(0))
End Select
'y = DataType(someArray(0))
For i = 1 To UBound(someArray) ' Loop through the rest of the elements
Select Case DataType
Case "Date"
x = CDate(someArray(i))
Case "Integer"
x = CInt(someArray(i))
Case "Long"
x = CLng(someArray(i))
Case "Double"
x = CDbl(someArray(i))
End Select
If x > y Then y = x
Next
fnMax = y
End Function



'******************************************************************************************
' fnMin
' -----
' This function finds out the minimum value in a given set.
' Arguments
' someArray: Array of elements
' DataType: Data type of the elements. The possible values are Date, Integer, Long and Double
' This function returns the minimum value
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' Msgbox fnMin(Array("11/20/2005","1/31/2005","6/10/2005","9/18/2005","10/21/2005","10/13/2005"),"Date")
'******************************************************************************************
Function fnMin(someArray,DataType)
Dim i, x, y
Select Case DataType
Case "Date"
y = CDate(someArray(0))
Case "Integer"
y = CInt(someArray(0))
Case "Long"
y = CLng(someArray(0))
Case "Double"
y = CDbl(someArray(0))
End Select
'y = DataType(someArray(0))
For i = 1 To UBound(someArray) ' Loop through the rest of the elements
Select Case DataType
Case "Date"
x = CDate(someArray(i))
Case "Integer"
x = CInt(someArray(i))
Case "Long"
x = CLng(someArray(i))
Case "Double"
x = CDbl(someArray(i))
End Select
If x < y =" x">
Next
fnMin = y
End Function



'******************************************************************************************
' fnGetObjectInActiveX
' --------------------
' This function retrieves the specified cell in an activeX grid
' Arguments
' obj: ActiveX spreadsheet
' row: the row number which has the column headers
' sourceColHeader: Column Name of the source column
' sourceColText: Data in the source column
' targetColHeader: Column Name of the target column
' This function returns the Cell object
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' Set a = Browser("Browser_2").Page("MatrixOne").Frame("pagecontent").ActiveX("Microsoft Office Spreadsheet").fnGetObjectInActiveX(obj,1,"Status","Status","Comments")
' Msgbox a.value
' OR
' Set obj = Browser("Browser_2").Page("MatrixOne").Frame("pagecontent").ActiveX("Microsoft Office Spreadsheet")
' set a = fnGetObjectInActiveX(obj,1,"Status","Status","Comments")
' Msgbox a.Value
'******************************************************************************************
Function fnGetObjectInActiveX(obj,row,sourceColHeader,sourceColText,targetColHeader)
set obj = obj.Object
range = trim(obj.ViewableRange)
range = Split(range,":")
startRow = Cint(Right(range(0),1))
startCol = Cint(Asc(Left(range(0),1)) - Asc("A") + 1)
For i = 1 To Len(range(1))
If IsNumeric(mid(range(1),i,1)) Then
Exit For
End If
Next
endRow = Cint(Right(range(1),(Len(range(1)) - (i-1))))
endCol = 0
If Len((Left(range(1),(i-1)))) > 1 Then
For j = 1 To Len((Left(range(1),(i-1))))
If j = Len((Left(range(1),(i-1)))) Then
endCol = endCol + Asc(Mid(Left(range(1),(i-1)),j,1)) - Asc("A") + 1 + Asc("Z") - Asc("A") + 1
Else
endCol = endCol + Asc(Mid(Left(range(1),(i-1)),j,1)) - Asc("A")
End If
Next
Else
endCol = Asc(Left(range(1),(i-1))) - Asc("A") + 1
End If

For i = startCol To endCol
If trim(obj.Cells(row,i).Value) = trim(sourceColHeader) Then
sourceCol = i
Exit For
End If
Next

For i = startCol To endCol
If trim(obj.Cells(row,i).Value) = trim(targetColHeader) Then
targetCol = i
Exit For
End If
Next

For i = (row + 1) To endRow
If trim(obj.Cells(i,sourceCol).Value) = trim(sourceColText) Then
targetRow = i
Exit For
End If
Next

char = 0
b = ""
If (targetCol/26) >= 1 Then
For i = 1 To (targetCol/26)
If i = 1 Then
char = Asc("A")
Else
char = char + 1
End If
Next
b = Chr(char) & Chr((targetCol Mod 26) - 1 + Asc("A"))
Else
b = Chr((targetCol Mod 26) - 1 + Asc("A"))
End If
Set fnGetObjectInActiveX = obj.Range(b & targetRow)
End Function

RegisterUserFunc "ActiveX","fnGetObjectInActiveX","fnGetObjectInActiveX"


'******************************************************************************************
' fnMyCheck
' ---------
' This function procedure clicks on the link in the MWP application's main page and checks for the specified links
' Arguments
' obj: the page object being passed
' Element1: Links which need to be clicked
' elementsToBeChecked : The links which need to be checked
' Thsi function returns a boolean value
' Example - Following is the Example Code
' -----------------------------------------------------------------------------------------
' Msgbox Browser("Matrix10 Applications").Page("Matrix10 Applications").fnMyCheck("My Desk,Projects","Projects,4 Block Submissions")
' OR
' set obj = Browser("Matrix10 Applications").Page("Matrix10 Applications")
' Msgbox fnMyCheck(obj,"My Desk,Projects","Projects,4 Block Submissions")
'******************************************************************************************
Function fnMyCheck(obj,Element1,elementsToBeChecked)
If InStr(Element1,",") <> 0 Then
Element = Split(Element1,",")
For i = 0 To Ubound(Element)
If i = 0 Then
If trim(Element(i)) <> "" Then
obj.WebElement("innertext:=" & trim(Element(i)),"Index:=0").Click(1)
End If
Else
If trim(Element(i)) <> "" Then
Page("index:=0").WebElement("class:=menu-label","innertext:="& trim(Element(i))).Click(1)
End If
End If
wait(1)
Next
Else
obj.WebElement("innertext:="& Element1,"Index:=0").Click
End If

If InStr(elementsToBeChecked,",") <> 0 Then
elementsToBeChecked = Split(elementsToBeChecked,",")
For i = 0 To UBound(elementsToBeChecked)
elem = trim(elementsToBeChecked(i))
If Page("index:=0").WebElement("class:=menu-item","innertext:="& elem).Exist(1) Then
fnMyCheck = True
Else
If Page("index:=0").WebElement("class:=menu-label","innertext:="& elem).Exist(1) Then
fnMyCheck = True
Else
fnMyCheck = False
Exit For
End If
End If
Next
Else
If Page("index:=0").WebElement("class:=menu-item","innertext:="& elementsToBeChecked).Exist(1) Then
fnMyCheck = True
Else
If Page("index:=0").WebElement("class:=menu-label","innertext:="& elementsToBeChecked).Exist(1) Then
fnMyCheck = True
Else
fnMyCheck = False
End If
End If

End If

End Function
--------------------------------------------------------------------------------------------