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 file. Show all posts
Showing posts with label file. Show all posts

File system handling using Vbscript in QTP


File system handling using Vbscript in QTP is another example of AOM model that is utilized to suit our needs to write logs especially to generate the customized result files. Scripting.Filesystem object is the claas which is utilized to cater to the needs of the object creation and hence its property access.

How to Create a new text file ?
How to Check if a specific file exist ?
How to write data to a file ?
How to Read line from file ?
How to Read Entire Text file ?

How to Close an open file ?
How to Open a specified file and returns an object that can be used to read from, write to, or append to the file ?
How to Copy a file ?
How to Delete a file ?
How to Create a Folder if it does not Exists ?
How to Count Number of Lines in file ?
dim objFso
' creating the file system object
set objFso = CreateObject ("Scripting.FileSystemObject")

' Create a new txt file

' Parameters:
' FilePath - location of the file and its name

Function CreateFile (StrFilePath)

   ' variable that will hold the new file object
   dim NewFile
   ' create the new text File
   set NewFile = objFso.CreateTextFile(StrFilePath, True)
   set CreateFile = NewFile
End Function

' Check if a specific file exist

' Parameters:
' FilePath - location of the file and its name

Function CheckFileExists (StrFilePath)

   ' check if file exist
   CheckFileExists = objFso.FileExists(StrFilePath)
End Function

' Write data to file

' Parameters:
' FileRef - reference to the file
' str - data to be written to the file

Function WriteToFile (byref FileRef,str)

   ' write str to the text file
   FileRef.WriteLine(str)
End Function

' Read line from file

' Parameters:
' FileRef - reference to the file

Function ReadLineFromFile (byref FileRef)

   ' read line from text file
   ReadLineFromFile = FileRef.ReadLine
End Function

' Read Entire Text File Test

' Parameters:
' FileRef - reference to the file

Function ReadTextFileTest(StrFilePath)

   Const ForReading = 1, ForWriting = 2, ForAppending = 8
   Dim fso, f, Msg
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile(StrFilePath, ForReading)
   ReadTextFileTest = f.Readall()
End Function

' Closes an open file.

' Parameters:
' FileRef - reference to the file

Function CloseFile (byref FileRef)

   FileRef.close
End Function

' Opens a specified file and returns an object that can be used to read from, write to, or append to the file.

' Parameters:
' FilePath - location of the file and its name
' mode options are:
' ForReading - 1
' ForWriting - 2
' ForAppending - 8

Function OpenFile (StrFilePath,mode)

   ' open the txt file and retunr the File object
   set OpenFile = objFso.OpenTextFile(StrFilePath, mode, True)
End Function

' Copy file.

' Parameters:
' FileRef - reference to the file

Sub FileCopy ( StrFilePathSource,StrFilePathDest)

   ' copy source file to destination file
   objFso.CopyFile StrFilePathSource, StrFilePathDest
End Function

' Delete a file.

' Parameters:
' FileRef - reference to the file

Sub FileDelete ( StrFilePath)
   ' copy source file to destination file
   objFso.DeleteFile ( StrFilePath)
End Function

' Create Folder if Not Exists.

Function ReportFolderStatus(fldr)

   Dim fso, msg
   Set fso = CreateObject("Scripting.FileSystemObject")
   If Not (fso.FolderExists(fldr)) Then
   Set f = fso.CreateFolder(fldr)
   End If
End Function

ReportFolderStatus("C:\Viplav")

' Count Number of Lines in txt file

Function NumberOfLines(FileName)

   i = 0
   Set objFSO = CreateObject("Scripting.FileSystemObject")
   Set objTextFile = objFSO.OpenTextFile(FileName, ForReading)
   Do Until objTextFile.AtEndOfStream
   Redim Preserve arrFileLines(i)
   arrFileLines(i) = objTextFile.ReadLine
   i = i +1
   Loop
   NumberOfLines = UBound(arrFileLines)
   objTextFile.Close
End Function

msgbox NumberOfLines("C:\Viplav\myfile.txt")




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

Automation Testing with QTP

Description:   ''This example starts QuickTest, opens a new test, and adds a new action, which calls a second action.Then it edits the first action's script to move the call to the second action to a new position in the script,validates the syntax of the new script, defines some action parameters, and uploads the modified action script.”

Dim qtApp, ActionContent, ActionName, ActionDescr, NewAction, SecondAction, script

Below line of code creates an object of the Class Application for the QuickTest Software
Set qtApp = CreateObject("QuickTest.Application") ' Create the application object
qtApp.Launch
qtApp.Visible = True
qtApp.New
 In the above line of code just the environment is getting created and then on we can start with the scenarios. qtApp is the instance of the QTP that will be used.

ActionContent = "Window(""Calculator"").WinButton(""1"").Click" & vbCrLf & "Window(""Calculator"").WinButton(""+"").Click" & vbCrLf & "Window(""Calculator"").WinButton(""+"").Click" & vbCrLf & "Window(""Calculator"").WinButton(""="").Click"
ActionDescr = "A new sample action for the test."
ActionName = "Action" + CStr(qtApp.Test.Actions.Count + 1)

CStr is a vbscript function that is used to change any content into string.

Add a new action at the beginning of the test
Set NewAction = qtApp.Test.AddNewAction(ActionName, ActionDescr, ActionContent, False, qtAtBegining)

Here what is being done is instance of the QTP application is availed in qtApp variable as initialized above and in that instance a class named Test which is actually automated Project name in the current context, and then on we add a method name which is different from a function “AddNewAction” : It can be termed as a set of events that may be used by some other events within the project.

Do remember that in oreder to make an Action to be reusable the property must be assigned as reusable, also in case we want to call it from outside the current project, it needs to be defined as Global which has also been discussed in prior posts.

What we do here is Add another action and call it from the beginning of the action that was just added above.

ActionContent = "Function f1(str)" & vbCrLf & vbTab & "msgbox str" & vbCrLf & "End Function"
ActionName = "Action" + CStr(qtApp.Test.Actions.Count + 1)

Set SecondAction = NewAction.AddNewAction(ActionName, ActionDescr, ActionContent, True, qtAtBegining)
qtApp.Test.AddNewAction was used in the previous action creation code.
NewAction.AddNewAction is being used in this very action creation code.

Now we will be using  the Load Script function to store the content of the first new action into the script array
script = Load_Script(NewAction.GetScript())
script = Move_CallAction(script, SecondAction.Name, UBound(script))
ActionContent = Save_Script(script)
scriptError = NewAction.ValidateScript(ActionContent)

'Converts script array to the text
'Sets new script source to the action
Load_Script, Move_CallAction, Save_Script  are user defined function as is availed below after some more logical coding.

Now the below code needs to be called
If Len(scriptError) = 0 Then
    NewAction.SetScript ActionContent
    NewAction.Description = "Check the calculator application and run next Action"
    NewAction.Type = "Reusable" 'Put Reusable type to the new action
    Set aParamDefs = NewAction.ActionParameterDefinitions
    aParamDefs.Add "InParam", "An input action parameter definition", 0, 0, "Input Value"        
    aParamDefs.Add "ResParam", "An output action parameter definition", 0, 1, "Output Value"
    Set resParamDef = aParamDefs.Item ("ResParam")
    resParamDef.Type = 1 'Put the boolean parameter type
    resParamDef.DefaultValue = false
    resParamDef.Description = "Result parameter"
Else
    Err.Raise E_SCRIPT_NOT_VALID, "Validate Script Error", scriptError
End If

Const E_SCRIPT_TABLE = 1
Const E_EMPTY_SCRIPT = 2
Const E_SCRIPT_NOT_VALID = 3

Const is the keyword available with VBScrip which can be used to assign values to variables that can not be overloaded with any other re initializations. Generally we use it in Sheet names and other environment variable names.
·         Public Function Load_Script(src)
If Len(src) = 0 Then
Err.Raise E_SCRIPT_TABLE, "Load_Script", "Script is empty"
End If
Load_Script = Split(Trim(src), vbCrLf)
·         End Function
Len is used to return the length of the string within the parameters. It is in built function with VbScript.
Split is another function name which is used to sub divide a string into individual elements based on separator mentioned [in this case vbcrlf ] and get it stored in an array format.
Trim is a yet another function which is used to remove any extra space that might be preceding or suffixing the string in this case src. Such as a string “  vip  ” string becomes trim(“  vip  ”) as “vip”.
We do have Ltrim & Rtrim functions to remove spaces only from left side or right side, ahich can be used as suits our requirement.
·         Public Function Save_Script(script)
If Not IsArray(script) Then
Err.Raise E_SCRIPT_TABLE, "Save_Script", "Script should be string array"
End If
If UBound(script) - LBound(script) = 0 Then
Err.Raise E_SCRIPT_TABLE, "Save_Script", "Script is empty"
End If
Save_Script = Join(script, vbCrLf)
·         End Function

IsArray is a function that checks if the parameter within braces is an array or not, an according returns as true or false which is VbScript is denoted as 1 or 0. 
UBound and Lbound gives the boundary value of the array index to which the resulting array from the string broken up results. Suppose the array size after string split is 78, then Lbound is 0 and UBound is 77.
Join as the name suggests joins the two strng just like a concatenation operator.

Find_Line, Move_Line,Insert_Line,Delete_Line are some of the functions which will help us demonstrate our conceptual clarity to play with QTP and make ourselves empowered to create any automated testing execution flow with ease, with perfection.
·         Public Function Find_Line(script, criteria)
Dim rExp, I
'Verify that the first argument contains a string array
If Not IsArray(script) Then
Err.Raise E_SCRIPT_TABLE, "Find_Line", "The script should be a string array"
End If
Set rExp = New RegExp
ptrn = ""
If IsArray(criteria) Then
ptrn = Join(criteria, " * ")
Else
ptrn = criteria
End If
rExp.Pattern = ptrn 'Set pattern string
rExp.IgnoreCase = True ' Set case insensitivity.
rExp.Global = True ' Set global applicability.
I = 0
For Each scrItem In script
If rExp.Execute(scrItem).Count > 0 Then
Find_Line = I
Exit Function
End If
I = I + 1
Next
Find_Line = -1
·         End Function

Find_Line  is a function that has a certain return type. We have two types of methods which is of profound interest to our requirement , one being the SubRoutine, and the other being Function . The only difference being that the SubRoutine has no return type and has the keyword Sub prefixed, and the latter Function has the keyword Function associated to it, and has some return values associated with it. In this case the return type being the value 0 or 1 in accordance with the code execution.
Having already discussed about IsArray & join we do not need to revisit it here .
For each Next block is something that is used as a looping control block to execute some loop for our business requirement or in this case just to visit to each index within the array.
Regular expression is something new we have come to in this very code block. It is used to create some sort of pattern matching for our requirements to be addressed with ease. For simple context suppose in a website we have to fill in an e-mail id, so there needs a validation to be performed as to whether the entered e-mail id is in correct format or not. A sort of pattern matching is needed in this context. The same is being done when we do in above code block.
New RegExp is the instantiation of the regular expression that is used to be met.

For each scrItem in Script means that for each index value in the array Script we have some looping that occurs, and the code is indeed self descriptive enough to us.

ExitFunction is the keyword that is used to exit from the execution of the Function block as and whne such condition is met. Similar is the use of ExitFor, ExitIf,ExitWhile.

·         Public Function Move_Line(script, curPos, newPos)
'Verify that the first argument contains a string array
If Not IsArray(script) Then
Err.Raise E_SCRIPT_TABLE, "Move_Line", "Script should be string array"
End If
scrLen = UBound(script) - LBound(script)
If curPos = newPos Or curPos < 0 Or newPos < 0 Or scrLen < curPos Or scrLen < newPos Then
Move_Line = script
Exit Function
End If
tmpLine = script(curPos)
If newPos > curPos Then
For curPos = curPos + 1 To scrLen
script(curPos - 1) = script(curPos)
If curPos = newPos Then
script(curPos) = tmpLine
Exit For
End If
Next
Else
For curPos = curPos - 1 To 0 Step -1
script(curPos + 1) = script(curPos)
If curPos = newPos Then
script(curPos) = tmpLine
Exit For
End If
Next
End If
Move_Line = script
·         End Function

In the function Block Move_Line , we have just reused the functions that were used in the previous function and introduced some new keywords which work in accordance with what we discussed earlier, such For Next loop , If Else condition block, For next with negative iteration as well by using the Keyword Step-1 to customize a back loop with 1 decrement, same can be altered by step-2 and so on and so forth. One binary operator is used “OR” which is same as we might have had acquaintance in the Digital Circuit Gate circuit creation. It equate to true if at least one condition evaluates to TRUE. We have similar Keyword available in AND wherein both needs to be TRUE to make the evaluation return the value as TRUE.

·         Function Insert_Line(script, lineSrc, linePos)
'Verify that the first argument contains a string array
If Not IsArray(script) Then
Err.Raise E_SCRIPT_TABLE, "Insert_Line", "Script should be string array"
End If
scrLen = UBound(script) - LBound(script)
If (scrLen = 0 And linePos <> 0) Or (linePos > scrLen + 1) Then
Insert_Line = script
Exit Function
End If
newScript = Split(String(scrLen + 1, " "), " ")
shiftIndex = 0
For I = 0 To scrLen + 1
If linePos = I Then
newScript(I) = lineSrc
shiftIndex = 1
Else
newScript(I) = script(I + shiftIndex)
End If
Next
Insert_Line = newScript
·         End Function
In the function above for Insert_Line we do not have much of an indifference to the prior code except for the introduction of the operator Not Equal to which is symbolically represented as “<>”.

·         Function Delete_Line(script, linePos)
'Verify that the first argument contains a string array
If Not IsArray(script) Then
Err.Raise E_SCRIPT_TABLE, "Delete_Line", "Script should be string array"
End If
scrLen = UBound(script) - LBound(script)
If (scrLen = 0) Or (linePos > scrLen) Then
Insert_Line = script
Exit Function
End If
If scrLen = 1 Then
Delete_Line = Array()
Exit Function
End If
newScript = Split(String(scrLen - 1, " "), " ")
shiftIndex = 0
For I = 0 To scrLen
If linePos = I Then
shiftIndex = 1
Else
newScript(I - shiftIndex) = script(I)
End If
Next
Delete_Line = newScript
·         End Function
Similar is the code creation as has been already discussed , with nothing new coming into picture. Split is being done for the string, and the separator in this case is blank space.

·         Public Function Move_CallAction(script, actName, newPos)
curPos = Find_Line(script, Array("RunAction", """" & actName & """"))
Move_CallAction = Move_Line(script, curPos, newPos)
·         End Function

Move_CallAction is the main controller within this module as is clearly visible from the above code block. Having read through the complete article carefully and patiencely anyone could have figured out how the control flow can be regulated. I hope the code is self explanatory and at times I have chipped in with some comments which can be definitely understood without much of a hara kiri.

Coded UI Automation Testing Walkthrough : Data Parameterization from CSV File

Now we will externalize data from a csv file in the following unit. Just create a csv file using excel sheet as is mentioned below. Though the file location is not at all a point of concern, yet we can avoid the same by keeping it in the project directory itself just in case the same project needs to be run from some other machine, the debug still works well.


Some Related posts on Coded UI Testing using VSTS :
 





Yeah we have created a csv file and have linked it up from the CodedUiTest file, via Test view. Right click to click its properies and follow up.








Now the automated script has been data driven in the true sense , and now if you change the userid and password in the csv file, the script will log you into the respective accounts.

QTP File System Operations


I) Working with Drives and Folders

a) Creating a Folder

Option Explicit
Dim objFSO, objFolder, strDirectory
strDirectory = "D:\logs"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.CreateFolder(strDirectory)

b) Deleting a Folder

Set oFSO = CreateObject("Scripting.FileSystemObject")
oFSO.DeleteFolder("E:\FSO")

c) Copying Folders


Set oFSO=createobject("Scripting.Filesystemobject")
oFSO.CopyFolder "E:\gcr6", "C:\jvr", True
d) Checking weather the folder available or not, if not creating the folder
Option Explicit
Dim objFSO, objFolder, strDirectory
strDirectory = "D:\logs"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(strDirectory) Then
Set objFolder = objFSO.GetFolder(strDirectory)
msgbox strDirectory & " already created "
else
Set objFolder = objFSO.CreateFolder(strDirectory)
end if

e) Returning a collection of Disk Drives

Set oFSO = CreateObject("Scripting.FileSystemObject")
Set colDrives = oFSO.Drives
For Each oDrive in colDrives
MsgBox "Drive letter: " & oDrive.DriveLetter
Next

f) Getting available space on a Disk Drive


Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oDrive = oFSO.GetDrive("C:")
MsgBox "Available space: " & oDrive.AvailableSpace

II) Working with Flat Files
a) Creating a Flat File

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile("E:\ScriptLog.txt")

b) Checking weather the File is available or not, if not creating the File

strDirectory="E:\"
strFile="Scripting.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(strDirectory & strFile) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFile = objFSO.CreateTextFile("E:\ScriptLog.txt")
End if

c) Reading Data character by character from a Flat File
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("E:\gcr.txt", 1)
Do Until objFile.AtEndOfStream
strCharacters = objFile.Read(1)
msgbox strCharacters
Loop

d) Reading Data line by line from a Flat File


Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("E:\gcr.txt", 1)
Do Until objFile.AtEndOfStream
strCharacters = objFile.Readline
msgbox strCharacters
Loop

e) Reading data from a flat file and using in data driven testing


Dim fso,myfile
Set fso=createobject("scripting.filesystemobject")
Set myfile= fso.opentextfile ("F:\gcr.txt",1)
myfile.skipline
While myfile.atendofline <> True
x=myfile.readline
s=split (x, ",")
SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe","","C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\","open"
Dialog("Login").Activate
Dialog("Login").WinEdit("Agent Name:").Set s(0)
Dialog("Login").WinEdit("Password:").SetSecure s(1)
Dialog("Login").WinButton("OK").Click
Window("Flight Reservation").Close
Wend

f) Writing data to a text file

Dim Stuff, myFSO, WriteStuff, dateStamp
dateStamp = Date()
Stuff = "I am Preparing this script: " &dateStamp

Set myFSO = CreateObject("Scripting.FileSystemObject")
Set WriteStuff = myFSO.OpenTextFile("e:\gcr.txt", 8, True)
WriteStuff.WriteLine(Stuff)
WriteStuff.Close
SET WriteStuff = NOTHING
SET myFSO = NOTHING

g) Delete a text file

Set objFSO=createobject("Scripting.filesystemobject")
Set txtFilepath = objFSO.GetFile("E:\gcr.txt")
txtFilepath.Delete()

h) Checking weather the File is available or not, if available delete the File

strDirectory="E:\"
strFile="gcr.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(strDirectory & strFile) Then
Set objFile = objFSO.Getfile(strDirectory & strFile)
objFile.delete ()
End if

i) Comparing two text files

Dim f1, f2
f1="e:\gcr1.txt"
f2="e:\gcr2.txt"
Public Function CompareFiles (FilePath1, FilePath2)
Dim FS, File1, File2
Set FS = CreateObject("Scripting.FileSystemObject")

If FS.GetFile(FilePath1).Size <> FS.GetFile(FilePath2).Size Then
CompareFiles = True
Exit Function
End If
Set File1 = FS.GetFile(FilePath1).OpenAsTextStream(1, 0)
Set File2 = FS.GetFile(FilePath2).OpenAsTextStream(1, 0)

CompareFiles = False
Do While File1.AtEndOfStream = False
Str1 = File1.Read
Str2 = File2.Read

CompareFiles = StrComp(Str1, Str2, 0)

If CompareFiles <> 0 Then
CompareFiles = True
Exit Do
End If
Loop

File1.Close()
File2.Close()
End Function

Call Comparefiles(f1,f2)

If CompareFiles(f1, f2) = False Then
MsgBox "Files are identical."
Else
MsgBox "Files are different."
End If

j) Counting the number of times a word appears in a file


sFileName="E:\gcr.txt"
sString="gcreddy"
Const FOR_READING = 1
Dim oFso, oTxtFile, sReadTxt, oRegEx, oMatches
Set oFso = CreateObject("Scripting.FileSystemObject")
Set oTxtFile = oFso.OpenTextFile(sFileName, FOR_READING)
sReadTxt = oTxtFile.ReadAll
Set oRegEx = New RegExp
oRegEx.Pattern = sString
oRegEx.IgnoreCase = bIgnoreCase
oRegEx.Global = True
Set oMatches = oRegEx.Execute(sReadTxt)
MatchesFound = oMatches.Count
Set oTxtFile = Nothing : Set oFso = Nothing : Set oRegEx = Nothing
msgbox MatchesFound

VbScript - Read File

How to read a txt file using the VbScript programming ?   


1.      Create a Text File
      Create a text file with the following name at the following location.
      C:\TestRead.txt

      Within the text file, add the following lines.
      If you get this message,
      you have successfully
      completed this
      programming task.

   2.      Open Notepad
      Go to Start - All Programs - Accessories - Notepad
      Save your file as C:\TestRead.vbs   ' A VbScript file

   3.            Copy and Paste the following code into any Text Editor.

      '*****************************************************************
      Option Explicit

      Const conForReading = 1

      'Declare variables
      Dim objFSO, objReadFile, contents

      'Set Objects
      Set objFSO = CreateObject("Scripting.FileSystemObject")
      Set objReadFile = objFSO.OpenTextFile("C:\TestReadtxt", 1, False)

      'Read file contents
      contents = objReadFile.ReadAll

      'Close file
      objReadFile.close

      'Display results
      wscript.echo contents

      'Cleanup objects
      Set objFSO = Nothing
      Set objReadFile = Nothing

      'Quit script
      WScript.Quit()
      '******************************************************************
      Save your file and exit Notepad

4. Execute the vbs file either from cmd prompt or by double clicking.

XML Part 1

The following JavaScript fragment loads an XML document
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
  {
  xhttp=new XMLHttpRequest();
  }
else
  {
  xhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}

The following code loads and parses an XML string:
if (window.DOMParser)
  {
  parser=new DOMParser();
  xmlDoc=parser.parseFromString(text,"text/xml");
  }
else // Internet Explorer
  {
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async="false";
  xmlDoc.loadXML(text);
  }
function loadXMLString(txt)
{
if (window.DOMParser)
  {
  parser=new DOMParser();
  xmlDoc=parser.parseFromString(txt,"text/xml");
  }
else // Internet Explorer
  {
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async="false";
  xmlDoc.loadXML(txt);
  }
return xmlDoc;
}

XML DOM Properties
These are some typical DOM properties:
    * x.nodeName - the name of x
    * x.nodeValue - the value of x
    * x.parentNode - the parent node of x
    * x.childNodes - the child nodes of x
    * x.attributes - the attributes nodes of x
Note: In the list above, x is a node object.

XML DOM Methods
    * x.getElementsByTagName(name) - get all elements with a specified tag name
    * x.appendChild(node) - insert a child node to x
    * x.removeChild(node) - remove a child node from x
Note: In the list above, x is a node object.
The JavaScript code to get the text from the first element in books.xml:
txt=xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue
After the execution of the statement, txt will hold the value "Everyday Italian"
Explained:
    * xmlDoc - the XML DOM object created by the parser.
    * getElementsByTagName("title")[0] - the first element
    * childNodes[0] - the first child of the element (the text node)
    * nodeValue - the value of the node (the text itself)
Accessing Nodes
You can access a node in three ways:
1. By using the getElementsByTagName() method
2. By looping through (traversing) the nodes tree.
3. By navigating the node tree, using the node relationships.

* getElementsByTagName() returns all elements with a specified tag name.
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title");
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("title");
for (i=0;i
  {
  document.write(x[i].childNodes[0].nodeValue);
  document.write("
");
  if (x[i].nodeType==1)
  {//Process only element nodes (type 1)
  document.write(x[i].nodeName);
  document.write("
");
  }
The following code navigates the node tree using the node relationships:
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("book")[0].childNodes;
y=xmlDoc.getElementsByTagName("book")[0].firstChild;
for (i=0;i
{
if (y.nodeType==1)
  {//Process only element nodes (type 1)
  document.write(y.nodeName + "
");
  }
y=y.nextSibling;
}

* Node Properties
In the XML DOM, each node is an object.
Objects have methods and properties, that can be accessed and manipulated by JavaScript.
Three important node properties are:    * nodeName
    * nodeValue
    * nodeType
The nodeName property specifies the name of a node.

    * read-only
    * nodeName of an element node is the same as the tag name
    * nodeName of an attribute node is the attribute name
    * nodeName of a text node is always #text
    * nodeName of the document node is always #document
The nodeValue property specifies the value of a node.
    * nodeValue for element nodes is undefined
    * nodeValue for text nodes is the text itself
    * nodeValue for attribute nodes is the attribute value

The following code retrieves the text node value of the first element:

xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
txt=x.nodeValue;
x.nodeValue="Easy Cooking";

The nodeType property specifies the type of node.
NodeType is read only.
The most important node types are:
Node type     NodeType
Element              1
Attribute            2
Text                   3
Comment          8
Document        9


xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName('title').length;
xmlDoc=loadXMLDoc("books.xml");
//the x variable will hold a node list
x=xmlDoc.getElementsByTagName('title');
for (i=0;i
{
document.write(x[i].childNodes[0].nodeValue);
document.write("
");
}
The attributes property of an element node returns a list of attribute nodes.
This is called a named node map, and is similar to a node list, except for some differences in methods and properties.
A attribute list keeps itself up-to-date. If an attribute is deleted or added, the list is automatically updated.
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName('book')[0].attributes;
document.write(x.getNamedItem("category").nodeValue);
document.write("
" + x.length);

The example below loops through all child nodes of , and displays their names and values:

All modern browsers support the W3C DOM specification.
However, there are some differences between browsers. One important difference is:
    * The way they handle white-spaces and new lines
Internet Explorer will NOT treat empty white-spaces, or new lines as text nodes, wile other browsers will.
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.documentElement.childNodes;
document.write("Number of child nodes: " + x.length);

DOM - Parent NodeAll nodes has exactly one parent node. The following code navigates to the parent node of :    
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("book")[0];
document.write(x.parentNode.nodeName);

Firefox, and some other browsers, will treat empty white-spaces or new lines as text nodes, Internet Explorer will not.
This causes a problem when using the properties: firstChild, lastChild, nextSibling, previousSibling.
To avoid navigating to empty text nodes (spaces and new-line characters between element nodes), we use a function that checks the node type:
  

  function get_nextSibling(n)
{
y=n.nextSibling;
while (y.nodeType!=1)
  {
  y=y.nextSibling;
  }
return y;
}
The nodeValue property is used to get the text value of a node.
The getAttribute() method returns the value of an attribute.

Get the Value of an Element
In the DOM, everything is a node. Element nodes does not have a text value.
The text of an element node is stored in a child node. This node is called a text node.
The way to get the text of an element, is to get the value of the child node (text node).
Get an Element Value
The getElementsByTagName() method returns a node list containing all elements with the specified tag name
in the same order as they appear in the source document.
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0];
The childNodes property returns a list of child nodes. The element has only one child node. It is a text node.
The following code retrieves the text node of the element:
x=xmlDoc.getElementsByTagName("title")[0];
y=x.childNodes[0];
The nodeValue property returns the text value of the text node:
x=xmlDoc.getElementsByTagName("title")[0];
y=x.childNodes[0];
txt=y.nodeValue;

Get the Value of an Attribute

In the DOM, attributes are nodes. Unlike element nodes, attribute nodes have text values.
The way to get the value of an attribute, is to get its text value.
This can be done using the getAttribute() method or using the nodeValue property of the attribute node.
Get an Attribute Value - getAttribute()
The getAttribute() method returns an attribute value.
The following code retrieves the text value of the "lang" attribute of the first element:
xmlDoc=loadXMLDoc("books.xml");
txt=xmlDoc.getElementsByTagName("title")[0].getAttribute("lang");
Get an Attribute Value - getAttributeNode()
The getAttributeNode() method returns an attribute node.
The following code retrieves the text value of the "lang" attribute of the first element:
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].getAttributeNode("lang");
txt=x.nodeValue;

Change the Value of an Element

In the DOM, everything is a node. Element nodes do not have a text value.
The text of an element node is stored in a child node. This node is called a text node.
The way to change the text of an element, is to change the value of the child node (text node).
Change the Value of a Text Node
The nodeValue property can be used to change the value of a text node.
The following code changes the text node value of the first element:
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Easy Cooking";
Change the Value of an Attribute
In the DOM, attributes are nodes. Unlike element nodes, attribute nodes have text values.
The way to change the value of an attribute, is to change its text value.
This can be done using the setAttribute() method or using the nodeValue property of the attribute node.
Change an Attribute Using setAttribute()
The setAttribute() method changes the value of an existing attribute, or creates a new attribute.
The following code changes the category attribute of the element:
xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName('book');
x[0].setAttribute("category","food");

Change an Attribute Using nodeValue
The nodeValue property can be used to change the value of a attribute node:
xmlDoc=loadXMLDoc("books.xml");

x=xmlDoc.getElementsByTagName("book")[0]
y=x.getAttributeNode("category");
y.nodeValue="food";


QTP XML Usage


We can create an Object Repository Via XML as Well


Function XmlController()
    Set doc = CreateObject("Microsoft.XMLDOM")
    doc.async = false
    doc.ValidateonParse = False
    doc.resolveExternals = False
    doc.LoadXml("")
    doc.save "C:\Test.xml"
    Set doc= Nothing
    Set objXMLDoc = CreateObject("Microsoft.XMLDOM")
    objXMLDoc.async = False
    objXMLDoc.load("C:\Test.xml")
    Dim objCurrNode, objNewNode, objNewText
    Call makeDisc(objXMLDoc)
    Call makeFiles(objXMLDoc)
    objXMLDoc.save("C:\Test.xml")
    set objXMLDoc =Nothing
End Function
'*******************************
'*  makeDisc                                          *
'*******************************
Sub makeDisc(objXMLDoc)
    getElem= GetElement()   
    getNo= GetNode()   
    Set objNewNode = objXMLDoc.createElement(getElem)
    Set objNewText = objXMLDoc.createTextNode(getNo)
    objNewNode.appendChild(objNewText)
    Set objCurrNode = objXMLDoc.documentElement
    objCurrNode.appendChild(objNewNode)
    Set objCurrNode = objCurrNode.lastChild
End Sub  'makeDisc subroutine

'******************************
'*  makeFiles                                       *
'******************************
Sub makeFiles(objXMLDoc)
    Set Root = objXMLDoc.documentElement
    Set NodeList = Root.getElementsByTagName("disc")
    For Each Elem In NodeList 
         Set objNewNode = objXMLDoc.createElement("title")
         Set objNewText = objXMLDoc.createTextNode("AVI 2")
         objNewNode.appendChild(objNewText)
         Set objCurrNode = objXMLDoc.documentElement
         objCurrNode.appendChild(objNewNode)
         Set objCurrNode = objCurrNode.lastChild
         objNewNode.appendChild(objNewText)
    Next

End Sub  'makeDisc subroutine

Function GetElement()
    message = "Enter Project Id"
    title = "Input Project id value"
    var = InputBox(message, title)
    Msgbox var
    GetElement =var
End Function

Function GetNode()
    message = "Enter Project Id"
    title = "Input Project id value"
    var = InputBox(message, title)
    Msgbox var
    GetNode =var
End Function

Call  XmlController

QTP Descriptive Programming

 1. logic or function of counting the no of subfolders under the main folder in tree structure.

 counter = 0
Function CountFolders(currentFolder)
    for each folder in currentFolder.SubFolders
        counter = counter + 1
        CountFolders(folder)
    Next
End Function

CountFolders
(CreateObject("Scripting.FileSystemObject").GetFolder("d:\temp") )
MsgBox(counter)
It counts only first level subfolders :)))

FCount = 0
 Set oFSO = CreateObject("Scripting.FileSystemObject")
  Set oFname = oFSO.GetFolder("D:\C:\Documents and
  Settings\cc_gubhi\Desktop\Gpubhi_folder") ' Folder Path
  Set vFiles = oFname.subfolders
  For each vFileItem in vFiles
  FCount = FCount + 1
  Next
  msgbox FCount

  Set oFSO = Nothing
  Set oFname= Nothing

   Set FSO = CreateObject("Scripting.FileSystemObject")
   Set TestFolder = FSO.GetFolder("C:\Documents and Settings")
   Set SubFolders= TestFolder.SubFolders
   MsgBox(SubFolders.Count)


1   What is use of library file and what is contains.?
2  What is difference between writing discripting programming and  writing
  code in library file.?

All the thing s that you can not do in the QTP can be done in vb script eg.
  implementing business logic.. This code can be written in the vb script in
  the library file. using library files you can separe the code so u will get
  kind of modularity in the code.

 2. When the objects in the AUT are dynamic in nature the we can use DP for
  identifying the objects DP code can be written in the library file.

  DP is a kind of programming which eliminate the existence of the OR.

   You can pass the property value pair to identify the object or Use
  Description object to do the same..

how can write a discriptive program to check first five check boxes out of ten check boxes.
Dim strChkBox
Dim intCntr
Dim intMaxChkbxCnt
Dim intTotalChkboxes

Set strChkBox=Description.create()

strChkBox("micclass").Value="WebCheckbox"

Set
intMaxChkbxCnt=Browser("YahooMail").Page("YahooInbox").ChildObjects(strChkBox)

intTotalChkboxes=intMaxChkbxCnt.Count()

For intCntr=1 To intTotalChkboxes

    If  intCntr<=5 Then
        Browser("YahooMail").Page("YahooInbox").WebCheckBox(intCntr).Set
"ON"

    Else
        Exit For
Next

 If an  object attributes are changing in runtime, it is different. Often we can
  handle dynamic changes by using regular expression, but sometimes RE doesn't
  help. Here is an example:


  Static Object Description:

          Set oDesc = Description.Create()
          oDesc("html tag").Value = "IMG"
          oDesc("image type").Value = "Plain Image"
          oDesc("html id").Value = "cal.*BOseries::Calendar::.*::on_sale::0"
          oDesc("micclass").Value = "Image"
          oDesc("file name").Value = "cal.gif"
 
  Dynamic Object Description:


          Set oDesc = Description.Create()
          oDesc("html tag").Value = "IMG"
          oDesc("image type").Value = "Plain Image"
          oDesc("html id").Value = "cal.*BOseries::Calendar::.*::on_sale::0"
          oDesc("micclass").Value = "Image"
          oDesc("file name").Value = "cal.gif"
  *        oDesc("index").Value = ActualIndex*

Sort out data in ascending/descending order in data table

 DataTable.ExportSheet "D:\Sort.xls" ,"Action1"
  RowCnt = DataTable.GetSheet("Action1").GetRowCount
  Set ExcelApp = CreateObject("Excel.Application")
  ExcelApp.Application.Visible = True
  Set Book = ExcelApp.Workbooks.Open("D:\Sort.xls")
  Set Sheet = Book.Worksheets("Action1")
  Sheet.Range("A2:A" &(RowCnt+1)).Sort Sheet.Range("A2")
  Book.SaveAs "D:\Sorted.xls"
  ExcelApp.Application.Quit
  DataTable.ImportSheet "D:\Sorted.xls", "Action1", "Action1"


RowCnt = DataTable.GetSheet("Action1").GetRowCount
  ReDim Arr(0)
  If (UBound(Arr) < RowCnt) Then
          ReDim Preserve Arr(RowCnt-1)
  End If
  For i = 0 to (RowCnt-1)
          Arr(i) =
  DataTable.GetSheet("Action1").GetParameter("RollNos").ValueByRow(i+1)
  Next
  For i = 0 to UBound(Arr)
      For j = i+1 to  UBound(Arr)
          If (Arr(i)   Arr(j)) Then
                          Tmp = Arr(j)
                          Arr(j) = Arr(i)
                          Arr(i) = Tmp
                          i = i - 1
              Exit For
          End If
      Next
  Next
  For i = 0 to (RowCnt-1)

  DataTable.GetSheet("Action1").GetParameter("RollNos").ValueByRow(i+1)
  = Arr(i)
  Next

QTP,check point Enhancement & Functions

Checkpoint Enhancements
. Ability to alter properties of all checkpoints during run-time. E.g. Expected bitmap of a bitmap checkpoint, expected values of a Table/DB checkpoint etc
. Ability to create checkpoints at run-time
. Ability to load checkpoints from a external file at run-time
. Ability to enumerate all checkpoints present in current script

Set oDosW = Description.Create
oDosW("regexpwndtitle").Value = "C:\\Windows\\System32\\cmd\.exe"
oDosW("regexpwndtitle").RegularExpression = False  
Window(oDosW).Activate
'Launch the window with title MyPuttyTesting
SystemUtil.Run "cmd", "/K title MyPuttyTesting" 
'Launch the window with title MyFTPTesting
SystemUtil.Run "cmd", "/K title MyFTPTesting" 
'Uniquely Recognize console application simultaneously without any ordinal identifier
Window("title:=MyPuttyTesting").Activate
Window("title:=MyFTPTesting").Activate
To get the current script name we can use the below line of code

Msgbox Environment("TestName")
'Description: Function to import the all the sheets present in the file
'Params:
'@FileName - File to import
Function ImportAllSheets(ByVal FileName)
      Dim oExcel, oBook 
      'Launch excel
      Set oExcel = GetObject("", "Excel.Application"
      'Open the file in read only mode
      Set oBook = oExcel.WorkBooks.Open(FileName,,True
      'Enumerate through all the sheets present in the file
      For each oSheet in oBook.WorkSheets  
            'Check if a DataTable with current name already exists
            If Not IfDataSheetExist(oSheet.Name) Then
                  'DataTable cannot be imported if the sheet does not exist
                  DataTable.AddSheet oSheet.Name
            End If 
            'Import the sheet
            DataTable.ImportSheet FileName, oSheet.Name,oSheet.Name
      Next  
      Set oBook = Nothing  
      'Quit Excel
      oExcel.Quit
      Set oExcel = Nothing
End Function
'Function to check if a DataTable sheet exists or not
Function IfDataSheetExist(ByVal SheetName)
      IfDataSheetExist = True
      On error resume next
      Dim oTest
      Set oTest = DataTable.GetSheet(SheetName)
      If err.number Then IfDataSheetExist = False
      On error goto 0
End Function
Smart identification is a algorithm which QTP uses when it is not able to identify a object. The algorithm tries to figure out if there is a unique control on the page which matches the some of the properties of the failed object.
This happens because when QTP SI starts looking for a Logout button there is none, but there is only one button on the page. So QTP SI assumes that it is the Logout button which we were looking for.
Setting("DisableReplayUsingAlgorithm") = 1
'or using AOM code
CreateObject("QuickTest.Application").Test.Settings.Run.DisableSmartIdentification = True