Search This Blog

Monday, February 11, 2013

Function to return only characters and numbers in any string

This function can be used to return only the characters and numbers in any string. It is useful for string comparison and data comparison. All spaces and other special characters will be removed from the return value.


Public Function ReturnOnlyCharactersandNumbers(myString)
mystr = NULL
sLen = Len(myString)
snewLen = sLen
For i = 1 to sLen
sChar = Left(myString,1)
sASCII= Asc(sChar)
myString = Right(myString,(snewLen-1))
snewLen = Len(myString)
If sASCII >64 and sASCII <91 span="" then="">
mystr = mystr & Chr(sASCII)
Elseif sASCII >96 and sASCII < 123 Then
mystr = mystr & Chr(sASCII)
Elseif IsNumeric(sChar) = True Then
mystr = mystr & sChar
End If
Next
ReturnOnlyCharactersandNumbers = Ucase(mystr)
End Function

Function to return only characters in any string

This function can be used to return only the characters in any string. It is useful for string comparison and data comparison. All spaces and other characters will be removed from the return value.



Public Function ReturnOnlyCharacters (myString)
mystr = NULL
sLen = Len(myString)
snewLen = sLen
For i = 1 to sLen
sChar = Left(myString,1)
sASCII= Asc(sChar)
myString = Right(myString,(snewLen-1))
snewLen = Len(myString)
If sASCII >64 and sASCII <91 p="" then=""> mystr = mystr & Chr(sASCII)
End If
If sASCII >96 and sASCII < 123 Then
mystr = mystr & Chr(sASCII)
End If
Next
ReturnOnlyCharacters = Ucase(mystr)
End Function

Sunday, December 9, 2012

Run QTP when the monitor is off/minimized


Change the following registry settings:-
Step 1: Goto HKEY_LOCAL_MACHINE\SOFTWARE\Mercury Interactive\QuickTest Professional\MicTest
Step 2: Locate the key “SkipEnvironmentChecks”
step 3: Change the value to “1″ (Default value is 0)
Step 4: Restart the QTP.

Thursday, November 15, 2012

Automating a checkbox in a combo box



val = Dialog(DialogName).WinComboBox(ComboBoxName).GetVisibleText
Num = Dialog(DialogName).WinComboBox(ComboBoxName).GetItemsCount

For i = 0 to Num-1
          selectitem = Dialog(DialogName).WinComboBox(ComboBoxName).GetItem(i)
          Pos = Instr(1, val,selectitem)
          If Pos <> 0 Then
                   On Error Resume Next
                   Dialog(DialogName).WinComboBox(ComboBoxName).Select i
          End If
          val = Dialog(DialogName).WinComboBox(ComboBoxName).GetVisibleText
Next


checkval = "Local"

For i = 1 to 2
          selectitem = Dialog(DialogName).WinComboBox(ComboBoxName).GetItem(i)
          Pos = Instr(1, checkval,selectitem)
          If Pos <> 0 Then
                   On Error Resume Next
                   Dialog(DialogName).WinComboBox(ComboBoxName).Select i
          End If
Next

Monday, May 9, 2011

Run Script - For associating all libraries, repositories and environment variables

Dim App 'As Application
Set App = CreateObject("QuickTest.Application")
App.Launch
App.Visible = True
App.Test.Settings.Launchers("Windows Applications").Active = False
App.Test.Settings.Launchers("Windows Applications").Applications.RemoveAll
App.Test.Settings.Launchers("Windows Applications").RecordOnQTDescendants = True
App.Test.Settings.Launchers("Windows Applications").RecordOnExplorerDescendants = False
App.Test.Settings.Launchers("Windows Applications").RecordOnSpecifiedApplications = True
App.Test.Settings.Run.IterationMode = "rngAll"
App.Test.Settings.Run.StartIteration = 1
App.Test.Settings.Run.EndIteration = 1
App.Test.Settings.Run.ObjectSyncTimeOut = 120000
App.Test.Settings.Run.DisableSmartIdentification = False
App.Test.Settings.Run.OnError = "NextStep"
App.Open "D:\Ranger Automation\Main Script\SmokeTest", False
App.Test.Settings.Resources.DataTablePath = "D:\Ranger Automation\Data Folder\Session Data\SmokeTest.xls"
App.Test.Settings.Resources.Libraries.RemoveAll

App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functional Layer\Ebeam_MainWindow.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functional Layer\iAS-Div.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functional Layer\IAS_FunctionalLayer.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functional Layer\Review.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functional Layer\Run_InspectionQueue_FunctionalLayer.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functional Layer\SetUp.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functional Layer\SetupRun_ReviewWafer_FunctionalLayer.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functional Layer\Setup_Button_ValidationStatus.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functional Layer\SetUp_Run.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functional Layer\Test_TestSummaryGrid.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functional Layer\Utilities.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functional Layer\WaferSetup.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functional Layer\WaferSetup_FunctionalLayer.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functions\Applic_Path.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functions\Calling Logger.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functions\Framework_Functions.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functions\Job Queue.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functions\KT-Logger.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functions\MachineLaunch.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functions\New_TestCase.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functions\QTP_Logger.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functions\Ranger_Recipe.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functions\Ranger_SubFunction.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functions\RunJobQueue.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functions\Utility.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functions\WPP_Feature.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functions\WPP_FunctionLayer.vbs")
App.Test.Settings.Resources.Libraries.Add("D:\Ranger Automation\Class\Functions\WPP_Functions.vbs")
App.Test.Settings.Web.BrowserNavigationTimeout = 60000
App.Test.Settings.Web.ActiveScreenAccess.UserName = ""
App.Test.Settings.Web.ActiveScreenAccess.Password = ""

App.Folders.RemoveAll

Dim objRepositoryFolder,repositoryFolder,repositoryFiles,repositoryFile
Set objRepositoryFolder = CreateObject("Scripting.FileSystemObject")
Set repositoryFolder = objRepositoryFolder.GetFolder("D:\Ranger Automation\Object Repository")
Set repositoryFiles = repositoryFolder.Files

App.Test.Actions("Action1").ObjectRepositories.RemoveAll

For Each repositoryFile In repositoryFiles
App.Test.Actions("Action1").ObjectRepositories.Add "D:\Ranger Automation\Object Repository" & "\" & repositoryFile.Name
Next

Call App.Test.Environment.LoadFromFile("D:\Ranger Automation\Class\Environment.xml",true)

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' System Local Monitoring settings
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
App.Test.Settings.LocalSystemMonitor.Enable = false
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Log Tracking settings
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
With App.Test.Settings.LogTracking
.IncludeInResults = False
.Port = 18081
.IP = "127.0.0.1"
.MinTriggerLevel = "ERROR"
.EnableAutoConfig = False
.RecoverConfigAfterRun = False
.ConfigFile = ""
.MinConfigLevel = "WARN"
End With

Tuesday, January 18, 2011

Getting the number of files with same extension in a folder

Flag = 0
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(sPath) 'Path of the folder
Set oFile = oFolder.Files
For each sFile in oFile
Pos = Instr(1,sFile.name,".jpeg",1) ' change the extn as required.
If Pos <> 0 Then
Flag =Flag +1
End If
Next
msgbox Flag

Monday, January 3, 2011

Reading data from a virtual table

This post will help you in reading data from a virtual table. This is really helpful and we took a very long time to come up with this solution. It is very simple but that thought process took some time to set in ;). So here we go.

Create the virtual table using the virtual objects manager. The properties available to you would be Width, Height, Rows, Columns, x, y.

Get the height and width of a single cell by dividing the table width and height by the column and row values respectively.

x and y are the values of the top left corner of the first cell, to get the bottom right corner add the height and width calculated for a single cell. Now use the GetVisibleText property with the parent object.

Like,
Say you have a grid or table that is recognized as a winobject, and you create a virtual table for it. Now the code to read the data from the first cell of the table would be:

val = Window(" ").Page(" ").WinObject(" ").GetVisibleText(x,y,x1,y1)
msgbox val

Wednesday, December 1, 2010

Setting the same value in all child objects

There might be cases where you want to enter the same value in all the objects of the same class like an edit box. This is particularly useful when checking for field level validations. The approach to be followed can be to identify all the childobjects in the page belonging to the same class, and then trying to set the value or retrieve a value. The below piece of code can be used to enter the same text in all the WebEdit objects in the YahooMail page.


Set objIE = CreateObject("InternetExplorer.Application")
objIE.Visible = True
objIE.Navigate "www.yahoomail.com"

Browser("Google").Page("Yahoo! Mail: The best").Sync
Set objDesc = Description.Create
objDesc("micclass").Value = "WebEdit"

Set Child = Browser("Google").Page("Yahoo! Mail: The best").ChildObjects(objDesc)

For iCount = 0 to Child.count -1
Child(iCount).Highlight
Child(iCount).Set "Divya Rakesh"
Next

Associating all the library files from a folder before start

Using the below code you can add all the library files in folder from a vbs script at the beginning of the session. This same vbs file can be used for doing all the settings as well, like opening QTP, opening the test, associating all resources and then running the test. You can easily get the script by modifying the script that is generated when the user gives Generate script in the File Settings. The below part of the code can be updated to this vbs file to associate all the library file from a given folder.


Set objFile = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFile.GetFolder("E:\Automation\Library")
Set objFiles = objFolder.Files

For each sFile in objFiles
sExtn = Right (sFile, 3)
If sExtn = "vbs" or sExtn = "qfl" Then
App.Test.Settings.Resources.Libraries.Add sFile
End If

Next

Wednesday, October 27, 2010

Lock your machine through the script

Add the below code to end of script to lock the machine automatically

Set obj = CreateObject("WScript.Shell")
sCmnd = "%windir%\SYSTEM32\rundll32.exe user32.dll,LockWorkStation"
obj.Run sCmnd, 0, False
Set obj =nothing

Tuesday, October 19, 2010

Getting the Machine Name through the Script

The below piece of code will give you the machine name and the user name of the pc where it is running. This is particularly useful when we need system parameters:

Set oWshNetwork = CreateObject("WScript.Network")
sMachine = oWshNetwork.ComputerName
sUser = oWshNetwork.UserName
msgbox sMachine
msgbox sUser
You can get all other system params also using similar codes using WScript.Network

Thursday, October 14, 2010

Memory Usage Using WMI

The below code can be used to get the memory usage, peak memory usage and the virtual memory usage as in the Task Manager without opening it. Here we are using the WMI object methods:

' To get the Machine Name

Set objWMISvc = GetObject( "winmgmts:\\.\root\cimv2" )
Set colItems = objWMISvc.ExecQuery( "Select * from Win32_ComputerSystem", , 48 )
For Each objItem in colItems
PCName = objItem.Name
Next

'To get the Memory Values

On Error Resume Next
arrComputers = Array(PCName)
For Each strComputer In arrComputers

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_Process")
For Each objItem In colItems

If objItem.Name = "ProcessNameYouWant.exe" Then
VM = objItem.PageFileUsage/1024
End If
Next

Set MemItems = objWMIService.ExecQuery("SELECT * FROM Win32_PerfFormattedData_PerfProc_Process", "WQL", _
wbemFlagReturnImmediately + wbemFlagForwardOnly)

For Each objItem In MemItems

If objItem.Name = "ProcessNameYouWant" Then
mem = objItem.WorkingSet/1024
peak = objItem.WorkingSetPeak/1024
End If
Next
Next

Wednesday, October 13, 2010

Add or Remove the Recovery Scenario dynamically from tge script

The below code is helpful in adding and removing the Recovery Scenario dynamically from the settings. This case would be particularly required in case where there is a looping of the recovery scenarios, i.e, a recovery scenario is triggered when inside another recovery scenario.

Here goes the code:
Set qtApp = CreateObject("QuickTest.Application")
Set qtTestRecovery = qtApp.Test.Settings.Recovery

'This part of the code is used to remove all the existing recovery scenarios associated with the test
If qtTestRecovery.Count > 0 Then
qtTestRecovery.RemoveAll
End If

' This is used to add the recovery scenarios. The first parameter is the location of the qrs file. 2nd parameter is the scenario name as given at the time of creating the recovery scenario and 3rd is the priority (used when multiplr scenarios need to be added. At that time we can have 1,2,3 etc)
qtTestRecovery.Add "E:\RecoveryScenario.qrs", "RecoveryScenario" , 1

For intIndex = 1 To qtTestRecovery.Count
qtTestRecovery.Item(intIndex).Enabled = True
Next
qtTestRecovery.Enabled = true

qtTestRecovery.SetActivationMode "OnError"
Set qtApp = Nothing
Set qtTestRecovery = Nothing

'Only if the below line of code is added the recovery scenario would be added to your code.
Recovery.Enabled= True

Tuesday, September 21, 2010

Recovery Scenario for Unknown Window

The following code can be added in the recovery scenario as a function call. When the occurence is set to "On Error" it will check for any unknown window, if it finds this unknown window, it will click ok or cancel button or any other button which we are giving in the script. If there is not such unwindow and still the object expected by QTP is not visible, then it will also click Retry for the QTP error.

This is very important since we are handling here both application generated as well as QTP generated errors. You can also add the function for caputuring the screenshot here to make it an excellent looking Recovery Scenario.

Function UnknownWindow(Object, Method, Arguments, retVal)

Dim var

var=Array("&No","OK","Ok", "Cancel", "Close")
Set o_Desc=description.Create
Set o_Nobutn=description.Create
o_Desc("Class Name").value="Dialog"
o_Desc("ispopupwindow").value=True

If Window(o_Desc).Exist Then
Window(o_Desc).Activate
Arr_Count=Ubound(var)

For i= 0 to Arr_Count
o_Nobutn("text").value=var(i)
If Window(o_Desc).winbutton(o_Nobutn).Exist(0) Then
Enabled = Window(o_Desc).winbutton(o_Nobutn).GetROProperty("enabled")
If Enabled = "True" Then
Exit For
End If

End If
Next
Window(o_Desc).winbutton(o_Nobutn).Click
Else

QTP_Error

End If

End Function

'-----------------------------------------------------------


Public Function QTP_Error

count = 1
For Count = 1 to 2
Set WshShell =CreateObject("WScript.Shell")
Btncode = WshShell.Popup ("object is disabled", 1)
WshShell.SendKeys "{TAB}"
wait 2
WshShell.SendKeys "~"
Next
CloseApplication
ExitTestIteration

End Function

Capturing the screenshot in case of error

The following piece of code can be inserted as a fucntion call in you recovery scenario. If you set the occurence as "On Error", it will take the screenshot of your screen in the event of an error. This is helpful in understanding what exactly happend before the recovery scenario was triggered.

Dim filename

Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FolderExists("D:\Automation\Results\Screenshots")= "False" Then
FSO.CreateFolder("D:\Automation\Results\Screenshots")
End If

timenow = now
timenw= split (timenow, " ")
filename = RecipeNo &"_"&timenw(1)&".png"
filename = Replace(filename,"/","")
filename = Replace(filename,":","")
filename = "D:\Ranger Automation\Results\Screenshots"&"\"&filename
Desktop.CaptureBitmap filename,true
Reporter.ReportEvent micFail,"image","<"

Create a line chart in excel

Set Excel = CreateObject("Excel.Application")
Set Book = Excel.Workbooks.Open("E:\Performance.xls")
Set Sheet = Book.Worksheets(1)

Set Range = Sheet.UsedRange
Range.Select ' Selects the area in the excel sheet with the data

Set Charts= Excel.Charts
Charts.Add

Set objCharts = Charts(1)
objCharts.Activate

objCharts.ChartType = 65 ' This will select a line chart

objCharts.SeriesCollection(1).Border.Weight = -4138 'Used to increase the width of the line in the graph
objCharts.SeriesCollection(2).Border.Weight = -4138
objCharts.SeriesCollection(3).Border.Weight = -4138

Book.Save
Excel.Quit

For more details and other types of charts. Please refer the website:
http://technet.microsoft.com/en-us/library/ee692900.aspx

Monday, August 30, 2010

Creating, Renaming and Data Entry in Excel

The below code is for creating your own excel application, custom naming the sheets and entering data in an excel. This is very useful if you have to get some data from the application and your datatable already has some other application input data. Basically a case where you need to have more than one excel sheets.

Set Excel = CreateObject("Excel.Application")
Set Book = Excel.Workbooks.Add
Set Sheet = Book.Worksheets(1)
Sheet.Name = "Results"
Sheet.Rows(1).Columns(1).value = "This is the first Sheet"

Book.SaveAs "D:\Results.xls"
Book.Close
Excel.Quit

To Rename the second sheet you just need to modify the Worksheet id in the above code. It would look like

Set Excel = CreateObject("Excel.Application")
Set Book = Excel.Workbooks.Open ("D:\Results.xls")
Set Sheet1 = Book.Worksheets(2)
Sheet1.Name = "Output_Data"

You need not close the excel to rename the second sheet. This code can be combined with the above code also. As per your needs. But you should make sure that the name does not exceed the default length in excel

Friday, August 27, 2010

Sending mails using Outlook and SMTP

Here we will see how we can send the mail after the test run using outlook and also using SMTP. First let us see how to send the mail using Outlook. This method though useful has the following drawbacks:
1. The system or machine where you are running the scripts should have outlook configured in it
2. The email will be sent in the name of the person whose email has been configured in the outlook.
3. Finally, outlook throws up a security message when you try to send an automated mail and to take care of this you will have to download a third party software called expressclick.

Well, if you still prefer to go by this method, then here is the code

systemutil.Run "C:\Program Files\Express ClickYes\ClickYes.exe"
wait 5
set oMailobj=CreateObject("Outlook.Application")

set oSendmail=oMailobj.CreateItem(0)
oSendmail.To=""
'oSendmail.Cc=""
oSendmail.Subject="Test"
oSendmail.Body="Hi" & vbcrLf & vbCrlf & "PFA the Smoke Test Automation Results" & vbCrlf & vbCrlf & "Thanks" & vbcrlf & "Automation Team"
sAttachment = "D:\Results.zip"
If (sAttachment <> "") Then
oSendmail.Attachments.Add(sAttachment)

Else
Reporter.ReportEvent micInfo,"Sending mail:","Unable to send attachment,please verify your attachment file"
End If
oSendmail.Send
wait 3
set oSendmail=Nothing
set oMailobj=Nothing
SystemUtil.CloseProcessByName "ClickYes.exe"

All these problems can be overcome by using SMTP mail. The only thing that you need to know is the SMTP server name and the machine should be in the network. Once you use this code you will never go back to using Outlook.

Set oMessage = CreateObject("CDO.Message")

oMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2

'SMTP Server
oMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") ="servername or ip"

oMessage.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25

oMessage.Configuration.Fields.Update
oMessage.Subject = "Test"
oMessage.Sender = "" ' any non-existing mail id will also work.
oMessage.To =""
'oMessage.CC = ""
'oMessage.BCC = ""

oMessage.AddAttachment "D:\Results.zip"
oMessage.TextBody = "Hi" & vbcrLf & vbCrlf & "PFA the Smoke Test Automation Results & vbCrlf & vbCrlf & "Thanks" & vbcrlf & "Automation Team" & vbCrlf & vbCrlf & vbCrlf &"*********************************************************************************************************" & vbcrlf & "This is an auto-generated email. Please do not reply to this email." & vbcrlf &"*********************************************************************************************************"
oMessage.Send

Set oMessage = Nothing

Tuesday, August 17, 2010

How to close an application opened through QTP

For opening an application through QTP we use the command SystemUtil.Run. We have a similar command for closing the opened function we as well. Both opening and closing an application called "application" is illustrated below:

Opening an application through QTP:
SystemUtil.Run "C:\Program Files\Application.exe", " ", "C:\Program Files", " "

Closing the same applcation through QTP:
SystemUtil.CloseProcessByName "Application.exe"

Other similar commands available are mentioned below and their names are self explainatory.
SystemUtil.CloseDescendentProcesses
SystemUtil.CloseProcessByHwnd
SystemUtil.CloseProcessById
SystemUtil.CloseProcessByWndTitle

Monday, August 16, 2010

How to search for data in a tab separated log file

Set Fso = CreateObject("Scripting.FileSystemObject")

Const ForReading = 1, ForWriting = 2
Set File1 = Fso.OpenTextFile ("abc.txt", ForReading, True)


Do While File1.AtEndOfStream <> True

text = File1.ReadLine()
newtext = replace (text, " ", " ")' Copy the tab from the Notepad and paste here.For details check the syntax for Replace function in QTP help

data = split (newtext, " ")
For i = Lbound(data) to UBound(data)
If data(i) = "TimeStamp" Then
msgbox "true"
End If
Next
Loop