Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Showing posts with label Vbscript Function in QTP. Show all posts
Showing posts with label Vbscript Function in QTP. Show all posts

QTP Reusable Functions Codes 5

QTP Reusable Function Codes :


Automation testing using QTP has always been talked upon the most in the testing industry. There are numerous features available within this very toolset, but most of us might not be aware of this very feature which has been discussed in this very articles on automation testing using QTP which is functions created in Vbscript , and is very useful in code customization to meet our automation testing requirements , as it reduces the script maintenance effort..


1) How to add a constant number in a datatable?
This is more to do with MS excel then QTP!! but useful to know because at times it becomes frustrating to the novices.
Just append ' to the number, this trick somehow is related to the simple concept applied in excel, however that we can deal separately.
Ex: if you wish to enter 1234567 in datatable then write it as '1234567

2) How can i check if a parameter exists in DataTable or not?

The best way would be to use the below code:
on error resume next
val=DataTable("ParamName",
dtGlobalSheet)
if err.number<> 0 then
'Parameter does not exist
else
'Parameter exists
end if

3) Does QuickTest Professional support Internet Explorer 7.0?
QuickTest Professional 9.1
QuickTest Professional 9.1 supports Microsoft Internet Explorer 7.0 Beta 3. Internet Explorer version 7.0 is now certified to work and to be tested with QuickTest Professional version 9.1.
QuickTest Professional 9.0
QuickTest Professional 9.0 supports Internet Explorer 7.0 Beta 2.
QuickTest Professional 8.2 and below
QuickTest Professional 8.2 and below do not include support for Internet Explorer 7.0.
Does QuickTest Professional support Firefox?
QuickTest Professional 9.1 and 9.2
QuickTest Professional 9.1 provides replay support for Mozilla Firefox 1.5 and Mozilla Firefox 2.0 Alpha 3 (Alpha-level support for Bon Echo 2.0a3).
Notes:
QuickTest Professional 9.1 will not record on FireFox. You can record a test on Microsoft Internet Explorer and run it on any other supported browser, such as FireFox.
The .Object property for web objects is not supported in FireFox.
QuickTest Professional 9.0
QuickTest Professional 9.0 provides replay support for Mozilla FireFox 1.5.
Notes:
QuickTest Professional 9.0 will not record on FireFox. You can record a test on Microsoft Internet Explorer and run it on any other supported browser, such as FireFox.
The .Object property for web objects is not supported in FireFox.
QuickTest Professional 8.2 and below
QuickTest Professional 8.2 and below do not have support for Firefox.
4) What is the lservrc file in QTP?
The lservrc file contains the license codes that have been installed
The lservrc file contains the license codes that have been installed. Whenever a new license is created, the license code is automatically added to this file. The lservrc file is a text file, with no extension.
File Location:
1) For a Concurrent (Floating) license installation:

C:\Program Files\Common Files\SafeNet\ SafeNet Sentinel\ LM Server\WinN

2) For a Seat (Stand-alone) license installation:

    * QTP 9.2 and below versions: C:\Program Files\Common Files\Mercury Interactive\License Manager\lservrc
    * QTP 9.5 and above versions: C:\Documents and Settings\All Users\Application Data\HP\Functional testing\License



Debug Run


   1. Step Into

      Choose Debug > Step Into, click the Step Into button, or press F11 to run only the current line of the active test or component. If the current line of the active test or component calls another action or a function, the called action/function is displayed in the QuickTest window, and the test or component pauses at the first line of the called action/function.

   2. Step Out

      Choose Debug > Step Out or click the Step Out button, or press SHIFT+F11 only after using Step Into to enter a action or a user-defined function. Step Out runs to the end of the called action or user-defined function, then returns to the calling action and pauses the run session.

   3. Step Over

      Choose Debug > Step Over or click the Step Over button, or press F10 to run only the current step in the active test or component. When the current step calls another action or a user-defined function, the called action or function is executed in its entirety, but the called action script is not displayed in the QuickTest window.

'Example of How to use functions.

' Example use DSN created for database of Flight sample application.


SQL="SELECT * FROM ORDERS"
connection_string="QT_Flight32"

isConnected = db_connect ( curConnection ,connection_string )

If isConnected = 0 then
   ' execute the basic SQL statement
   set myrs=db_execute_query( curConnection , SQL )
   ' report the query and the connection string
   Reporter.ReportEvent micInfo ,"Executed query and created recordset ","Connection_string is ==> " & connection_string & " SQL   
query is ===> " & SQL    ' show the number of rows in the table using a record set
   msgBox " Quantity of rows in queried DB ( db_get_rows_count )==> " & db_get_rows_count( myrs )
   ' show the number of rows in the table using a new SQL statement
   msgBox " Quantity of rows in queried DB (db_get_rows_count_SQL ) ==> " & db_get_rows_count_SQL( curConnection , "SELECT COUNT(*) FROM ORDERS" )
   ' change a value of a field in an existing row
   rc = db_set_field_value (curConnection, "ORDERS" , "Agents_Name" , "test", "Agents_Name", "AGENT_TESTER")
   ' examples of how to retrieve values from the table
   msgBox "val row 0 col 0: " & db_get_field_value( myrs , 0 , 0 )
   msgBox "val row 0 col 1: " & db_get_field_value( myrs , 0 , 1 )
   msgBox "val row 1 col Name: " & db_get_field_value( myrs , 1 , "Agents_Name" )
   msgBox "val SQL row 1 col Name: " & db_get_field_value_SQL( curConnection , "ORDERS" , 1 , "Agents_Name" )
   db_disconnect curConnection
End If

' Database Functions library

'db_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 "DSN=SQLServer_Source;UID=SA;PWD=abc123"

Function db_connect( byRef curSession ,connection_string)

   dim connection
   on error Resume next
   ' Opening connection
   set connection = CreateObject("ADODB.Connection")
    If Err.Number <> 0 then
   db_connect= "Error # " & CStr(Err.Number) & " " & Err.Description
   err.clear
   Exit Function
   End If
   connection.Open connection_string
   If Err.Number <> 0 then
   db_connect= "Error # " & CStr(Err.Number) & " " & Err.Description
   err.clear
   Exit Function
   End If
   set curSession=connection
   db_connect=0
End Function

' db_disconnect

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

Function db_disconnect( byRef curSession )

   curSession.close
   set curSession = Nothing
End Function

' db_execute_query

' The function executes an SQL statement.
' Note that a db_connect for (arg1) must be called before this function
' curSession - the session name (string)
' SQL - an SQL statement

Function db_execute_query ( byRef curSession , SQL)

   set rs = curSession.Execute( SQL )
   set db_execute_query = rs
End Function

' db_get_rows_count

' The function returns the number of rows in the record set
' curRS - variable , contain record set , that contain all values that retrieved from DB by query execution

Function db_get_rows_count( byRef curRS )
   dim rows
   rows = 0
   curRS.MoveFirst
   Do Until curRS.EOF
   rows = rows+1
   curRS.MoveNext
   Loop
   db_get_rows_count = rows
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 db_get_rows_count_SQL( byRef curSession ,CountSQL )
   dim cur_rs
   set cur_rs = curSession.Execute( CountSQL )
   db_get_rows_count_SQL = cur_rs.fields(0).value
End Function

' db_get_field_value_SQL

' curSession - variable denote current active connection
' tableName - name of the table , where value should be retrieved
' rowIndex - row number
' colName - the column name.

Function db_get_field_value_SQL( curSession , tableName , rowIndex , colName )

   dim rs
   SQL = " select " & colName & " from " & tableName
   set rs = curSession.Execute( SQL )
   rs.move rowIndex
   db_get_field_value_SQL = rs.fields(colName).value
End Function

' db_get_field_value

' The function returns the value of a single item of an executed query.
' Note that a db_execute_query for (arg1) must called before this function
' curRecordSet - variable , contain record set , that contain all values that retrieved from DB by query execution
' rowIndex - the row index number (zero based)
' colIndex - the column index number (zero based) or the column name.
' returned values
' -1 - requested field index more than exists in record set

Function db_get_field_value( curRecordSet , rowIndex , colIndex )

   dim curRow
   curRecordSet.MoveFirst
   count_fields = curRecordSet.fields.count-1
   If ( TypeName(colIndex)<> "String" ) and ( count_fields < colIndex ) then
   db_get_field_value = -1 'requested field index more than exists in recordset
   Else
   curRecordSet.Move rowIndex
   db_get_field_value = curRecordSet.fields(colIndex).Value
   End If
End Function

' db_set_field_value

' The function changes the value of a field according to a search criteria.
' We search for a certain row according to a column name and the desired vale, then we change a value in that row according
' to a desired columns
' curConnection - the session name (string)
' tableName - name of the table , where value should be retrieved
' colFind - the column we search the criteria in
' colFindValue - the value we search in the column
' colChange - the column were we want to change the value
' colChangeValue - the new value ' returned values

' -1 - requested field index that doesn't exists in the recordset

Function db_set_field_value(
curConnection, tableName , colFind , colFindValue, colChange, colChangeValue)
   dim curRow
   dim updateSQL
   dim checkSQL
   checkSQL = "select * from Details"
   set myrs1 = db_execute_query( curConnection , SQL )
   myrs1.MoveFirst
   count_fields = myrs1.fields.count
   If ( TypeName(colFind)<> "String" ) or ( TypeName(colChange)<> "String" ) then
   db_set_field_value = -1 'requested field index that doesn't exists in the record set
   Else
   updateSQL = "UPDATE " & tableName & " SET " & colChange & "='" & colChangeValue & "' WHERE " & colFind & "='" & colFindValue &    "'"
   set myrs1 = db_execute_query( curConnection , updateSQL )
   db_set_field_value = 1 'operation suceeded
   End If
End Function

' db_add_row

' The function adds a new row to the desired table

' curConnection - variable , contains a recordset , that contains all the values to be retrieved from DB by query execution
' tableName - name of the table , where value should be retrieved from
' values - array that contains values to be entered in a new row to the table.
' Note: the function must receive values for all the columns in the table!
' returned values
' -1 - the number of values to be entered to the table doesn't fit the number of columns
' 1 - execution of the query succeed and the data was entered to the table

Function db_add_row(curConnection, tableName , byRef values)

   dim i
   dim updateSQL
   dim myrs1
   updateSQL = "INSERT INTO " & tableName & " VALUES ("
   arrLen = UBound (values) - LBound (values) + 1
   set myrs1=db_execute_query( curConnection , SQL )
   myrs1.MoveFirst
   count_fields = myrs1.fields.count
   ' check if numbers of values fit the numbers of columns
   If arrLen <> count_fields then
   db_add_row = -1
   Else
   For i = 0 to arrLen-1
   updateSQL = updateSQL & values (i)
   If i <> arrLen-1 then
   updateSQL = updateSQL & ","
   End If
   Next
   updateSQL = updateSQL & ")"
   set myrs1 = db_execute_query( curConnection , updateSQL )
   db_add_row = 1
End If
End Function

' represent_values_of_RecordSet

' the function reports all the values on fields in a record set
' curRS - variable , contains the recordset , that contains all the values that were retrieved from the DB by the query execution

Function represent_values_of_RecordSet( myrs)

dim curRowString
myrs.MoveFirst
reporter.ReportEvent 4,"Fields quantity" , myrs.fields.count
count_fields = myrs.fields.count-1
curRow=0
Do Until myrs.EOF
   curRowString= ""
   curRow = curRow+1
   For ii=0 to count_fields
   curRowString = curRowString& "Field " &"==> " & myrs.fields(ii).Name &" : Value ==>" & myrs.fields(ii).Value & vbCrLf
   Next
   myrs.MoveNext
   reporter.ReportEvent 4,"Current row"& curRow , curRowString
Loop
End Function





Learn More On QTP Reusable Function creation codes :

QTP-reusable-functions-codes-5
QTP-reusable-functions-codes-4
QTP-reusable-functions-codes-3
QTP-reusable-functions-codes-2
QTP-reusable-functions-codes-1


For gaining more insights in the automation using QTP log on to below url :
Automation Testing Using QTP

QTP Reusable Functions Codes 4


QTP Reusable Function Codes :


Automation testing using QTP has always been talked upon the most in the testing industry. There are numerous features available within this very toolset, but most of us might not be aware of this very feature which has been discussed in this very articles on automation testing using QTP which is functions created in Vbscript , and is very useful in code customization to meet our automation testing requirements , as it reduces the script maintenance effort.

1. Can I change the Active Screen which is shown on every new test?

You can change the Active Screen to any valid HTML page. The page can be located either locally or on the network.

For example, if you want your entire organization to view the same Active Screen when opening QuickTest Professional, open the NewTest.inf file located in QuickTest Professional\dat\SnapShots folder and add the following line:

FileName1= "any full path to an HTML file"

For example:
FileName1=\mercury\public\MainPage.html

2. How do I create an action template?

If you want to include one or more statements in every new action in your test, you can create an action template. For example, if you always enter your name as the author of an action, you can add this comment line to your action template. An action template applies only to actions created on your computer.

To create an action template, create a text file containing the comments, function calls, and other statements that you want to include in your action template. The text file must be in the structure and format used in the Expert View.

Save the text file as ActionTemplate.mst in your QuickTest Professional\dat folder. All new actions you create contain the script lines from the action template.

3. How can I configure the report to show only errors by default?

You can configure the report to show only errors by default by adding the following section to the QTReport.ini file in your QuickTest Professional\bin folder.

[FilterDialog]

ReportAppDefaultFilter=1 # for error only

ReportAppDefaultFilter=3 # shows all messages (default)

4. How do I use environment variables?

QuickTest supports using environment variables. Environment variables can be either system variables or user-defined variables.

You can define the user-defined variables in an external file QuickTest reads when it is launched.

5. I have a Microsoft Access database that contains data I would like to use in my test. How do I do this?

The Expert View enables you to access databases using ADO and ODBC. Below is a sample test that searches for books written by an author in the "Authors" table of the database.

Dim MyDB
Dim MyEng
Set MyEng = CreateObject("DAO.DBEngine.35")
Dim Td
Dim rs
' Specify the database to use.
Set MyDB = MyEng.OpenDatabase("BIBLIO.MDB")
' Read and use the name of the first 10 authors.
Set Td = MyDB.TableDefs("Authors")
Set rs = Td.OpenRecordset
rs.MoveFirst
For i = 1 To 10
   Browser("Book Club").Page("Search Books").WebEdit("Author Name").Set rs("Author")
   Browser("Book Club").Page("Search Books").WebButton("Search").Click
Next

6. How do I add a manual wait step to my test?

A manual wait (think time) can be added to a QuickTest Professional test using the following command:

Call Wait()

7. How do I make the test prompt the user for input while it is running?

The VBScript InputBox function enables you to display a dialog box that prompts the user for input and then continues running the test. You can use the value that was entered by the user later in the test. For more information on the InputBox function, refer to the VBScript Reference.

The following example shows the InputBox function used to prompt the user for a password.

Browser("Mercury Tours").Page("Mercury Tours").WebEdit("username").Set "administrator"

Passwd = InputBox ("Enter password", "User Input")

Browser("Mercury Tours").Page("Mercury Tours").WebEdit("password").Set Passwd

8. How can I configure the report to show only errors by default?

You can configure the report to show only errors by default by adding the following section to the QTReport.ini file in your QuickTest Professional\bin folder.

[FilterDialog]

ReportAppDefaultFilter=1 # for error only

ReportAppDefaultFilter=3 # shows all messages (default)

9. How can I remove test result files from old tests?

You can use the Test Results Deletion Tool to view a list of all the test results in a specific location in your file system or in a Quality Center project. You can then delete any test results that you no longer require.

The Test Results Deletion Tool enables you to sort the test results by name, date, size, and so forth, so that you can easily identify the results you want to delete.

You can find this utility in Start > Programs > QuickTest Professional > Tools > Test Results Deletion Tool.

10. How can I launch a new browser from a test?

A new browser window (and any other application) can be launched from within a test by adding the following step to your test:

SystemUtil.Run "iexplore.exe", "http://www.testingfaqs.co.in"

11. How can I record on nonstandard menus?

You can modify how QuickTest behaves when it records menus.

The options that control this behavior are located in the Advanced Windows Applications Options dialog box. (Tools > Options > Windows Applications > Advanced).

12. How can I terminate an application that is not responding?

You can terminate any standard application while running a test in QuickTest by adding one of the following steps to the test:

SystemUtil.CloseProcessByName "app.exe"
SystemUtil.CloseProcessByWndTitle "Some Title"

13. Can I copy and paste to and from the Clipboard during a test run?

You can use the Clipboard object to copy, cut, and paste text during a QuickTest test run.

The object has the same methods as the Clipboard object available in Visual Basic:

Clear
GetData
GetFormat
GetText
SetData
SetText

Below is an example of Clipboard object usage:

Set MyClipboard = CreateObject("Mercury.Clipboard")
MyClipboard.Clear
MyClipboard.SetText "TEST"
MsgBox MyClipboard.GetText

14. How do I close QuickTest after "n" test runs when running from Quality Center?

When running multiple QuickTest tests from Quality Center, you can specify that you want to close QuickTest after a specified number of tests are executed.

To do so, add the following lines to the end of the mic.ini file, located in your QuickTest Professional\bin folder:
[RemoteAgent]
CloseToolAfterRuns= (number)

15. Adding Defects to Quality Center

Connects to Quality Center (TestDirector) from a QuickTest test and adds a bug to the database.

Dim TDConnection
Set TDConnection = CreateObject("TDApiOle.TDConnection")
TDConnection.InitConnection "http://yovav/tdbin" ' URL for the DB
TDConnection.ConnectProject "TD76","bella","pino" ' Valid login information
If TDConnection.Connected Then
MsgBox("Connected to " + chr (13) + "Server " + TDConnection.ServerName _
+ chr (13) +"Project " + TDConnection.ProjectName )
Else
MsgBox("Not Connected")
End If
'Get the IBugFactory
Set BugFactory = TDConnection.BugFactory
'Add a new empty bug
Set Bug = BugFactory.AddItem (Nothing)
'Fill the bug with relevant parameters
Bug.Status = "New"
Bug.Summary = "Connecting to TD"
Bug.Priority = "4-Very High" ' depends on the DB
Bug.AssignedTo = "admin" ' user that must exist in the DB's users list
Bug.DetectedBy = "admin" ' user that must exist in the DB's users list
'Post the bug to database (commit)
Bug.Post

16. Using Message Boxes That Close Automatically

The function below shows a message box that disappears after the specified timeout (in seconds). The script execution then continues.

Public Sub MsgBoxTimeout (Text, Title, TimeOut)
   Set WshShell = CreateObject("WScript.Shell")
   WshShell.Popup Text, TimeOut, Title
End Sub

If TimeOut is 0, it behaves just like a normal message box. If TimeOut is greater than 0, the dialog box disappears after the specified number of seconds.

17. Using Microsoft Word Spell Check

The following code shows a function for checking the number of spelling and grammar errors in a string. This function is also used to check the accuracy of a specific property in all the objects of a given application.

Function NumberOfSpellErrors(strText)
Dim objMsWord
Set objMsWord = CreateObject("Word.Application")
objMsWord.WordBasic.FileNew
objMsWord.WordBasic.Insert strText
NumberOfSpellErrors = objMsWord.ActiveDocument.SpellingErrors.Count
objMsWord.Documents.Close (False)
objMsWord.Quit ' close the application
Set objMsWord = Nothing' Clear object memory
End Function

' The following function uses the Spell errors function to check a specific property
' of all the objects with a given description which are under a given parent

Sub CheckAllObjects(ParentObj, ObjDesc, PropName)
Dim ObjCol, idx, PropValue, OldReportMode
OldReportMode = Reporter.Filter
Reporter.Filter = 2 ' Report only errors
If (IsNull(ParentObj)) Then
Set ObjCol = Desktop.ChildObjects(ObjDesc)
Else
Set ObjCol = ParentObj.ChildObjects(ObjDesc)
End If
For idx=0 to ObjCol.count-1
PropValue = ObjCol.Item(idx).GetROProperty(PropName)
RetVal = NumberOfSpellErrors(PropValue) ' The actual spell check result
If (RetVal > 0) Then
ReportText = "Object #" & idx+1 & ": The '" & PropName & "' Property has " & RetVal & " spell errors (" & PropValue & ")"
Reporter.ReportEvent 1, "Spell Check", ReportText
End If
Next
Reporter.Filter = OldReportMode
End Sub

'''''''''''''''''''''''''''''''''''''
' An example of usage:
' Go over all the static objects in the Login window of the Flight Application
' and for each object check the text for spelling and grammatical errors
'''''''''''''''''''''''''''''''''''''

' Go over all the links in the page and report all the ones that fail the spellcheck
Set Desc = Description.Create()
Desc("nativeclass").Value = "Static"
Set Obj = Dialog("nativeclass:=#32770", "text:=Login")
' Invoke the Flight Application before calling the function
CheckAllObjects Obj, Desc, "text"


18. Using Microsoft Outlook to Send Email

The code below illustrates two methods for sending email using the VBScript code in QuickTest Professional, and two different COM objects.

' Example 1

Function SendMail(SendTo, Subject, Body, Attachment)
Set ol=CreateObject("Outlook.Application")
Set Mail=ol.CreateItem(0)
Mail.to=SendTo
Mail.Subject=Subject
Mail.Body=Body
If (Attachment <> "") Then
Mail.Attachments.Add(Attachment)
End If
Mail.Send
ol.Quit
Set Mail = Nothing
Set ol = Nothing
End Function

' Example 2

Function SendMail(SendFrom, SendTo, Subject, Body)
Set objMail=CreateObject("CDONTS.Newmail")
ObjMail.From = SendFrom
ObjMail.To = SendTo
ObjMail.Subject = Subject
ObjMail.Body = Body
ObjMail.Send
Set objMail = Nothing
End Function

19. DP Example

SetEditBox "userID", 0, "Sairam"

Sub SetEditBox(ObjName, index, TestData)
strHandle = Window("RegExpWndClass:=IEFrame","index:=0" ).GetROProperty("hWnd")
Set gobjBrowser = Browser("hWnd:=" & strHandle)
Set gobjPage = gobjBrowser.Page("index:=0")
Set objDescription = Description.Create()
objDescription("Class Name").Value = "WebEdit"
objDescription("html tag").Value = "INPUT"
objDescription("name").Value =ObjName
objDescription("index").Value = index
gobjPage.WebEdit(objDescription).Set TestData
set gobjBrowser = nothing
Set gobjPage = nothing
End Sub

20. SaveAs Excel file with QTP

Set xl = CreateObject("Excel.Application")
xl.visible = True
xl.Application.Workbooks.open "C:\sai.xls"
xl.Worksheets(1).Activate
xl.Application.Visible = True
xl.Cells(1,1).Value = "mum"
xl.Cells(1,2).Value = "dad"
xl.activeworkbook.SaveAs("C:\sai1.xls")
xl.Application.Quit


Learn More On QTP Reusable Function creation codes :

QTP-reusable-functions-codes-5
QTP-reusable-functions-codes-4
QTP-reusable-functions-codes-3
QTP-reusable-functions-codes-2
QTP-reusable-functions-codes-1


For gaining more insights in the automation using QTP log on to below url :
Automation Testing Using QTP



QTP Reusable Functions Codes 3

QTP Reusable functions :


Automation testing using QTP has always been talked upon the most in the testing industry. There are numerous features available within this very toolset, but most of us might not be aware of this very feature which has been discussed in this very articles on automation testing using QTP which is functions created in Vbscript , and is very useful in code customization to meet our automation testing requirements , as it reduces the script maintenance effort..
 
1. BEEP from QTP

' Three methods of issuing a BEEP from QTP

' Method 1
Extern.Declare micLong,"MessageBeep","User32","MessageBeep",micLong
retVal = Extern.MessageBeep(&HFFFFFFFF)
MsgBox retVal 'The return value should be 1.

' Method 2
Err.Number = 0
On Error Resume Next
Extern.Declare micLong,"MessageBeep","User32","MessageBeep",micLong
Extern.MessageBeep(&HFFFFFFFF)
If (Err.Number <> 0) Then
MsgBox Err.Description
End If

' Method 3
Extern.Declare micLong,"Beep","Kernel32","Beep",micLong,micLong
retVal = Extern.Beep(1000,250) 'The first number is frequency the second is duration.

MsgBox extract_number("This user belongs to 10 groups")
MsgBox extract_number("206 features assigned to the user.")

2. Check for Required URL

startURL = "www.google.com" ' Amend this to your required URL

' If no browser open, open browser and navigate to required URL
If Not Browser("CreationTime:=0").Exist Then
   Call launch(startURL)
Else

' Get the URL of the current open browser
currentURL=Browser("CreationTime:=0").GetROProperty("OpenURL")
' If not correct URL navigate to required URL
If Not currentURL = "www.google.com" Then
   Call launch(startURL)
End If
End If

Function launch(startURL)
 ' Create IE object and navigate
 ' to required URL
 set IE = CreateObject("InternetExplorer.Application")
 IE.Visible = true
 IE.Navigate startURL
End function

3. Close QTP with QTP script

Private Function CloseQTP
   Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
   Set colProcess = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = 'QTPro.exe'")
   For Each objProcess in colProcess
    objProcess.Terminate()
   Next
   Set objWMIService = Nothing
   Set colProcess = Nothing
End Function

4. Open any Appllication through QTP

   ' Function OpenApp
   ' ------------------
   ' Open a specified application
   ' Parameter: application - the application full name (including location)
   '@Description Opens an application
   '@Documentation Open the application.

   Function OpenApp (application)
     systemUtil.Run application
    End Function

5. Adding any information to QTP Results

   ' AddToTestResults
   ' --------------
   ' Add a Report.Event step to the Test Results
   'Parameters:
   ' status - Step status (micPass, micFail, micDone or micWarning)
   ' StepName - Name of the intended step in the report (object name)
   ' details - Description of the report event    '
   '@Description Reports an event to the Test Results
   '@Documentation Report an event to the Test Results.

   Public Function AddToTestResults (status, StepName, details)
       Reporter.ReportEvent status, StepName, details
   End Function

6. Enable Doubleclick Event in QTP

Enable the ondblclick event in the Web Event Recording Configuration

To enable special event handling, use the Web Event Recording Configuration utility.
1. Go to Tools -> Web Event Recording Configuration.
2. Click .
3. Expand the Standard Objects branch.
4. Select the object you want to configure.
5. Go to Event -> Add -> ondblclick. The event will be added to the list on the right.
6. Select "If Handler" in the Listen column.
7. Select "Enabled" in the Record column.
8. Click to close the dialogs.

7. DSN - Less Connection

Public sconn
uid = "UID"
pwd = "PWD"
ServerName = "Server Name"

Connection()

Function Connection()
Set sconn = CreateObject("ADODB.connection")
sconn.Open "Driver=Microsoft ODBC for Oracle;Server="& ServerName &";Uid="& uid &";Pwd="& pwd &""
End Function

8. High-Level Automation Framework Information

At a very high level the framework components can be divided into two categories software part and documentation part. Here is my list of components ? you can add your item if anything is missing.

---------------------------------------------
All software code part
---------------------------------------------
Supporting libraries for Logging, error handling, Execution management
1. Tool specific code
2. Setup and configuration scripts
3. Test management code
4. Test data and Test data management code
5. Platform/OS specific scripts

---------------------------------------------
Non software part
---------------------------------------------
Folder structure
Documents
i. Coding guidelines
ii. Procedure for creating scripts
iii. Planning, design and review procedures
iv. Approach for automation
v. Approach for Testing automation code
vi. Automation documentation - how scripts work
vii. Setup and implementation procedures
viii. Defect tracking procedure for Automation scripts
ix. Source control procedures
x. Project plan
xi. Templates for effort estimation
xii. Template for test case categorization
xiii. Template for ROI calculation

9. Get Input Parameter Data and Use in Script

Set qtApp = CreateObject("QuickTest.Application") ' Create the Application object
Set pDefColl = qtApp.Test.ParameterDefinitions
Set pDef = pDefColl.Item(1)
MsgBox pDef.DefaultValue

10. Pass Test Data from MQC to QTP?

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

11. Get the Attachement from QC to local machine

To get attachment from test

Public Function GetTestAttachmentPath(TDAttachmentName) 'Returns File Path
'Test Director TDAPIOLELib object variables
Dim otaAttachmentFactory 'As TDAPIOLELib.AttachmentFactory
Dim otaAttachment 'As TDAPIOLELib.Attachment
Dim otaAttachmentList 'As TDAPIOLELib.List
Dim otaAttachmentFilter 'As TDAPIOLELib.TDFilter
Dim otaExtendedStorage 'As TDAPIOLELib.ExtendedStorage
Dim strPath 'As String

Set otaAttachmentFactory = QCUtil.CurrentTest.Attachments
Set otaAttachmentFilter = otaAttachmentFactory.Filter
otaAttachmentFilter.Filter("CR_REFERENCE") = "'TEST_" & QCUtil.CurrentTest.Id & "_" & TDAttachmentName & "'"
Set otaAttachmentList = otaAttachmentFilter.NewList
If otaAttachmentList.Count = 1 Then
Set otaAttachment = otaAttachmentList.Item(1)
otaAttachment.Load True, ""
strPath = otaAttachment.FileName
ElseIf otaAttachmentList.Count > 1 Then
Reporter.ReportEvent micFail, "Failure in library function 'GetTestAttachmentPath'", _ "Found more than one attachment '" & TDAttachmentName & "' in test '" & _ QCUtil.CurrentTest.Name & "'."
strPath = ""
ElseIf otaAttachmentList.Count < 1 Then
Reporter.ReportEvent micFail, "Failure in library function 'GetTestAttachmentPath'", _ "Found 0 attachments '" & TDAttachmentName & "' in test '" & _ QCUtil.CurrentTest.Name & "'."
strPath = ""
End If

GetTestAttachmentPath = strPath
Set otaAttachmentFactory = Nothing
Set otaAttachment = Nothing
Set otaAttachmentList = Nothing
Set otaAttachmentFilter = Nothing

End Function

To get attachment from folder

Public Function GetFolderAttachmentPath(TDAttachmentName, TDFolderPath) 'Returns File Path

'Test Director TDAPIOLELib object variables
Dim otaAttachmentFactory 'As TDAPIOLELib.AttachmentFactory
Dim otaAttachment 'As TDAPIOLELib.Attachment
Dim otaAttachmentList 'As TDAPIOLELib.List
Dim otaAttachmentFilter 'As TDAPIOLELib.TDFilter
Dim otaTreeManager 'As TDAPIOLELib.TreeManager
Dim otaSysTreeNode 'As TDAPIOLELib.SysTreeNode
Dim otaExtendedStorage 'As TDAPIOLELib.TreeManager
Dim intNdId
Dim strPath 'As String
Set otaTreeManager = QCUtil.TDConnection.TreeManager
Set otaSysTreeNode = otaTreeManager.NodeByPath(TDFolderPath)
Set otaAttachmentFactory = otaSysTreeNode.Attachments
Set otaAttachmentFilter = otaAttachmentFactory.Filter
intNdId = otaSysTreeNode.NodeID
otaAttachmentFilter.Filter("CR_REFERENCE") = "'ALL_LISTS_" & intNdId & "_" & TDAttachmentName & "'"
Set otaAttachmentList = otaAttachmentFilter.NewList
If otaAttachmentList.Count > 0 Then
Set otaAttachment = otaAttachmentList.Item(1)
otaAttachment.Load True, ""
strPath = otaAttachment.FileName
Else
Reporter.ReportEvent micFail,"Failure in library function 'GetFolderAttachmentPath'", _ "Failed to find attachment '" & TDAttachmentName & "' in folder '" & TDFolderPath & "'."
End If
GetFolderAttachmentPath = strPath
Set otaAttachmentFactory = Nothing
Set otaAttachment = Nothing
Set otaAttachmentList = Nothing
Set otaAttachmentFilter = Nothing
Set otaTreeManager = Nothing
Set otaSysTreeNode = Nothing

End Function




Learn More On QTP Reusable Function creation codes :

QTP-reusable-functions-codes-5
QTP-reusable-functions-codes-4
QTP-reusable-functions-codes-3
QTP-reusable-functions-codes-2
QTP-reusable-functions-codes-1


For gaining more insights in the automation using QTP log on to below url :
Automation Testing Using QTP

QTP Reusable Functions Codes 2

QTP Reusable function Codes :
Automation testing using QTP has always been talked upon the most in the testing industry. There are numerous features available within this very toolset, but most of us might not be aware of this very feature which has been discussed in this very articles on automation testing using QTP which is functions created in Vbscript , and is very useful in code customization to meet our automation testing requirements , as it reduces the script maintenance effort.

1. Getting Number from String

Function extract_number(msg)
   Dim re, matches, item, result
   Set re = New RegExp
   re.pattern = "[A-Za-z -.]*(\d+).*"
   Set matches = re.Execute(msg)
   If matches.Count > 0 Then
      Set item = matches(0)
      If item.SubMatches.Count > 0 Then
         result = item.SubMatches(0)
      Else
         result = -1
      End If
   Else
           result = -1
   End If
   extract_number = result
End Function

MsgBox extract_number("This user belongs to 10 groups")
MsgBox extract_number("206 features assigned to the user.")

2. Close All the opened Browsers Except QC opened browser

On Error Resume Next
Dim intWndCnt
Dim oDesc, oWnd
'Create Object description
Set oDesc = Description.Create '
Set oWnd = Desktop.ChildObjects(oDesc)
intWndCnt = oWnd.Count
For i = 0 to intWndCnt - 1
Set TmpObj = oWnd.item(i)
strTmpTitle = oWnd.item(i).GetROProperty("Text")
If instr(1,strTmpTitle, "Microsoft Internet Explorer",1) > 0 Then
   If instr(1,strTmpTitle, "Mercury Quality Center",1) > 0 Then
       'msgbox "Title :" & oWnd.item(i).GetROProperty("Text")
   Else
       'msgbox "Close :" & oWnd.item(i).GetROProperty("Text")
       oWnd.item(i).close
   End if
End If
Next
'Clean up
Set oDesc = nothing
Set oWnd = nothing

3. Close all opened Excel files

Public Function fn_close_all_excel_files()
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = 'EXCEL.EXE'")
For Each objProcess in colProcessList
   objProcess.Terminate()
Next
End Function

4. Excel sheet column count

Public Function dtGetColCount (sSheetName)
   On Error Resume Next
   Do
   i = i + 1
   sColName = DataTable.GetSheet(sSheetName).GetParameter(i).Name
   Loop While 0 = Err.Number
   'GetParameter throws an error when using an index that is out of bounds ...
   'We can use this functionality to ASSUME that it's an unused column.
   'We've come to the end of our USED columns
   dtGetColCount = i - 1
   On Error GoTo 0
End Function

5. Count Number of files in any Folder

iFileCount = 0
Set objFileSysOb = CreateObject("Scripting.FileSystemObject")
Set colFolderName = objFileSysOb.GetFolder("C:\Automation") ' Folder Path
Set vFiles =colFolderName.Files
For each vFileItem in vFiles
   print vFileItem
   iFileCount = iFileCount + 1
Next
print iFileCount

6. Create Dynamic Array

For i = 0 to 20
   Redim Preserve arrFileLines(i)
   arrFileLines(i) = "test" & i
Next

7. Close Dialog box

Function DialogClose (obj)
If obj.Dialog("nativeclass:=#32770").Exist(0) Then
   obj.Dialog("nativeclass:=#32770").WinButton("nativeclass:=Button","index:=0").Click
End If
RegisterUserFunc "Browser", "DialogClose", "DialogClose"
End Function

8. Create Dynamic Value

iDynamicValue = now
iDynamicValue = replace(iDynamicValue,"/","")
iDynamicValue = replace(iDynamicValue,":","")
iDynamicValue = replace(iDynamicValue," ","")
iDynamicValue = replace(iDynamicValue,"PM","")
iDynamicValue = replace(iDynamicValue,"AM","")
msgbox iDynamicValue

9. Get QTP file path

Set qtApp = CreateObject("QuickTest.Application") ' Create the Application objectqtpApp.Test.Location
TestLoc = qtApp.Test.Location
MsgBox TestLoc

10. IS QC Connected?

Set qtApp = CreateObject("QuickTest.Application")
If qtApp.TDConnection.IsConnected Then
   msgbox "QC"
Else
   msgbox "Local"
End If

(or)

if QCUtil.IsConnected then
   Reporter.ReportEvent 0, "Connected", "Connected to server: " + QCUtil.QCConnection.ServerName + chr (13) +"Project: " +
   QCUtil.QCConnection.ProjectName + chr (13) + "Domain: " + QCUtil.QCConnection.DomainName
else
   Reporter.ReportEvent 1, "Not connected", "Not connected to Quality Center"
end if

11. Keyboard Key Press through QTP Script

'Create Shell Object
Set WshShell = CreateObject("WScript.Shell")
'Send any Functinal Keys
' ALT = %
' F4 = {F4}
WshShell.SendKeys "%{F4}"
' Set shell object to Null
Set WshShell=nothing

12. QTP9.0 Futurs

- Open and edit multiple Object Repositories
- Easy conversion to/from XML
- Multiple object repositories per test asset
- Leveraging the automation assets across multiple groups
- Missing resources panel
- Pass parameters between Actions





Learn More On QTP Reusable Function creation codes :

QTP-reusable-functions-codes-5
QTP-reusable-functions-codes-4
QTP-reusable-functions-codes-3
QTP-reusable-functions-codes-2
QTP-reusable-functions-codes-1


For gaining more insights in the automation using QTP log on to below url :
Automation Testing Using QTP

QTP Reusable Functions Codes

Automation testing using QTP has always been talked upon the most in the testing industry. There are numerous features available within this very toolset, but most of us might not be aware of this very feature which has been discussed in this very articles on automation testing using QTP which is functions created in Vbscript , and is very useful in code customization to meet our automation testing requirements , as it reduces the script maintenance effort.


1. Action Template 

If you need any default Template to be loaded whenever you create a new Action, just follow these steps.

  1. Design the template with all the statements and comments in a text file.
  2. Save the text file as "ActionTemplate.mst" to the "QuickTest Installation Folder" under \dat folder.
  3. Start QTP and whenever you create new Actions, you can find the template by default.

2. ADO Connection Function - Open the ADO connection through QTP

Public Function BIP_sqlDBConnect(sConnectionStr)
   ' Create the Connection Object.
   Set objADOConnection = CreateObject("ADODB.Connection")
   ' Set the Connection String.
   objADOConnection.Open (sConnectionStr)
   'ReturnADO object reference
   Set BIP_sqlDBConnect = objADOConnection
End Function

3. Close QTP - Closing the QTP after Execution

Private Function CloseQTP
   Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
   Set colProcess = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = 'QTPro.exe'")
   For Each objProcess in colProcess
   objProcess.Terminate()
   Next
   Set objWMIService = Nothing
   Set colProcess = Nothing
End Function

4. Open Application

' Open a specified application
' Parameter: application - the application full name (including location)
'@Description Opens an application
'@Documentation Open the application.

Function OpenApp (application)
   systemUtil.Run application
End Function

5. Add Test Results

' Add a Report.Event step to the Test Results
'Parameters:
' status - Step status (micPass, micFail, micDone or micWarning)
' StepName - Name of the intended step in the report (object name)
' details - Description of the report event
'@Description Reports an event to the Test Results
'@Documentation Report an event to the Test Results.

Public Function AddToTestResults (status, StepName, details)
   Reporter.ReportEvent status, StepName, details
End Function

6. Verify Object Is Enabled

' Add a Report.Event step to the Test Results
'Parameters:
' status - Step status (micPass, micFail, micDone or micWarning)
' StepName - Name of the intended step in the report (object name)
' details - Description of the report event
'@Description Reports an event to the Test Results
'@Documentation Report an event to the Test Results.

Public Function VerifyEnabled (obj)
   Dim enable_property
   'Get the enabled property from the test object
   enable_property = obj.GetROProperty("enabled")
   If enable_property <> 0 Then ' The value is True (anything but 0)
     Reporter.ReportEvent micPass, "VerifyEnabled Succeeded", "The test object is enabled"
     VerifyEnabled = True
   Else
     Reporter.ReportEvent micFail, "VerifyEnabled Failed", "The test object is NOT enabled"
     VerifyEnabled = False
   End If
End Function

7. Verify Object Is Disabled

' Add a Report.Event step to the Test Results
'Parameters:
' status - Step status (micPass, micFail, micDone or micWarning)
' StepName - Name of the intended step in the report (object name)
' details - Description of the report event
'@Description Reports an event to the Test Results
'@Documentation Report an event to the Test Results.

Public Function VerifyDisabled (obj)
   Dim enable_property
   'Get the enabled property from the test object
   enable_property = obj.GetROProperty("disabled")
   If enable_property = 0 Then ' The value is False (0) - Enabled
     Reporter.ReportEvent micPass, "VerifyDisabled Succeeded", "The test object is enabled"
     VerifyDisabled = True
   Else
     Reporter.ReportEvent micFail, "VerifyDisabled Failed", "The test object is NOT enabled"
     VerifyDisabled = False
   End If
End Function

8. Get Value Property

' Return the object 'Value' property
'@Description Returns the Object value
'@Documentation Return the 'Test object name' 'test object type' value.

Public Function GetValueProperty (obj)
   GetValueProperty = obj.GetROProperty("value")
End Function

9. Get Text Property

' Return the object 'Text' property
'@Description Returns the Object value
'@Documentation Return the 'Test object name' 'test object type' value.

Public Function GetTextProperty (obj)
   GetTextProperty = obj.GetROProperty("text")
End Function

10. Get Position Property

' Return the object 'position' property
'@Description Returns the Object value
'@Documentation Return the 'Test object name' 'test object type' value.

Public Function GetPositionProperty (obj)
   GetPositionProperty = obj.GetROProperty("position")
End Function

11. Get Selection Property

' Return the object 'selection' property
'@Description Returns the Object value
'@Documentation Return the 'Test object name' 'test object type' value.

Public Function GetSelectionProperty (obj)
   GetSelectionProperty = obj.GetROProperty("selection")
End Function

12. Get Checked Property

' Return the object 'checked' property
'@Description Returns the Object value
'@Documentation Return the 'Test object name' 'test object type' value.

Public Function GetCheckedProperty (obj)
   GetCheckedProperty = obj.GetROProperty("checked")
End Function



Learn More On QTP Reusable Function creation codes :

QTP-reusable-functions-codes-5
QTP-reusable-functions-codes-4
QTP-reusable-functions-codes-3
QTP-reusable-functions-codes-2
QTP-reusable-functions-codes-1


For gaining more insights in the automation using QTP log on to below url :
Automation Testing Using QTP


Vbscript Coding In QTP

Vbscript Coding In QTP


In the below article we will discuss the following topics related to the VBScripting in QTP.
  1. While .. Wend Looping In QTP.
  2. For ...Loop Handling In QTP VBScript.
  3. If ...End If Handling in VBScript in QTP.
  4. Usage of For...Each Loop in QTP Vbscripting.
  5. ChildObjects in QTP.
  6. LoadAndRunAction method.
  7. ReDimUsage in Vbscripting QTP.
  8. SystemUtil Usage in VbScripting  QTP.
  9. ExecQuery
  10. IE.Terminate()
  11. Associated library :
  12. Action Code :
  13. The LoadAndRunAction method allows calling any Action for Local system or Quality center at run-time.


Regular Expression in VBScript in QTP :
 
Dim text
text = ""

Dim rgx
Set rgx = New RegExp
rgx.IgnoreCase = True
rgx.Global = True
rgx.Pattern = "([A-Za-z]{3,9})://([-;:&=\+\$,\w]+@{1})?([-A-Za-z0-9\.]+)+:?(\d+)?((/[-\+~%/\.\w]+)?\??([-\+=&;%@\.\w]+)?#?([\w]+)?)?"

Dim match, matches
Set matches = rgx.Execute(text)
For Each match in matches
  MsgBox match.Value, 0, "Found Match"
Next

'Launch a notepad window :
 
SystemUtil.Run "notepad.exe"
 
'Close the window just launched using the exact title :

SystemUtil.CloseProcessByWndTitle "Untitled - Notepad"
 
'Launch a notepad window
SystemUtil.Run "notepad.exe"
 
'Close the window just launched using a pattern string
SystemUtil.CloseProcessByWndTitle ".*Notepad", True
 
SystemUtil.CloseDescendentProcesses
 
CloseDescendentProcesses can be used to close any process launched by QTP. The code below illustrates the usage
 
'Launch explorer
SystemUtil.Run "iexplore.exe"
 
'Launch excel using COM
Set oXL = CreateObject("Excel.Application")
oXL.Visible = True
 
'Close processes launched by QTP. This will close
'the internet explorer and Excel as well
SystemUtil.CloseDescendentProcesses

While Browser("creationtime:=0").Exist(0)
 
    'Close the browser
    Browser("creationtime:=0").Close
 
Wend

'Create a description for browser
Set oBrowser = Description.Create
oBrowser("micclass").Value = "Browser"
 
Set oPage = Description.Create
oPage("micclass").Value = "Page"
 
'Get all browsers
Set allBrowser = Desktop.ChildObjects(oBrowser)
 
Dim i, iCount
 
iCount = allBrowser.Count - 1
 
For i = 0 To iCount
    'Get the page object from the browser
    Set oPg = allBrowser(i).ChildObjects(oPage)(0)
 
    'Get the URL of the
    If InStr(oPg.GetROProperty("title"), "Quality Center", vbTextCompare) = 0 Then
        'Close the browser
        allBrowser(i).Close
    End If
Next
 
By now you must be wondering about the line
 
'Get the page object from the browser
Set oPg = allBrowser(i).ChildObjects(oPage)(0)

'Name/IP of the computer
sComp = "."
 
'Get the WMI object
Set WMI = GetObject("winmgmts:\\" & sComp & "\root\cimv2")
 
'Get collection of processes for with name iexplore.exe
Set allIE = WMI.ExecQuery("Select * from Win32_Process Where Name = 'iexplore.exe'")
 
'Loop through each process and terminate it
For Each IE in allIE
    IE.Terminate()
Next

'Create the shell application object
Set shlApp = CreateObject("Shell.Application")
 
'Get all open windows collection
Set allWins = shlApp.Windows
 
'Loop through each window and close if IE
For Each window In allWins
    If InStr(window.fullName, "iexplore.exe") Then
        'Close the IE window
        window.Quit
    End If
Next

Dim windows2Close
 
'Initialize with negative upper bound
ReDim windows2Close( -1)
 
'Create the shell application object
Set shlApp = CreateObject("Shell.Application")
 
'Get all open windows collection
Set allWins = shlApp.Windows
 
'Loop through each window and close if IE
For Each window In allWins
    'Close all IE windows but ignore Quality Center
    If InStr(window.fullName, "iexplore.exe") And InStr(Window.LocationURL, "/qcbin/") = 0 Then
 
        'Increase the array size by 1
        ReDim Preserve windows2Close(UBound(windows2Close) + 1)
 
        Set windows2Close(UBound(windows2Close)) = Window
    End If
Next
 
'Loop through all array elements and close each window
For Each Window In windows2Close
    Window.Quit
Next
WebUtil.DeleteCookies()
Function DeleteIECookies()
    Set oWebUtil = CreateObject("Mercury.GUI_WebUtil")
    oWebUtil.DeleteCookies()
End Function
Function DeleteFFCookies()
    Dim FSO, cookiePath
    Set FSO = CreateObject("Scripting.FileSystemObject")
 
    cookiePath = GetFFCookiesPath()
 
    If FSO.FileExists(cookiePath) Then FSO.DeleteFile cookiePath
 
End Function
Function GetFFCookiesPath()
                    Dim FSO, oShell
                    Set FSO = CreateObject("Scripting.FileSystemObject")
                    Set oShell = CreateObject("WScript.Shell")
 
                    If InStr(Environment("OS"),"Vista") Then
                                         Dim sUserProf
                                         sUserProf = oShell.ExpandEnvironmentStrings("%USERPROFILE%") & "\AppData\Roaming\Mozilla\Firefox\Profiles"
                                         GetFFCookiesPath = ""
 
                                         If FSO.FolderExists(sUserProf)  Then
                                           Set oFolder =  FSO.GetFolder(sUserProf)
                                           If oFolder.SubFolders.Count> 0 Then
 
                                                             'oFolder.item(0) throws an error, so we use a workaround to find the first folder                
                                                             For each oFolder in oFolder.SubFolders
                                                                                 Exit For
                                                             Next
                                                             'Set oFolder = oFolder.item(0)
                                                             Dim sPath
                                                             sPath = oFolder.Path
 
                                                             If FSO.FileExists(sPath & "\Cookies.txt") Then
                                                               GetFFCookiesPath = sPath & "\Cookies.txt"
                                                             End If
                                           End If
                                         End If
                    Else
                                         Err.raise vbObjectError + 1, "GetFFCookiesPath", "This function has not yet been implemented for your OS - " & Environment("OS") 
                    End if
End Function
Function Login(username, password)
                    oUserTxt.Set username
                    oUserPwd.Set Ucase(password)
                    oLogin.Click
End Function
ExecuteFile PathFinder.Locate("LoginUpdate.vbs")
 
Associated library :

Function NewMsgBox(Message)
                    Print "The user says – " & Message
End Function

Dim fnPtrNewMsgBox
Set fnPtrNewMsgBox = GetRef("NewMsgBox")

Action Code :

Dim MsgBox

Set MsgBox = fnPtrNewMsgBox

Msgbox "Tarun"

The advantage of this approach is that we can use the original MsgBox function as well in the NewMsgBox method which was not possible with the earlier approach
orkaround to that I decided to use a new ActualParams objects. So the Library was updated as
Dim ActualParams

'By default we will use the component parameters
Set ActualParams = Parameter

Function App_Login()
                    Browser("X").Page("X").WebEdit("UserName").Set ActualParams("UserName")
                    Browser("X").Page("X").WebEdit("Password").Set ActualParams("Password")
                    Browser("X").Page("X").WebButton("Login").Click
End Function
Now I can use the function as below in my component
'Call with component parameter
Call App_Login

Dim DummyParams
Set DummyParams = CreateObject("Scripting.Dictionary")
DummyParams("UserName") = "Tarun"
DummyParams("Password") = "Tarun" ' Do remember that password field should be first encrypted

'Set the Actual parameters be used in Function as DummyParams
Set ActualParams = DummyParams
Call App_Login

'Rest of the functions to use the component parameters
Set ActualParams = Parameter

The LoadAndRunAction method allows calling any Action for Local system or Quality center at run-time.

LoadAndRunAction(TestPath, ActionName, [Iteration], [Parameters])
'Get the Test type
TestType = DataTable.Value("TestType",dtGlobalSheet)

'Load and call the Action
LoadAndRunAction "C:\Framework\Tests\Actions", TestType