Common Functions in QTP 1

1. Taking Snapshot as JPG file
Public Sub TakeSnapshot (obj, sFileName)
   Dim fso
   Dim resDir
   Dim sTmpFileName
   sTmpFileName = "tmp"
   Set fso = CreateObject("Scripting.FileSystemObject")
   resDir = Environment("ResultDir")
   obj.CaptureBitmap "C:"&Chr(92)&sTmpFileName&".bmp"
   SystemUtil.Run "BMP2JPG.EXE", "C:"&Chr(92)&sTmpFileName&".bmp "&"C:"&Chr(92)&sTmpFileName&".jpg"
   ' the JPEG has been created, move it to the results Dir then delete both files from c
   Wait(5)
   fso.CopyFile "C:"&Chr(92)&sTmpFileName&".jpg", resDir&Chr(92)&sFileName&".jpg"
   fso.DeleteFile("C:"&Chr(92)&sTmpFileName&".bmp")
   fso.DeleteFile("C:"&Chr(92)&sTmpFileName&".jpg")
   ' reportevent    Reporter.ReportEvent 2, "TakeSnapshot", "Created file: "&VbCrLf&resDir&Chr(92)&sFileName&".jpg"
   Set fso = Nothing
End Sub
2. TE Functions
'Send Enter Key
'Syntax
'Call ReturnKey (strWindowName)
Public Sub ReturnKey (strWindowName)
   TeWindow("TeWindow").TeScreen(strWindowName).SendKey TE_ENTER
   TeWindow("TeWindow").TeScreen(strWindowName).Sync
End Sub

'Send PauseBreak
'Syntax
'Call PauseBreak (strTeScreen,strTeField)
'Public Sub PauseBreak (strTeScreen,strTeField)
Public Sub PauseBreak (strTeScreen)
TeWindow("TeWindow").TeScreen(strTeScreen).SendKey TE_CLEAR
TeWindow("TeWindow").TeScreen(strTeScreen).Sync
End Sub

'Enter a value into any defined edit field
'Syntax
'Call Public Sub AnyEdit (strTeScreen,strTeField,strInput)
Public Sub AnyEdit (strTeScreen,strTeField,strInput)
TeWindow("TeWindow").TeScreen(strTeScreen).TeField(strTeField).Set strInput
End Sub

'Send Enter Key
'Syntax
'Call ReturnKey (strWindowName, strKey)
Public Sub SendKey (strWindowName, strKey)
Dim qtApp 'As QuickTest.Application ' Declare the Application object variable
Dim qtTeOptions 'As QuickTest.TeOptions ' Declare the TE Options object variable
TeWindow("TeWindow").TeScreen(strWindowName).SendKey strKey
TeWindow("TeWindow").TeScreen(strWindowName).Sync
End Sub
3. Test Parameters
Creating Test Parameter at Run-time
********************************
Set qtApp = CreateObject("QuickTest.Application") ' Create the Application object
Set pDefColl = qtApp.Test.ParameterDefinitions
Set pDef = pDefColl.Item(1)
MsgBox pDef.DefaultValue

Passing Parameters from QC to QTP scripts
*************************************
1) Create Test parameters in QTP (via file>Settings>Parameters) [These are the parameters that you see in QC, on the automated tab of the Configuration page in the Test Instance Propertirs.]
2) Create action parameters (Action Properties> Parameters)
3)Link action & test parameters together. To do this, go into Action Call Properties>Parameters / In Keyword View right click the action and select the Action Call Properties > Parameters. You'll see your action parameters here. Click in the Value column for a parameter and press the Configure Value button. This will open up the Value Configuration Options dialogue. In the parameter drop down list, select Test/action parameter and then, from the following Test parameters; Parameter drop down list, select the Test parameter that you want to link to your Action parameter.
This should then link the Test parameters to the Action parameters.
Then in your script, you'll use the parameters as follows: -
Browser("Browser_Name").Page("Page_Name").WebEdit("Edit_Name").Set Parameter("Parameter_Name")
4. Upload / Attach File to Quality Center
' Requirements:
' QTP must be connected to QC.
' QCs root directory must be "Subject"
' This was tested on QC 8.2
' The folder location must include a "\" at the end of the string. For example, "C:\Folder" will not work but "C:\Folder\" will.
'This will attach files to QC (and possibly TestDirector).
'Parameters:Folder, Filename, QC Folder, QC Test Name
Public function AttachFileToQC(FromFileLoc,FromFileName,ToQCTestPath,ToQCTestName) 
  Dim FromFile, Qc, tm, root, fold
  AttachFileToQC="Failed to attach file for unknown reason."
  FromFile=FromFileLoc & FromFileName
  Set fso = CreateObject("Scripting.FileSystemObject")
  status=fso.FileExists(FromFile)
  If status=False Then
    AttachFileToQC="Failed to attach file because file does not exist"
    Set fso = Nothing
    Exit Function
  End If
  Set Qc = QCUtil.TDconnection 'if it fails here, you're not connected to QC
  Set tm = Qc.TreeManager
  Set root=tm.TreeRoot("Subject") 'Connects to Subject
  Set fold = tm.NodeByPath( "Subject\" & ToQCTestPath)'Finds folder, if it fails here, you're either pointing to a bad QC folder or to a test in a folder
  Set testList = fold.FindTests(ToQCTestName)
  if(testList.Count =0) then
    AttachFileToQC="Failed to find any test in folder."
    Set Qc = Nothing
    Set tm = Nothing
    Set root = Nothing
    Set fold = Nothing
    Set testList = Nothing
  end if
  For i = 1 To testList.Count
    Set vTest = testList.Item(i)
    If LCase(vTest.Name) = LCase(ToQCTestName) Then 'searchs each test name for requested test. This is not case sensative.
      Set attf = vTest.Attachments
      Set att = attf.AddItem(Null)
      att.FileName = FromFile
      att.Type = 1
      att.Post
      att.Save False
      AttachFileToQC= "The file " & FromFileName & " was uploaded on the following path " & ToQCTestPath & " to the test " & ToQCTestName & ","
      Set Qc = Nothing
      Set tm = Nothing
      Set root = Nothing
      Set fold = Nothing
      Set testList = Nothing
      Set attf = Nothing
      Set att = Nothing
      Set vTest = Nothing
      Exit Function
    end if
  next
  Set Qc = Nothing
  Set tm = Nothing
  Set root = Nothing
  Set fold = Nothing
  Set testList = Nothing
  Set vTest = Nothing
End Function
5. Upload / Attach File to Quality Center
Print AttachFileToQC("C:\Documents and Settings\konkaravi.krishna\Desktop\","Workaround_Script.txt","BPT Resources\Libraries")
Public function AttachFileToQC(FromFileLoc,FromFileName,ToQCTestPath) 
    Dim FromFile, Qc, tm, root, fold
    AttachFileToQC="Failed to attach file for unknown reason."
    FromFile=FromFileLoc & FromFileName
    Set fso = CreateObject("Scripting.FileSystemObject")
    status=fso.FileExists(FromFile)
    If status=False Then
    AttachFileToQC="Failed to attach file because file does not exist"
    Set fso = Nothing
    Exit Function
    End If
    Set Qc = QCUtil.TDconnection 'if it fails here, you're not connected to QC
    Set tm = Qc.TreeManager
    Set root=tm.TreeRoot("Subject") 'Connects to Subject
    Set fold = tm.NodeByPath( "Subject\" & ToQCTestPath)'Finds folder, if it fails here, you're either pointing to a bad QC folder or to a test in a folder
    Set attf = fold.Attachments
    Set att = attf.AddItem(Null)
    att.FileName = FromFile
    att.Type = 1
    att.Post
    att.Save False
    AttachFileToQC= "The file " & FromFileName & " was uploaded on the following path " & ToQCTestPath
    Set att = Nothing
    Set Qc = Nothing
    Set tm = Nothing
    Set root = Nothing
    Set fold = Nothing
    Set vTest = Nothing
End Function
3. Checking for DNS Existance
Function CheckDSN(DSN, Server, DB)
'Create an object to read registry
Set oReg = GetObject("Winmgmts:\\.\root\default:StdRegProv")
'Set the path to read System DSNs
strPath = "SOFTWARE\ODBC\ODBC.INI"
'Get the list of System DSNs
oReg.EnumKey &H80000002, strPath, arrSubKeys
'Check if the required System DSN exists
DSNExists = False
For Each subkey in arrSubKeys
If subkey = DSN Then
DSNExists = True
Exit For
End If
Next
'If the required System dsn exists, Check if the Server and DB are correct or give a correct message
If DSNExists Then
strKeyPath = strPath & "\" & DSN
'Note what server is mapped in this DSN
oReg.GetStringValue &H80000002, strKeyPath, "NetworkAddress", szValueServer
'Check if the Server is the required one
If szValueServer <> Server Then
CheckDSN = "Required System DSN exists on the system but is mapped to a Wrong Server - " & szValueServer
'Check if the DB is the Required One
Else
'Note waht DB is used in this DSN
oReg.GetStringValue &H80000002, strKeyPath, "Database", szValueDB
If szValueDB <> DB Then
CheckDSN = "Required System DSN exists on the system but is mapped to a Wrong Database - " & szValueDB
Else
CheckDSN = ""
End If
End If
Else
CheckDSN = "Required System DSN does not exist on the System."
End If
Set oReg = Nothing
End Function
3. Record Execution time of a script
To record the execution time of a QTP script Timer function from VB script can be used.
Declare following steps

StartTime= Timer [Begining of the script]
EndTime = Timer [ End of Script]
TotalTime = EndTime - StartTime
min = TotalTime \ 60
sec = TotalTime mod 60
Msgbox("Execution Time=" &min &":" &sec)
3. Upload / Attach File to Quality Center3. Upload / Attach File to Quality Center3. Upload / Attach File to Quality Center''********************************************************************************************************************************************
' This is a basic sample of Descriptive Programming in QTP for Web applications.
' If you are interested in doing more with it, either do it yourself or hire me as consultant :). Of course I prefer second part =:+)
' I am limiting shared code because each one of you has different needs/skills and would need different things from DP approach
' I am specifically avoiding the biggest benefit of this approach: overloading functions with extra code (like measuring how long it tool to refresh the page, translation, doing basic verifications etc)
' Even for Link object on the web I have created many more functions, but purpose of this article is to give you a brief introduction to 'hidden powers' of Descriptive Programming approach.
' I do not claim DP is the only option, or that my functions are perfect. You can pick as much as you want on my coding style as well. However, be warned: once you use DP once.... =;-}
' And Yes, I did NOT compile this code in my QTP :). Point is to give you real experience with DP (by the way, code SHOULD work)
' To work with this code, simply load it as any other library. Make sure only ONE IE window is open. Create basic script by using Click_Link function
''********************************************************************************************************************************************
Intilization
***********

dim EXIST_TIME_OUT
dim browser_title
dim page_title

page_title=".*"
browser_title=".*"
EXIST_TIME_OUT = 1
1. Link Exists
Function Link_Exists(pStrLinkText, pIntLinkIndex)
    'check existence without index parameter.
    Dim existenceWithoutIndex_
    Call Initiate_wHandle ' make sure hWindow is known
    Reporter.Filter = rfDisableAll
    existenceWithoutIndex_ = Browser("hwnd:=" & hWindow).Page("title:=" & page_title).Link("Name:=" & pStrLinkText).Exist(EXIST_TIME_OUT)
    'If there is only 1 object and pIntLinkIndex is set 0, this function returns True
    If existenceWithoutIndex_ And pIntLinkIndex = 0 Then
        Link_Exists = True
        Exit Function
    End If
    'If there is only 1 object and pIntLinkIndex is NOT set 0, this function returns False
    If existenceWithoutIndex_ And pIntLinkIndex <> 0 Then
        Link_Exists = False
        Exit Function
    End If
    'In the other case, which there is no object or are more than 1.
    Reporter.Filter = rfDisableAll
    Link_Exists = Browser("hwnd:=" & hWindow).Page("title:=" & page_title).Link("Name:=" & pStrLinkText, "Index:=" & pIntLinkIndex).Exist(EXIST_TIME_OUT)
End Function
2. Verify Link Exists
Function Verify_Link_Exists(pStrLinkText, pIntLinkIndex)
    If Link_Exists (pStrLinkText, pIntLinkIndex) Then
        Reporter.Filter = rfEnableAll
        Reporter.ReportEvent micPass , _
    "Verify_Link_Exists", _
    "Link found: link name = '" & pStrLinkText & "' link index ='" & pIntLinkIndex & "'"
    Verify_Link_Exists = PASS
    Else
        Reporter.ReportEvent micFail, _
        "Verify_Link_Exists", _
        "Link not found: link name = '" & pStrLinkText & "' link index ='" & pIntLinkIndex & "'"
        Verify_Link_Exists = FAIL
    End If
End Function
3. Verify Link Not Found
Function Verify_Link_NotFound(pStrLinkText, pIntLinkIndex)
    If Link_Exists (pStrLinkText, pIntLinkIndex) Then
        Reporter.Filter = rfEnableAll
        Reporter.ReportEvent micFail , "Verify_Link_NotFound", "Link found: link name = '" & pStrLinkText & "' link index ='" & pIntLinkIndex & "'"
        Verify_Link_NotFound = FAIL
    Else
        Reporter.Filter = rfEnableAll
        Reporter.ReportEvent micPass,"Verify_Link_NotFound", "Link Not Found: link name = '" & pStrLinkText & "' link index ='" & pIntLinkIndex & "'"
        Verify_Link_NotFound = PASS
    End If
End Function
4. Count_Link
Function Count_Link (pStrName)
dim i_
i_=0
while (Link_Exists(pStrName, i_))
i_=i_+1
wend
Count_Link = i_
End Function
5. Clicking Link
Function Click_Link(pStrLinkText, pIntLinkIndex)
    If Link_Exists (pStrLinkText, pIntLinkIndex) Then
        start_time=time
        Reporter.Filter = rfDisableAll
        Browser("hwnd:=" & hWindow).Page("title:=" & page_title).Link("Name:="& pStrLinkText, "Index:=" & pIntLinkIndex).Click
        Reporter.Filter = rfEnableAll
        Reporter.ReportEvent micPass,"Click_Link","Click_Link worked. Link name = '" & pStrLinkText & "' link index ='" & pIntLinkIndex & "'"
        Click_Link = PASS
        Browser("hwnd:=" & hWindow).Sync
    Else         Reporter.ReportEvent micFail, "Click_Link", "Link not found! Couldn't click on link. Link name = '" & pStrLinkText & "' link index ='" & pIntLinkIndex & "'"
        Click_Link = FAIL
    End If
End Function
6. Initiate Window Handle
' NOTE: window handling is the HARDEST item of Descriptive Programming. Each one of you should customize it for you own needs.
' NOTE: I am specifically NOT providing what I have created to handle windows -- you might implement it better then I if you spend some time on it.
Function Initiate_wHandle()
    Reporter.Filter = rfDisableAll
    If Browser("index:=0").Exist(EXIST_TIME_OUT) Then
        wHandle1 = Browser("index:=0").GetROProperty("hwnd")
    Else
        Reporter.Filter = rfEnableAll
        Reporter.ReportEvent micFail, "NO WINDOWS OPEN!!!", ""
    End If
    Reporter.Filter = rfEnableAll
End Function