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

Sunday, July 17, 2022

Synchronization and Page Load ,Waits

 Implicit Waits:

Implicit waits tell to the WebDriver to wait for certain amount of time before it throws an exception. Once we set the time, WebDriver will wait for the element based on the time we set before it throws an exception. The default setting is 0 (zero). We need to set some wait time to make WebDriver to wait for the required time.

Note: Implicit Wait is in place for the entire time the browser is open. Time taken to search all the elements are based on the time fixed for the implicit wait.

driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);

 first parameter will accept the time as an integer value, second parameter will accept the time measurement in terms of SECONDS, MINUTES, MILISECOND, MICROSECONDS, NANOSECONDS, DAYS, HOURS, etc.

 

Selenium FluentWait:

FluentWait can define the maximum amount of time to wait for a specific condition and frequency with which to check the condition before throwing an “ElementNotVisibleException” exception.

To say in effortless manner, it tries to find the web element repeatedly at regular intervals of time until the timeout or till the object gets found.

We use FluentWait commands mainly when we have web elements which sometimes visible in few seconds and some times take more time than usual. Mainly in Ajax applications. We could set the default pooling period based on our requirement. We could ignore any exception while polling an element.

Wait wait = new FluentWait(WebDriver reference)

.withTimeout(timeout, SECONDS)

.pollingEvery(timeout, SECONDS)

.ignoring(Exception.class);

 

WebElement foo=wait.until(new Function<WebDriver, WebElement>() {

public WebElement applyy(WebDriver driver) {

return driver.findElement(By.id("foo"));

}

});

 

Example:

Wait wait = new FluentWait<WebDriver>(driver)

.withTimeout(45, TimeUnit.SECONDS)

.pollingevery(5, TimeUnit.SECONDS)

.ignoring(NoSuchElementException.class);

 

WebDriverWait In Selenium:

It is applied on certain element with defined expected condition and time. This wait is only applied to the specified element. This wait can also throw exception when element is not found.

The following are the Expected Conditions that can be used in Explicit Wait

  1. alertIsPresent()
  2. elementSelectionStateToBe()
  3. elementToBeClickable()
  4. elementToBeSelected()
  5. frameToBeAvaliableAndSwitchToIt()
  6. invisibilityOfTheElementLocated()
  7. invisibilityOfElementWithText()
  8. presenceOfAllElementsLocatedBy()
  9. presenceOfElementLocated()
  10. textToBePresentInElement()
  11. textToBePresentInElementLocated()
  12. textToBePresentInElementValue()
  13. titleIs()
  14. titleContains()
  15. visibilityOf()
  16. visibilityOfAllElements()
  17. visibilityOfAllElementsLocatedBy()
  18. visibilityOfElementLocated()

//WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);

WebDriverWait wait = new WebDriverWait (driver, 20);

wait.until(ExpectedConditions.VisibilityofElementLocated(By.xpath(""//button[@value='Save Changes']"")));

 

What happen if you mix both implicit wait and explicit wait in a Selenium Script?

As per the official Selenium documentation, it is suggested not to mix both Implicit waits and Explicit Waits. Mixing both of them can cause unpredictable wait times. Implicit wait is defined only once in the code. It will remain same throughout the driver object instance. Explicit wait is defined whenever it is necessary in the code. This wait will call at the time of execution. It is a conditional wait.Explicit wait will overwrite the implicit wait where ever explicit wait is applied. So, Explicit Wait gets first preference then Implicit Wait.

 Cheers,

TJ

Taking Screenshots in automation

 Some of the scenarios we may need to capture a screenshot using Selenium WebDriver are

i. Application issues
ii. Assertion Failure
iii. Difficulty to find Webelements on the web page
iv. Timeout to find Webelements on the web page

Tosca

Take Screen Shot In Tosca Testsuite

A standard module is provided by tricentis to take screenshot. It is present in standard modules. TBox TakesScreenshot

Selenium

Selenium provides an interface called TakesScreenshot which has a method getScreenShotAs which can be used to take a screenshot of the application under test.

Syntax to capture and save the screenshot.
File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

Syntax to store it in our local drive

FileUtils.copyFile(screenshotFile, new File("filename_with_path"));

to capture full page screenshot using Selenium WebDriver:

What is aShot?
aShot is a WebDriver Screenshot utility. It takes a screenshot of the WebElement on different platforms (i.e. desktop browsers, iOS Simulator Mobile Safari, Android Emulator Browser).

aShot might be configured to handle browsers with the viewport problem. This gives a screenshot of the entire page even for Chrome, Mobile Safari, etc

Add this jar file in to your project. Note: Select Project and Right click on the Project – Go to ‘Build path’ – Go to ‘Configure build path’ – Click on ‘lib’ section – Add external jar

Screenshot fpScreenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);

                  ImageIO.write(fpScreenshot.getImage(),"PNG",new File("D:///FullPageScreenshot.png"));

To Capture Screenshot of Failed Test Cases Using Selenium WebDriver

If a script fails, we need to know where was the error in script. Solution for this is to capture a screenshot of webpage when the test case fails. We could easily identify where exactly the script got failed by seeing the screenshot.

To achieve this, we could place the entire code in try-catch block. Which means placing the test steps in try block and screen capture statement in catch block. If a test step fails in the try block then it goes to the catch block and capture a screenshot of the web page.

 

UFT/QTP 

Dim ScreenName

  On Error Resume Next

  ScreenName = " "
  
  CurrentTime = "_Test_Case"&"_"& Day(Now)&"_"& Month(Now)&"_"& Year(Now)&"_"&

   Hour(Now)&"_"& Minute(Now)&"_"& Second(Now)

  ScreenShotName = "Name_of_the_Screen" &  CurrentTime & ".png"

  ScreenName ="Path where the Screenshot needs to be stored"&"\"&ScreenShotName

  Desktop.CaptureBitmap ScreenName,True

 

 

Thursday, June 11, 2020

VBA Function to Clear content except header rows and Get col headers in string or array

Folks,

sometimes need to use only headers or template from existing file then below code might help to clear the data. Sometimes you need to capture the column header in array or string then below function will help you.

Function DeleteExceptFirstHeader(shWrite)
    'shWrite.Rows("2:" & Rows.Count).ClearContents
    shWrite.Rows("2:" & Rows.Count).Clear
End Function

Function fnReadColHeader(wST As Worksheet)
    Dim strData() As Variant
    lastCol = wST.Range("a1").End(xlToRight).Column
    strData = wST.Range("1:" & lastCol).Value
    strHeaders = 0
    Dim columnCounter As Long
 
    For columnCounter = LBound(strData, 1) To UBound(strData, 1)
        strHeaders = strHeaders & ":" & strData(1, columnCounter)
    Next columnCounter
 '   MsgBox strHeaders
   fnReadColHeaderDRF = strHeaders
End Function

Cheers.
TJ

VBA Function to Generate Dummy data for numbers, string and date values

Hi guys,

If you need to generate any random dummy data for string/alphanumeric/date/numbers(2 digit/3 digit) then below logic might help you.

provide your sDatatype in below select case.

  Select Case sDataType
            Case Is = "Alphabets"
                dtRndData = UCase(Cnst) & Vowel & Cnst & Vowel & Cnst
            Case Is = "Alphanumeric"
                DLocation = UCase(Cnst) & Vowel & Cnst & Vowel & Cnst
                dtRndData = Tens() & " " & DLocation
            Case Is = "Date"
                dtRndData = GetRndDate(#12/1/1965#, #5/31/2020#)
            Case Is = "Numbers"
                dtRndData = Tens()
        End Select

Function LName()
    Dim i As Long, Tmp As String
    LName = UCase(Cnst) & Vowel & Cnst & Vowel & Cnst
End Function

Function Vowel()
      Dim V
      V = Array("a", "e", "i", "o", "u")
      Vowel = V(Int((5 * Rnd)))
End Function
   
Function Cnst()
    Dim C
    C = Array("b", "c", "d", "f", "g", "h", "j", "k", "l", "m", _
                "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z")
    Cnst = C(Int((21 * Rnd)))
End Function
Function Tens()
    Tens = Int(100 * Rnd)
End Function

Function Hundreds()
    Hundreds = Int(1000 * Rnd)
End Function

Function GetRndDate(dtStartDate As Date, dtEndDate As Date) As Date
    On Error GoTo Error_Handler
    Dim dtTmp                 As Date

    'Swap the dates if dtStartDate is after dtEndDate
    If dtStartDate > dtEndDate Then
        dtTmp = dtStartDate
        dtStartDate = dtEndDate
        dtEndDate = dtTmp
    End If

    Randomize
    GetRndDate = DateAdd("d", Int((DateDiff("d", dtStartDate, dtEndDate) + 1) * Rnd), dtStartDate)

Error_Handler_Exit:
    On Error Resume Next
    Exit Function

Error_Handler:
    MsgBox "The following error has occurred" & vbCrLf & vbCrLf & _
           "Error Number: " & Err.Number & vbCrLf & _
           "Error Source: GetRndDate" & vbCrLf & _
           "Error Description: " & Err.Description & _
           Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
           , vbOKOnly + vbCritical, "An Error has Occurred!"
    Resume Error_Handler_Exit
End Function

Getting data type from given value whether Number/String/Date/Alphanumeric

Hi Folks,

Sometimes need to generate some random test data based on given value of cell or variables data value, whether it is number, date, string, alphabets.
strOrignalData="John Smith" 'DOB,phone number any original data

 sDataType = GetDatatype(strOrignalData)

Public Function GetDatatype(strData)
            numbers = 0
            alphabets = 0
            specialChar = 0
            For i = 1 To Len(strData)
                b = Mid(strData, i, 1)
                If IsNumeric(b) Then
                 numbers = numbers + 1
                ElseIf (Asc(b) >= 97) And (Asc(b) <= 122) Or Asc(i) >= 65 And Asc(i) <= 90 Then
                 alphabets = alphabets + 1
                ElseIf InStr(b, "/") > 0 Then
                 specialChar = specialChar + 1
                Else
                    'None
                End If
            Next
            If numbers = Len(strData) Then
                strdatatype = "Numbers"
            ElseIf specialChar >= 2 Then
                strdatatype = "Date"
            ElseIf alphabets > 0 And numbers = 0 Then
                strdatatype = "Alphabets"
            Else
                strdatatype = "Alphanumeric"
            End If
            GetDatatype = strdatatype
         
End Function

cheers.
TJ

Generate filename with date time stamp and separate file name and path from given file path

Hi folks,

many times we need to create the dummy or new file or report file with date timestamp appending to file name. Also, from the given file path we need to separate the file name and file path then definitely this post might help you.

Public Function AddResultTestdatafile(strFilePath)
   
    Workbooks.Add Template:=strFilePath
    strNewFileTempName = getFName(strFilePath)
    strTestFileNameval = Split(strNewFileTempName, ".")
    strNewFilePath = getPath(strFilePath)
    'to generate file name appending datetime stamp
    strNewTestFileName = strTestFileNameval(0) & "_" & "DummyData" & "_" & Year(Date) & Right("00" & Month(Date), 2) & Right("00" & Day(Date), 2) & Right("00" & Hour(Time), 2) & Right("00" & Minute(Time), 2) & Right("00" & Second(Time), 2) & ".xlsx"
    ActiveWorkbook.SaveAs _
        Filename:=strNewFilePath & strNewTestFileName
    ResultDummyFilename = strNewFilePath & strNewTestFileName
    AddResultTestdatafile = ResultDummyFilename
   
End Function

'to get the path from given file path
Function getPath(pathfile) As String: getPath = Left(pathfile, InStrRev(pathfile, "\")): End Function

'to get the file name from given file path
Function getFName(pathfile) As String: getFName = Mid(pathfile, InStrRev(pathfile, "\") + 1): End Function

Cheers.
TJ

Thursday, May 28, 2020

Getting row index for particular given string value of string

Hi Folks,

Sometimes, you need to find the row index of particular row in sheet based on fixed value string and need to operate some operation based on that row like adding and delete row above and below that string value row, this code might help you.

strSearchTxt ="This is search row text for index find of this row"
Dim iTextRow As Long: iTextRow = GetTextRow(strSearchTxt )

Public Function GetTextRow(strSearchTxt)
GetTextRow = 0
With ActiveSheet
    Set Rng = .UsedRange.Find(strSearchTxt)
    If Not (Rng Is Nothing) Then GetTextRow = Rng.Row
End With
End Function

Cheers.

Get Column index based on column name using vba

Hi folks,

If you need to find the column index based on column name, when your column sequence is not fixed in your sheet, please find below code which might helpful to you.

Code sample 1:
 Set findrng = wST.Range("1:1")
 ColNameIndex = findrng.Find("searchcolname").Column

Code sample 2:
strnameindex = wST.Match("searchcolname",wST.Range("1:1"), 0)

Code sample 3:
Function GetHeaderColumn(shRead As Worksheet, header As String) As Integer
    Dim headers As Range
    Set headers = shRead.Range("1:1")
    GetHeaderColumn = IIf(IsNumeric(Application.Match(header, headers, 0)), Application.Match(header, headers, 0), 0)
End Function

Cheers.
TJ.

Friday, October 5, 2018

Read XML file as string using Vbscript

hi folks, To read XML file as entirely string we can use below logic. Hope it will useful.

set xmldoc=createobject("MICROSOFT. XMLDOM")
xmldoc. async=false
xmldoc. load(recentxmlfilepath)
for each ochdnd in xmldoc. documentelement. childnodes
     strxmldocline=ochdnd. nodename & ":" & ochdnd. text & vbcrlf
xmldocdata= xmldocdata & strxmldocline
next
msgbox xmldocdata

cheers
Trupti

Thursday, August 2, 2018

Text file edit using UFT/QTP/VBS

Hi folks

Create test file on path with content.

Test file edit data-Trupti to Jethva
Data -Trupti

Save file c:\test.txt

Now write function as
Public function fnModifytextfile(strfilepath,strchangedata)
Const ForReading=1
Const ForWriting=2
Set objfso=createobject(“scripting.filesystemobject”)
Set myfile=objfso.opentextfile(strfilepath,forreading,true)
Set mytemp=objfso.opentextfile(strfilepath & “.tmp”, forwriting,true)
Do while not myfile.atendofstream
       Myline=myfile.readline
       If instr(myline,”Data”) then
            Orignaldata=split(myline,”-“)
            Orignaldatachange=orignaldata(1)
            Datatobechange=“ “& strchangedata
            Myline=replace(myline,orignaldatachange,datatobechange)
       Endif
       Mytemp. Writeline myline
Loop
Myfile.close
Mytemp.close
Objfso.deletefile(strfilepath )
Objfso.movefile strfilepath & “.tmp”, strfilepath
Msgbox “done”
End function
Call fnModifytextfile(“c:\test.txt”,”jethva”)

Tuesday, October 31, 2017

Key design activities and component for framework

Folks,

Following are key design activities for create robust automation framework

1. Define standard project folder hierarchy
2. Define standard configuration and launcher script.
3. Design standard format for automation component
4. Define reusable modules to reduce development and maintenance cost
5. Define layered architecture of reusable modules
6. Design standard flow control module
7. Design standard data storage, loading, sharing mechanism
8. Define standard reporting mechanism
9. Design standard error or exception handling mechanism

Components
1. Controller
2. Reusable component
3. Event Handler
4. Reporter

Regards, Trupti 

Read, write and delete a key from windows system registry

Dim owshell, skeypath, Skeyval, skeytype
Skeypath= "hkey_current_user\mycustomekey\mycustomedata\myvalue"
Skeyval="this is UFT made registry"
Skeytype="reg_sz"

Set owshell= createobject("wscript.shell")
Owshell.RegWrite skeypath,Skeyval ,skeytype

Skeyval = owshell .RegRead(skeyPath)
Print Skeyval

Owshell .RegDelete skeypath
 'To run application
SApp="notepad.exe"
Owshell .run sApp
Set owshell = nothing

Monday, October 30, 2017

File Rename, invalid extension and modify file data using UFT

'Invalid file extension
Public Function fnFileInvalidExtn(strfolderSourcePath,strfolderdestnPath,strFile)
   
        Set FSO=CreateObject("Scripting.FileSystemObject")
        strfolderSourcePath_mod=strfolderSourcePath&"\"&strFile
        strTestFileName1=Split (strFile,".")
        strTestFileNameFir=strTestFileName1(0)
        strTestFileName_extn_chg=strTestFileNameFir&"."&"d"
        strfolderdestnPath_mod=strfolderdestnPath&"\"&strTestFileName_extn_chg
        FileEx=FSO.FileExists(strfolderSourcePath_mod)
   
        If FileEx=True Then
            FSO.MoveFile strfolderSourcePath_mod,strfolderdestnPath_mod
            Call fnDoneResult("File Extension changed is Sucessful","File is renamed to " & strfolderdestnPath)    
        else
            Call fnFailResult("File Extension changed is UnSucessful ","Unable to renamed file to " & strfolderdestnPath)
        End If
        fnFileInvalidExtn=strTestFileName_extn_chg
                               
End Function

'File Rename

Public Function fnFileRename(strfolderSourcePath,strfolderdestnPath,strFile)
        Set FSO=CreateObject("Scripting.FileSystemObject")
        strfolderSourcePath_mod=strfolderSourcePath&"\"&strFile
        strTestFileNamemsg=Split (strFile,".")
        strTestFileNameFir=strTestFileNamemsg(0)
        strNewTestFileName=Left(strTestFileNameFir,5)&"_"&"Data"& "_" & year(Date) & Right("00" & Month(Date),2) & Right("00" & Day(Date),2) & Right("00" & Hour(Time),2) & Right("00" & Minute(Time),2)  & Right("00" & Second(Time),2) & ".dat"
        strfolderdestnPath_mod=strfolderdestnPath&"\"&strNewTestFileName
        FileEx=FSO.FileExists(strfolderSourcePath_mod)
   
    If FileEx=True Then  
        FSO.MoveFile strfolderSourcePath_mod,strfolderdestnPath_mod
        Call fnDoneResult("File Rename is Sucessful","File is renamed to " & strfolderdestnPath)    
      else
        Call fnFailResult("File Rename is UnSucessful ","Unable to renamed file to " & strfolderdestnPath)
    End If
fnFileRename=strNewTestFileName  
End Function

'Function to modify the file data
Public Function fnModifyFile(strFilePath,strOrignalString, strmodifiedString)
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFilePath, ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, strOrignalString, strmodifiedString)
Set objFile = objFSO.OpenTextFile(strFilePath, ForWriting)
objFile.WriteLine strNewText
objFile.Close
End Function

Cute FTP connect, disconnect and file upload

'function to connect cute FTP
public function fnConnectCuteFTP(strHost,strUploadUserID,strUploadPwd)
Dim Flag
If Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").Exist Then
       Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").Close
    End If
Systemutil.Run "C:\Program Files (x86)\Globalscape\CuteFTP\cuteftppro.exe"
Wait (5)
Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").Dialog("regexpwndclass:=#32770","regexpwndtitle:=Tip of the Day").WinButton("regexpwndclass:=Button","regexpwndtitle:=&Close").Click
Wait(1)
Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").WinEdit("regexpwndclass:=Edit","attached text:=Host:").Type trim(strHost)
Wait(1)
Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").WinEdit("nativeclass:=Edit","attached text:=Username:").Set trim(strUploadUserID)
Wait(1)
Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").WinEdit("nativeclass:=Edit","attached text:=Password:").Set trim(strUploadPwd)
Wait(1)
Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").WinToolbar("regexpwndclass:=ToolbarWindow32","regexpwndtitle:=Quick Connect").Press 1
Wait (5)
If Window("regexpwndclass:=#32770","regexpwndtitle:=File Transfer Log").Exist Then
       Window("regexpwndclass:=#32770","regexpwndtitle:=File Transfer Log").Close
       Call fnFailResult("CuteFTP Connection Failure ","Unable to connect to CuteFTP")
Flag=False      
    Else
       Call fnDoneResult("CuteFTP Connection Sucessful ","CuteFTP connection is sucessful")
Flag=True      
    End If
    fnConnectCuteFTP=Flag
End function

Public function fnDisconnectCuteFTP()
If Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").Exist Then
       Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").Close
Call fnDoneResult("CuteFTP DisConnection","CuteFTP Disconnected sucessful")      
    Else
Call fnFailResult("CuteFTP is not launched","Unable to close as CuteFTP is not launched")  
    End If

End function

Public Function fnCuteFTPFileUpload(strFileSourcePath,strTestFileName)
Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").WinEdit("regexpwndclass:=Edit","window id:=132").Set trim(strFileSourcePath)
Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").WinEdit("regexpwndclass:=Edit","window id:=132").Type micReturn
Count=Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").WinListView("regexpwndclass:=SysListView32","window id:=1200").GetItemsCount
For i = 0 To Count
        FileName=Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").WinListView("regexpwndclass:=SysListView32","window id:=1200").GetItem(i)
        If FileName=trim(strTestFileName) Then
           Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").WinListView("regexpwndclass:=SysListView32","window id:=1200").Activate i
           Exit For
        End If
Next
Call fnDoneResult("CuteFTP Fileupload done","CuteFTP File upload sucessful")
End Function

Validate Environment Variable value

Environment is global object in UFT, it can be used to store and retrieve both run time and design time data.
Two type of environment variables
1. User defined-it has two types
- internal variable-- referred as default values
-external variable-- referred as constant value
2. Built in-give two type of information
- static data such as OS,OS version,local host name, test name, test fir etc
-Runtime data such as test iteration ,action name,action iteration etc

function for Validate_EnvironmentVar
Public function fnVerifyEnvironmentVar(strTestCaseID,strVarName,strVarValue)
Dim Flag
Set Obj = CreateObject("wscript.shell")
set objEnv = Obj.Environment("System")
sVarValue = objEnv.Item(strVarName)
If Trim(ucase(sVarValue))=Trim(ucase(strVarValue)) Then
Call fnDoneResult("Environment variable verify successfully", strVarName & " variable have value " &strVarValue& " match successfully.")
Flag=True
else
Call fnFailResult("Environment variable verify unsuccessfully",strVarName & " variable have value " &strVarValue& " not match successfully.")
Flag=False
End If
fnVerifyEnvironmentVar=Flag

End function

To rename folder

public Function fnRenameFolder(strFolderName,strSourcePath,strDestinationPath)
 
    Set FSO = CreateObject("Scripting.FileSystemObject")
    If Not FSO.FolderExists(strDestinationPath) Then
       FSO.MoveFolder strSourcePath,strDestinationPath
       Call fnDoneResult(strFolderName & " Folder rename",strFolderName & " Folder rename from " & strSourcePath & "to " & strDestinationPath & "Sucessfully")
    Else
       Call fnFailResult(strFolderName & " Folder Not Exist",strFolderName & " Folder already exist with same name on " & strDestinationPath )
    End If  
End Function

Get Recent log file and validate log message present or not using UFT

'function to get recent log file
Public Function fnRecentLogFile(strLogpath)
    Set recentLogFile = Nothing
    For Each file in fsoLogFile.GetFolder(strLogpath).Files
          If (recentLogFile is Nothing) Then
            Set recentLogFile = file
        ElseIf (file.DateLastModified > recentLogFile.DateLastModified) Then
            Set recentLogFile = file
        End If
    Next
End Function
'function to verify log messages present in file or not
Function fnVerifyLogFile(strLogFilePath,strLogFileMsg)
    Dim Flag
    Call fnRecentLogFile(strLogFilePath)
    Set objFile = fsoLogFile.OpenTextFile(recentLogFile)
    line_num=0
    Dim bMatchFlag
    bMatchFlag=False
    Do Until objFile.AtEndOfStream
        strLine = objFile.ReadLine
        line_num = line_num+1
        If InStr(strLine,strLogFileMsg)>0 Then
            'msgbox strLine
            bMatchFlag=True
            Exit Do
        else
            bMatchFlag=False
        End If
    Loop  
    If bMatchFlag=True Then
       Call fnDoneResult("Log Message Present",strLogFileMsg & "Log Message Present in LOG File.")
       Flag=True
    else
      Call fnFailResult("Log Message not present",strLogFileMsg & "Log Message not present in LOG File.")
      Flag=False
    End If
    fnVerifyLogFile=Flag
End Function

XML File validations using UFT

'function to load xml file and use globle xml object
Public Function fnLoadReadXMLFile(strFile,strFilePath)
Set objXMLFile=createobject("Microsoft.XMLDOM")
objXMLFile.async=False
Set gobjXMLFile=fnLoadXMLFile(strFilePath,objXMLFile)
End Function
'function to load xml file
Public Function fnLoadXMLFile(strFilePath,ByRef objXMLFile)
objXMLFile.Load(strFilePath)
If objXMLFile.parseError.ErrorCode=0 Then
Call fnDoneResult("XML File Loaded", "XML File Loaded Successfully.")
else
Call fnFailResult("XML File does not Loaded","XML File does not Loaded Successfully.")
End If
Set fnLoadXMLFile=objXMLFile
End Function
'function to read xml node value
Public Function fnRetriveXMLNodeValue(strXMLNode,ByRef objXMLFile)
Set ColNodes=objXMLFile.selectNodes(strXMLNode)
If ColNodes.length >0 Then
For each objNode in ColNodes
strXMLTempOld=objNode.Text
strXMLTemp=strXMLTemp & "|" & strXMLTempOld

If Left(strXMLTemp,1)="|" Then
strXMLTemp=Right(strXMLTemp, Len(strXMLTemp)-1)
End If
' strXMLClientIDAttr=objNode.getAttribute("strAttributeName")
Next
fnRetriveXMLNodeValue=strXMLTemp
Call fnDoneResult("XML Node value found","XML Node value" & strXMLTemp& " found")
ElseIf ColNodes.length=0 Then
strXMLTemp=""
fnRetriveXMLNodeValue=strXMLTemp
else
Call fnFailResult("XML Node value not found","XML Node value" & strXMLTemp& " not found")
End If
End Function
'function to read xml node attribute value
Public Function fnRetriveXMLNodeAttributeValue(strXMLNode,strAttributeName,ByRef objXMLFile)
Set ColNodes=objXMLFile.selectNodes(strXMLNode)
If ColNodes.length >0 Then
For each objNode in ColNodes
strXMLTemp=objNode.Text
strXMLAttriVal=objNode.getAttribute(strAttributeName)
Next
fnRetriveXMLNodeAttributeValue=strXMLAttriVal
Call fnDoneResult("XML Node Attribute value found","XML Node Attribute value " & strXMLAttriVal & " found")
ElseIf ColNodes.length=0 Then
strXMLAttriVal=""
fnRetriveXMLNodeAttributeValue=strXMLAttriVal
else
Call fnFailResult("XML Node Attribute value not found","XML Node Attribute value " & strXMLAttriVal & " not found")
End If
End Function
'function to modify xml node attribute value 
 Public Function fnModifyXMLNodeAttributeValue(strXMLNode,strAttributeName,strModifyTagVal,ByRef objXMLFile,strFilePath)
Set ColNodes=objXMLFile.selectNodes(strXMLNode)
If ColNodes.length >0 Then
For each objNode in ColNodes
objNode.Attributes.getNamedItem(strAttributeName).Text = strModifyTagVal
strXMLAttriVal=objNode.getAttribute(strAttributeName)
If strXMLAttriVal=strModifyTagVal Then
Call fnDoneResult("XML Node Attribute modified","XML Node Attribute value is modifed with " & strModifyTagVal)
else
Call fnFailResult("XML Node Attribute not modified","XML Node Attribute value is not modified with " & strModifyTagVal)
End If
objXMLFile.Save(strFilePath)
Call fnDoneResult("XML File save","XML File save with attribute change")
Next
'fnModifyXMLNodeAttributeValue=strXMLAttriVal
Call fnDoneResult("XML Node Attribute modified","XML Node Attribute value is modifed with " & strModifyTagVal)
'ElseIf ColNodes.length=0 Then
' strXMLAttriVal=""
'fnModifyXMLNodeAttributeValue=strXMLAttriVal
else
Call fnFailResult("XML Node Attribute not modified","XML Node Attribute value is not modified with " & strModifyTagVal)
End If
End Function

To check whether file exist in the specified path or not

Function fnFileExists_InSpecifiedPath(str_Path_FileName)
On Error Resume Next
'Specify the Path as well along with file name
Set fso = CreateObject("Scripting.FileSystemObject")
fnFileExists_InSpecifiedPath = fso.FileExists(str_Path_FileName)
    Set fso = Nothing
End Function

To get the size of specified file

Function fnGet_FileSize(str_Path_FileName)
   On Error Resume Next
'Specify the Path along with the file name
On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(str_Path_FileName) Then
Set ofile = fso.GetFile(str_Path_FileName)
File_Size = ofile.Size & " bytes"
Else
Call DoneResult("Specified File: " & str_Path_FileName & " not found", "Not able to fetch size of the file")
End If
fnGet_FileSize = File_Size
Set fso = Nothing
Set ofile = Nothing
End Function