The online community for software testing & quality assurance professionals
 
 
Calendar   Today's Topics
Sponsors:




Lost Password?

Home
BetaSoft
Blogs
Jobs
Training
News
Links
Downloads



Testing Tools >> Micro Focus/Borland/Segue SilkTest

Pages: 1 | 2 | 3 | >> (show all)
Bapanna Setti
Member


Reged: 03/24/04
Posts: 21
Loc: Noida
Donate a user defined function to this topic
      #26222 - 04/07/04 01:27 AM

Hi all,

I would like to initialize an evergreen topic in this forum.
Each person will contribute to this topic by submitting a useful
user defined function or existing method or workaround to a known problem.
It will be very nice to see the invaluable findings together.
Please submit only code related solutions rather than environment related. If the problem is debatable please start a new topic. Thanks in advance.

I am starting this topic with the following three small functions
code:
 
[-] CreateResultFile(STRING fname)
[ ] HFILE FileHandle
[ ] // Open file, If exists delete contents else create a new file
[ ] FileHandle = FileOpen (fname, FM_WRITE)
[ ] FileClose (FileHandle)

[-] PrintToResultFile(STRING str,STRING fname)
[ ] HFILE FileHandle
[ ] // Open file, append line, and close
[ ] FileHandle = FileOpen (fname, FM_APPEND)
[ ] FileWriteLine (FileHandle, str)
[ ] FileClose (FileHandle)
//in the test plan we can call CreateResultFile(STRING fname)to initialize result file in first test case.
// Afterwords we can append any results(User defined) to this file by calling PrintToResultFile(STRING str,STRING fname)from any test case in that plan

[-] String timestamp()
[ ] DATETIME DayAndTime
[ ] STRING sTime
[ ] STRING sDate
[ ] String stamp
[ ] // get current date and time
[ ] DayAndTime = GetDateTime ()
[ ] // format current date and time
[ ] sTime = FormatDateTime (DayAndTime, "hhnnss")
[ ] sDate = FormatDateTime (DayAndTime, "mmddyy")
[ ] stamp= sDate+sTime
[ ] return stamp
//This functions works well when we need a random string or unique string



Post Extras: Print Post   Remind Me!   Notify Moderator  
blacst
Member


Reged: 01/15/02
Posts: 295
Loc: Des Moines, Iowa
Re: Donate a user defined function to this topic
      #26223 - 04/08/04 12:37 AM

This function will find out which version of IE is installed on the PC and set the browser type to that version. It does a Registery dip for the version info. Same concept could work for Netscape as well.


code:
[-] boolean SetBrowserEnvironment()
[ ] BROWSERTYPE btType
[ ] INTEGER iKey = HKEY_LOCAL_MACHINE
[ ] STRING sPath = "Software\Microsoft\Internet Explorer"
[ ] STRING sItem = "Version"
[ ] STRING sBrowserVersion = SYS_GetRegistryValue (iKey, sPath, sItem)//Get the version of the browser from this machine/
[-] if left (sBrowserVersion, 1) == '5' //Set the Browser to be Internet explorer 5
[ ] btType = explorer5_DOM
[-] if left (sBrowserVersion, 1) == '6' //Set the Browser to be Internet explorer 6
[ ] btType = explorer6_DOM
[-] if left (sBrowserVersion, 1) == '4' //Set the Browser to be Internet explorer 4
[ ] btType = explorer4
[ ]
[ ] SetBrowserType (btType)



Post Extras: Print Post   Remind Me!   Notify Moderator  
hseymer
Junior Member


Reged: 10/19/01
Posts: 7
Loc: LONDON UK
Re: Donate a user defined function to this topic
      #26224 - 04/08/04 03:47 AM

Here's a variation on Verify that strongly prefer over the original.
code:
[+] VerifyAndContinue( anytype pInActual ,anytype pInExpected ,string pDesc )
[-] do
[ ] Verify( pInActual ,pInExpected ,pDesc )
[ ] print( "VERIFY "+ pDesc+ " PASSED." )
[ ]
[-] except
[ ] LogVerifyError( pInActual ,pInExpected ,pDesc )
[ ]
[ ]
[+] // NOTES for VerifyAndContinue:
[ ] // Objections to Verify:
[ ] // 1: On PASS ,nothing is written to the .res.
[ ] // 2: On FAIL ,the testcase is terminated immediately.
[ ]
[ ] // Both these objections are overcome by VerfiyAndContinue.
[ ] // 1: On PASS ,"Verify "+ pDesc+ " passed." is written to the .res.
[ ] // 2: On FAIL ,except path prevents termination and LogVerifyError is executed.
[ ]
[ ] // Otherwise Verify behaves nicely.
[ ] // In particular ,it can handle lists of different lengths.
[ ]



Post Extras: Print Post   Remind Me!   Notify Moderator  
shreev
Member


Reged: 12/26/01
Posts: 163
Loc: Boston,MA, USA
Re: Donate a user defined function to this topic
      #26225 - 04/08/04 06:32 AM

Hi All,

Here goes, I had to find out the currently logged user on a system for which I wrote this function -

************************************************
code:
[-] dll "advapi32.dll"
[ ] INT GetRealUserName (out STRING sUserName, inout INT iMaxSize) alias "GetUserNameA"
[-] STRING GetUserName ()
[ ] INT iLen = 1024
[-] if !(GetRealUserName (sUserName, iLen))
[ ] LogWarning ("* Warning: Unable to get UserName")
[ ] print(sUserName)
[ ] return sUserName
[ ]

**************************************************
You can extend this code to delete all browser cookies for the currently logged user by appending the following code -

************************************************
code:
[-] DeleteCookies()
[-] LIST lfFiles
[ ] INTEGER iCount
[ ] STRING sDir = "C:\Documents and Settings\"+sUserName+"\Cookies\"
[ ] lfFiles = SYS_GetDirContents(sDir)
[ ]
[-] for iCount = 1 to ListCount (lfFiles)
[ ] String sExtension
[ ] sExtension = Right((lfFiles[iCount].sName), 3)
[ ]
[-] if sExtension== "txt"
[ ] SYS_RemoveFile(sDir + lfFiles[iCount].sName)



Post Extras: Print Post   Remind Me!   Notify Moderator  
MattGray
Member


Reged: 08/09/99
Posts: 191
Loc: Irvine, CA
Re: Donate a user defined function to this topic
      #26226 - 04/08/04 08:48 AM

Here is a function we use with all of our data-driven test cases. You pass it a data file name and a test case name. The function will execute the test case with every data value present in the file. Data values are expected to be in SilkTest format (ie, the FileReadValue function is used).

code:
[-] void ProcessDataFile (string sDataFile, string sTestCaseFunc)
[-] // About
[ ] //********
// @func | ProcessDataFile |
// Open a given data file, read each record, then execute the given test case.
// @parm string | sDataFile |
// a fully qualified file name, file must be in SilkTest format (comments or lists)
// @parm string | sTestCaseFunc |
// the name of the test case to execute
// @end
//********
[ ] integer iCounter
[ ] HFILE hDataFile
[ ] anytype aDataRecord // Variable to hold the record that is read from the data file
[ ]
[ ] // Verify the input file
[-] if !SYS_FileExists(sDataFile) // If the data file does not exist, then log msg to results and return
[ ] Print("The data file {Upper(sDataFile)} was not found. Nothing will be done.")
[ ] Print("Testcase {sTestCaseFunc} will not be executed, since no input data is present.")
[ ] return
[-] if !SyntaxCheck(sDataFile) // If syntax check fails, then exit the script
[ ] LogException("Data file ({sDataFile}) can't be processed due to a syntax error. Test Aborted.")
[ ] exit
[ ]
[ ] // Process the input file
[ ] hDataFile = FileOpen(sDataFile, FM_READ) // Open the provided data file for read
[-] while FileReadValue (hDataFile, aDataRecord) // Read each record from data file until EOF
[ ] ResOpenList("{aDataRecord}")
[-] do
[ ] @(sTestCaseFunc) (aDataRecord) // Execute provided testcase with current record from data file
[-] except
[ ] cExceptLog()
[ ] ResCloseList()
[ ] FileClose (hDataFile)// Close data file

The ProcessDataFile function uses the following function to make sure the data file is free of syntax errors.

code:
[-] boolean SyntaxCheck(string sDataFile) 
[-] // About
[ ] //********
// @func boolean | SyntaxCheck |
// Test whether a data file is in SilkTest readable format (i.e. lists or records)
// @parm string | sDataFile |
// the fully qualified data file to check.
// @rdesc Return FALSE if file can't be read correctly.
// @end
//********
[ ] HFILE hDataFile
[ ] string sLine
[ ] anytype aLine
[ ] integer iNumLines = 0, iRecLine
[ ] list of string lsResults = {}
[ ] list of integer liRecLine = {}
[ ]
[ ] // Get a list of all the lines on the file that do not begin with "//" or are ""
[ ] hDataFile = FileOpen(sDataFile, FM_READ)
[-] while FileReadLine(hDataFile, sLine)
[ ] iNumLines++
[ ] sLine = Trim(sLine)
[-] if (Left(sLine, 2) != "//") && (sLine != "")
[ ] ListAppend(liRecLine, iNumLines)
[ ] FileClose(hDataFile)
[ ]
[ ] // Read every line into anytype. If exception occurs, add it to error list and keep reading. Comments and blank lines are ignored.
[ ] hDataFile = FileOpen(sDataFile, FM_READ)
[-] for each iRecLine in liRecLine
[-] do
[ ] FileReadValue(hDataFile, aLine)
[-] except
[ ] ListAppend(lsResults, "LINE#:{iRecLine} EXCEPTION: {ExceptData()}")
[ ] FileClose(hDataFile)
[ ]
[ ] // If error list contains any values, then print all the errors and return FALSE
[-] if ListCount(lsResults)
[ ] ListAppend(lsResults, " NOTE: Syntax check only ensures that the SilkTest can read the file into an anytype variable.")
[ ] ListAppend(lsResults, " This does not test whether the data is in the correct record format for a test case function.")
[ ] ResPrintList("Syntax Check failed for file ({sDataFile}). Data is not in SilkTest list or record format. Check all quotes, commas, and curly brackets.",lsResults)
[ ] return FALSE
[ ]
[ ] // File could be read without error, return TRUE
[ ] return TRUE



Post Extras: Print Post   Remind Me!   Notify Moderator  
TonyM
Active Member


Reged: 11/22/99
Posts: 1036
Loc: Eagle, ID,USA
Re: Donate a user defined function to this topic
      #26227 - 04/08/04 09:18 AM

Here is a function to turn off your screen saver. I place this in my ScriptEnter() function.

code:
[-] dll "user32.dll"
[ ] LONG SystemParametersInfo (LONG uAction, LONG uParam, LONG lpvParam, LONG fuWinIni) alias "SystemParametersInfoA"
[ ]
[-] void DisableScreenSaver ()
[ ] SystemParametersInfo (17, 0, 0, 0)



Post Extras: Print Post   Remind Me!   Notify Moderator  
TonyM
Active Member


Reged: 11/22/99
Posts: 1036
Loc: Eagle, ID,USA
Re: Donate a user defined function to this topic
      #26228 - 04/08/04 09:30 AM

This function will cause SilkTest to sleep until a certain time of day. It is smart enough to cross midnight so if current time is 22:00:00 and you pass a value of 02:00:00, it will sleep until 2:00 AM of the following day. This routine will not be able to sleep more than 23 hours 59 minutes 59 seconds. Military time is assumed.

code:
[-] void WaitUntil (STRING sWaitTOD)
[ ]
[ ]
[ ] // Replace / and - with :
[ ] STRING sTempWait = StrTran (sWaitTOD, "/", ":")
[ ] STRING sWaitToUse = StrTran (sTempWait, "-", ":")
[ ] // Get the current time
[ ] STRING sCurrTOD = TimeStr ()
[ ]
[ ] // Convert time to wait until to seconds
[ ] INTEGER iWaitHrs = Val (GetField (sWaitToUse, ":", 1))
[ ] INTEGER iWaitMins = Val (Getfield (sWaitToUse, ":", 2))
[ ] INTEGER iWaitSecs = Val (SubStr (sWaitToUse, 7))
[ ] INTEGER iWaitTODSecs = (3600 * iWaitHrs) + (60 * iWaitMins) + iWaitSecs
[ ]
[ ] // Convert current time to seconds
[ ] INTEGER iCurrHrs = Val (GetField (sCurrTOD, ":", 1))
[ ] INTEGER iCurrMins = Val (Getfield (sCurrTOD, ":", 2))
[ ] INTEGER iCurrSecs = Val (SubStr (sCurrTOD, 7))
[ ] INTEGER iCurrTODSecs = (3600 * iCurrHrs) + (60 * iCurrMins) + iCurrSecs
[ ]
[ ] // Calculate total seconds to sleep
[ ] INTEGER iTotalSleepSecs = iWaitTODSecs - iCurrTODSecs
[ ]
[ ] // If the total is >= to 0 then sleep for this many seconds
[-] if (iTotalSleepSecs >= 0)
[ ] Sleep (iTotalSleepSecs)
[ ]
[ ] // Else normalize the number of seconds by adding the total
[ ] // number of seconds in one day and then sleeping this many
[ ] // seconds
[-] else
[ ] INTEGER iNormSleepSecs = ((24 * 3600) + iTotalSleepSecs)
[ ] Sleep (iNormSleepSecs)
[ ] Print ("Normal sleep secs = {iNormSleepSecs}")



Post Extras: Print Post   Remind Me!   Notify Moderator  
testingdocs
Member


Reged: 02/28/05
Posts: 308
Loc: Bangalore, India
Re: Donate a user defined function to this topic
      #26229 - 06/21/06 07:57 PM

Great Topic Bopanna [Smile]

This function is used to print the exception
code:
[-] Exception ()
[ ] const CRLF = Chr(10)
[ ] CALL Call
[ ] LIST OF CALL lCall
[ ] String sResult
[ ] Integer iInc
[ ] lCall = ExceptCalls ()
[ ] sResult = ExceptData()
[ ] iInc=1
[-] for each Call in lCall
[-] if iInc > 1
[ ] sResult = sResult+"{CRLF}Script: {Call.sModule}{CRLF}Testcase: {Call.sFunction}{CRLF}Line: {Call.iLine}"
[ ] iInc++
[ ] Print("------------------------ Exception Call - Start ------------------------")
[ ] Print(sResult)
[ ] Print("------------------------ End ------------------------")

Hi Guys, don't stop with your functions alone, it will be useful if you post the problem you faced and the tips to overcome it.

Ex.
To get text from disabled Textbox

Goto menu Options > Agent, click on Verification tab and uncheck flag 'Verify that windows are enabled'. This will allow you to operate with disabled control

or thru script
code:
Agent.SetOption (OPT_VERIFY_ENABLED, FALSE)



[ 06-21-2006, 08:06 PM: Message edited by: testingdocs ]


Post Extras: Print Post   Remind Me!   Notify Moderator  
cwBrendan
Member


Reged: 02/17/04
Posts: 292
Loc: Canada
Re: Donate a user defined function to this topic
      #26230 - 06/22/06 09:49 AM

This code allows you to get and set regional settings. It currently only has constants setup for short date, long date and negative currency settings since those are the only 3 that we change right now.

code:
[ ] use "msw32.inc"
[ ]
[ ]
[+] dll "kernel32.dll"
[ ] INT GetLocaleInfoA(Long locale, Long LCType, String lpLCData, Long cchData)
[ ] INT SetLocaleInfoA(Long locale, Long LCType, String lpLCData)
[ ] LONG GetUserDefaultLCID()
[ ] DWORD GetLastError()
[ ]
[-] window AnyWin Utils
[ ]
[ ] // Constants for ...RegionalSetting() functions
[ ] const LONG SHORT_DATE = 31 // LOCALE_SSHORT_DATE
[ ] const LONG LONG_DATE = 32 // LOCALE_SLONG_DATE
[ ] const LONG NEG_CURRENCY = 28 // LOCALE_INEGCURR
[ ]
[ ] // See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/intl/nls_8rse.asp for details
[ ] // on the correct values for each setting. The comments on each line specify the actual name
[ ] // used in the Windows API.
[ ]
[ ]
[ ] // @HELP
[ ] // @class: Utils
[ ] // @method: SetRegionalSetting(iType, sNewValue)
[ ] // @parameter: iType: the regional setting to change. see list of contents in this file.
[ ] // @parameter: sNewValue: the new value for the regional setting.
[ ] // @notes: assigns the string in sNewValue to the regional setting referred to by iType.
[ ] // @END
[+] BOOLEAN SetRegionalSetting(INTEGER iType, STRING sNewValue)
[ ]
[ ] INTEGER result
[ ] INTEGER error
[ ] LONG locale
[ ]
[ ] locale = GetUserDefaultLCID()
[ ] result = SetLocaleInfoA(locale, iType, sNewValue)
[ ]
[ ] // If there was an error call GetLastError() to find out what happened
[+] if(result == 0)
[ ] error = GetLastError()
[ ]
[ ] // Display the proper error message
[+] if(error == 1004)
[ ] LogWarning("Error: invalid flag. This probably means you entered an invalid Regional Setting type.")
[+] else if(error == 87)
[ ] LogWarning("Error: invalid parameter. This probably means the new value you entered was invalid.")
[+] else
[ ] LogWarning("Error: invalid access. This probably means you don't have permission to change the Regional Settings.")
[ ] return(false)
[ ]
[ ] return(true)
[ ]
[ ]
[ ]
[ ]
[ ] // @HELP
[ ] // @class: Utils
[ ] // @method: GetRegionalSetting(iType)
[ ] // @parameter: iType: the regional setting to retrieve. see list of contents in this file.
[ ] // @notes: returns the value of the regional setting referred to by iType.
[ ] // @END
[+] STRING GetRegionalSetting(INTEGER iType)
[ ]
[ ] Long locale
[ ] String data
[ ] Long dataLen
[ ] int result, error
[ ]
[ ] locale = GetUserDefaultLCID()
[ ] result = GetLocaleInfoA(locale, iType, [out]data, [out]dataLen)
[ ]
[ ] // If there was an error call GetLastError() to figure out what happened
[+] if(result == 0)
[ ] error = GetLastError()
[ ]
[+] if(error == 1004)
[ ] LogWarning("Error: invalid flag. This probably means you entered an invalid Regional Setting type.")
[+] else if(error == 87)
[ ] LogWarning("Error: invalid parameter. This probably means the new value you entered was invalid.")
[+] else
[ ] LogWarning("Error: insufficient buffer.")
[ ]
[ ]
[ ] return(data)
[ ]
[ ]
[ ]
[+] testcase SetDateFormat() appstate none
[ ]
[ ] Utils.SetRegionalSetting(Utils.SHORT_DATE, "dd/MM/yyyy")
[ ]
[ ]

Hope someone finds this useful.

Brendan


Post Extras: Print Post   Remind Me!   Notify Moderator  
fencer_Dan
Member


Reged: 10/17/05
Posts: 124
Loc: Northern Colorado
Re: Donate a user defined function to this topic
      #26231 - 06/23/06 03:08 PM

Great thread!

Here is a Virtual Machine class I wrote. It is specifically for Microsoft VM 2004, but I plan on extending it for VMWare quite soon.

References to the logging class can be replaced by simple Prints or whatever you use.

code:
[ ] // ***********************************************************************
[ ] // File Name : VMachine.INC
[ ] // Description : SilkTest include file for MS Virtual PC 2004 abstraction.
[ ] // Author : Dan Brandow - dbrandow (at) excelsiorsoftware (dot) com
[ ] // ***********************************************************************
[ ]
[+] // Description:
[ ] // The VMachineClass is designed to let the Test Engineer utilize Virtual PCs
[ ] // in their testing with minimal impact to their existing scripts. This class is
[ ] // designed for Microsoft Virtual PC 2004 specifically, but can be easily
[ ] // modified.
[ ] //
[ ] // Please note the assumptions posted within the class description, as well
[ ] // as the other tool requirements listed in the included files. This class also
[ ] // requires the PSTools toolset from www.sysinternals.com.
[ ] //
[ ] // Please note that some items in the "initialization" section of each function
[ ] // may need to be updated to match your specific situation (for example, the
[ ] // restart license server function works best if the command string is actually
[ ] // pointing to the "restartServer.bat" file. :)
[ ] //
[ ] // This code is Copyright 2006 by Daniel J. Brandow. Permission to reuse
[ ] // and redistribute is given as long as the following conditions are met:
[ ] // * The headers, including this Copyright notice is left intact, with proper
[ ] // credit retained.
[ ] // * Modifications, improvements and expansions must be transmitted to the
[ ] // original author, Daniel J. Brandow, to be shared with the community.
[ ] // The author can be reached at dbrandow (at) excelsior (dot) com.
[ ] //
[ ]
[ ] // To-do: Assumes the VM Server/VMs are running locally. Fix that.
[ ]
[ ]
[+] // General initialization
[ ] const STRING VM_USER = "YOUR_USER_NAME"
[ ] const STRING VM_PASSWORD = "YOUR_USER_PASSWORD"
[ ] const STRING VM_FILE_EXTENSION = ".vmc"
[ ] const STRING VM_DATA_DIRECTORY = "C:\My Virtual Machines\" // Base directory for your VMs
[ ] // NOTE: Store your VMs in this form: {VM_DATA_DIRECTORY}{sVMName}\{sVMName}.vmc
[ ] // Example: C:\My Virtual Machines\VMxpsp2\VMxpsp2.vmc
[ ] const STRING VM_SHARED_DIR = "Z:\"
[ ] const INTEGER NO_AGENT = 0
[ ] const INTEGER VM_STARTUP_WAIT = 30 // Waiting a minimum time before even trying to connect.
[ ] const INTEGER MAX_VMBOOT_RETRIES = 10
[ ] const INTEGER MAX_AGENT_START_RETRIES = 10
[ ] const INTEGER DEFAULT_AGENT_PORT = 2965
[ ]
[ ] INTEGER iReturnValue = 0
[ ] BOOLEAN bReady = FALSE
[ ] LIST OF STRING lsResults = {}
[ ]
[-] VOID RestartLicenseServer ()
[+] // ***** DESCRIPTION *****
[ ] // Runs the Restart License Server batch file on the host system.
[ ] // Done in case of license issues on VMs.
[+] // Initialization
[ ] const STRING sRestartServer = 'start "" "C:\Program Files\Segue\SilkMeter\bin\restartServer.bat"'
[ ] Log.Write ("License server is being restarted.", "INFO", TRACE_WARNING)
[ ] hHost->SYS_Execute (sRestartServer)
[ ] Sleep (3) // The server seems to need a few extra seconds before being hit.
[-] LIST OF STRING ReduceList (LIST OF STRING lsInput, STRING sPattern)
[+] // Description:
[ ] // This function takes a list of string and a pattern string to match.
[ ] // It takes each line in the list and looks for the pattern. If the
[ ] // pattern is found, the line is appended to the returned list.
[ ] LIST OF STRING lsTemp = {}
[ ] STRING sLine = ""
[-] for each sLine in lsInput
[-] if (StrPos (sPattern, sLine) != 0)
[ ] ListAppend (lsTemp, sLine)
[ ] return lsTemp
[ ]
[ ] use "Infrastructure\PSTools\psinfo.inc"
[ ]
[+] winclass VMachineClass : MainWin // Microsoft Virtual PC 2004
[+] // Description:
[ ] // Assumes VPC is installed, and the .vmc extension is registered.
[ ] // Assumes each VM is configured to log in automatically as {VM_USER} with {VM_PASSWORD}
[ ] // Assumes each VM is set to shut down and discard changes upon exit.
[ ] // Assumes each VM is in {VM_DATA_DIRECTORY}{sVMName}\{sVMName}{VM_FILE_EXTENSION}
[ ] // Assumes each VM computer name is {sVMName}
[ ] // Assumes that the Agent can be started/Connected and stopped/Disconnected
[ ] // Any number of times between Constructing/Destructing the VM.
[+] // Data
[ ] BOOLEAN bConstructed = Constructor (SubStr (WindowTag (this), 2))
[ ] STRING sVMName // Set by VMachineConstructor and NULLed by VMachineDestructor
[ ] LIST OF STRING lsMachineInfo // Set by VMachineConstructor and NULLed by VMachineDestructor
[ ] INTEGER iAgentPID // Set by StartAgent, NULLed by StopAgent
[ ] INTEGER iAgentTCP // Set by StartAgent, NULLed by StopAgent
[ ] HMACHINE hVMHandle = NULL // Set by VMConnect and NULLed by VMDisconnect
[ ]
[ ] // VM Window GUI elements included just in case someone wants to affect the GUI
[ ] // with an agent running on the server. I don't, but someone might.
[+] Menu Action
[ ] tag "Action"
[+] MenuItem FullScreenMode
[+] multitag "Full-Screen Mode"
[ ] "$10200"
[+] MenuItem CtrlAltDel
[+] multitag "Ctrl+Alt+Del"
[ ] "$10323"
[+] MenuItem Pause
[+] multitag "Pause"
[ ] "$10201"
[+] MenuItem Reset
[+] multitag "Reset"
[ ] "$10202"
[+] MenuItem Close
[+] multitag "Close"
[ ] "$10203"
[+] MenuItem InstallOrUpdateVirtualMach
[+] multitag "Install or Update Virtual Machine Additions"
[ ] "$10204"
[+] MenuItem Properties
[+] multitag "Properties"
[ ] "$10115"
[+] Menu Edit
[ ] tag "Edit"
[+] MenuItem Copy
[+] multitag "Copy"
[ ] "$57634"
[+] MenuItem Paste
[+] multitag "Paste"
[ ] "$57637"
[+] MenuItem SelectAll
[+] multitag "Select All"
[ ] "$10210"
[+] MenuItem Settings
[+] multitag "Settings"
[ ] "$10211"
[+] Menu CD
[ ] tag "CD"
[+] MenuItem UsePhysicalDriveD
[+] multitag "Use Physical Drive D:"
[ ] "$10400"
[+] MenuItem CaptureISOImage
[+] multitag "Capture ISO Image"
[ ] "$10309"
[+] MenuItem ReleaseCD
[+] multitag "Release CD"
[ ] "$10312"
[+] MenuItem EjectCD
[+] multitag "Eject CD"
[ ] "$10311"
[+] Menu Floppy
[ ] tag "Floppy"
[+] MenuItem CaptureFloppyDiskImage
[+] multitag "Capture Floppy Disk Image"
[ ] "$10315"
[+] MenuItem ReleaseDisk
[+] multitag "Release Disk"
[ ] "$10317"
[+] Menu Help
[ ] tag "Help"
[+] MenuItem VirtualPCHelp
[+] multitag "Virtual PC Help"
[ ] "$10120"
[+] MenuItem VirtualPCOnline
[+] multitag "Virtual PC Online"
[ ] "$10121"
[+] MenuItem AboutVirtualPC
[+] multitag "About Virtual PC"
[ ] "$10124"
[+] StatusBar StatusBar
[ ] tag "$59393"
[+] DynamicText DynamicText1
[ ] tag "#1"
[+] DynamicText DynamicText2
[ ] tag "#2"
[+] DialogBox StatusBox
[ ] tag "$0"
[+] CustomWin Network
[ ] msw tag "[BitMap]$1065"
[+] CustomWin SharedFolder
[ ] msw tag "[BitMap]$1064"
[+] CustomWin FloppyDrive
[ ] msw tag "[BitMap]$1063"
[+] CustomWin CDRomDrive
[ ] msw tag "[BitMap]$1062"
[+] CustomWin HardDrive
[ ] msw tag "[BitMap]$1060"
[+] CustomWin VMClientArea
[ ] msw tag "[AfxWnd70s]$1010"
[ ]
[+] BOOLEAN Constructor(STRING sName)
[ ] INTEGER iNameFront = StrPos("]", sName)
[ ] INTEGER iNameEnd = Len (sName) - 1
[ ] STRING sShortName = Right (Left (sName, iNameEnd), iNameEnd - iNameFront)
[ ] Log.Write ("Constructing VM: {sShortName}.", "INFO", TRACE_WARNING)
[ ] BOOLEAN bTemp = TRUE
[+] if (! IsSet (bConstructed))
[ ] bTemp = FALSE
[ ] sVMName = sShortName
[ ] integer iRetries = 0
[ ] lsResults = {}
[ ] // Try to start the vm. If it is already running, return NULL.
[ ] hHost->SYS_Execute ('start "" "{VM_DATA_DIRECTORY}{sShortName}\{sShortName}{VM_FILE_EXTENSION}"', lsResults)
[ ] // To-do: find all cases where we do/do not return results and handle them.
[ ] if (lsResults != {})
[ ] // If the VM start fails, return NULL.
[+] if ((lsResults != {}) && (lsResults[1] == "The process cannot access the file because it is being used by another process."))
[ ] return FALSE
[ ] // Make sure it starts right by checking back with a psinfo
[ ] Sleep (VM_STARTUP_WAIT)
[ ] bReady = FALSE
[ ] lsResults = {}
[ ] iRetries = 0
[+] while ((iRetries < MAX_VMBOOT_RETRIES) && ! bReady) // VM not running yet...
[ ] lsResults = {}
[ ] lsResults = PSGetInfo (sShortName, VM_USER, VM_PASSWORD)
[ ] // determine if bReady
[+] if (lsResults != {})
[ ] bReady = TRUE
[+] else
[ ] iRetries ++
[ ] sleep (1)
[ ] this.lsMachineInfo = lsResults
[ ]
[ ] Log.Write ("VM operational. Here is the VM's base information:", "INFO", TRACE_WARNING)
[ ] Log.ListWrite (this.lsMachineInfo)
[ ] bTemp = FALSE
[-] if bReady
[ ] // Plug in details about VM from psinfo call and return the window.
[ ] sVMName = sShortName
[ ] lsMachineInfo = lsResults
[ ] iAgentPID = NO_AGENT
[ ] iAgentTCP = NO_AGENT
[ ] bTemp = TRUE
[ ] return bTemp
[+] window Destructor()
[+] // Initialization:
[ ] const STRING sKillVM = '{PS_BIN_DIR}psexec \\{sVMName} -u {VM_USER} -p {VM_PASSWORD} -d -i "C:\WINDOWS\SYSTEM32\SHUTDOWN.EXE" -s -t 5'
[ ] const STRING sWaitForVMShutdown = '"{sSilkRoot}\Infrastructure\VMachine\WaitForApp.exe" "{sVMName} - Microsoft Virtual PC 2004"'
[ ] Log.Write ("Destroying VM: {sVMName}.", "INFO", TRACE_WARNING)
[ ] lsResults = {}
[ ] hHost->SYS_Execute (sKillVM, lsResults)
[+] if (hVMHandle != NULL)
[ ] VMDisconnect ()
[ ] Sleep (4)
[ ] // Wait until VM shuts down.
[ ] lsResults = {}
[ ] hHost->SYS_Execute (sWaitForVMShutdown, lsResults)
[+] if (lsResults != {})
[ ] Log.Write ("Error in VM shutdown.", "INFO", TRACE_WARNING)
[ ] Log.ListWrite (lsResults)
[ ] lsMachineInfo = {}
[ ] iAgentPID = NULL
[ ] iAgentTCP = NULL
[ ] sVMName = ""
[ ] hVMHandle = NULL
[ ] return NULL
[ ]
[+] BOOLEAN AgentRunningCorrectly ()
[+] // Description:
[ ] // This function performs a remote netstat on the VMachine to see if the Agent is
[ ] // actually running on the port assigned to it.
[ ] // This function assumes this.iAgentPID and iAgentTCP contain valid information.
[ ] // If either of them are NULL, this function immediately returns FALSE.
[ ] // The netstat information is parsed for the correct port and PID. If the correct
[ ] // information is found, TRUE is returned, otherwise FALSE.
[ ]
[+] // Initialization:
[ ] STRING sLine = ""
[ ] BOOLEAN bReturn = FALSE
[+] if ((this.iAgentPID == NULL) || (this.iAgentTCP == NULL))
[ ] return FALSE
[ ] LIST OF STRING lsActiveTCP = GetTCPorts (this.sVMName, VM_USER, VM_PASSWORD)
[+] // Example netstat information:
[ ] // C:\PSTools>psexec \\VMxpsp2 -u Adman -p HPis4me2 "C:\WINDOWS\system32\netstat.exe" -anop TCP
[ ] //
[ ] // returns this if the agent is NOT present:
[ ] // PsExec v1.63 - Execute processes remotely
[ ] // Copyright (C) 2001-2005 Mark Russinovich
[ ] // Sysinternals - www.sysinternals.com
[ ] //
[ ] //
[ ] //
[ ] // Active Connections
[ ] //
[ ] // Proto Local Address Foreign Address State PID
[ ] // TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 768
[ ] // TCP 0.0.0.0:445 0.0.0.0:0 LISTENING 4
[ ] // TCP 10.10.10.55:139 0.0.0.0:0 LISTENING 4
[ ] // TCP 10.10.10.55:139 10.10.10.122:3158 SYN_RECEIVED 4
[ ] // TCP 10.10.10.55:445 10.10.10.122:3157 ESTABLISHED 4
[ ] // TCP 127.0.0.1:1028 0.0.0.0:0 LISTENING 112
[ ] // C:\WINDOWS\system32\netstat.exe exited on VMxpsp2 with error code 0.
[ ] //
[ ] //
[ ] // ...and this if it is sucessful:
[ ] // (NOTE: agent is listening on assigned (or default) port (in this case, 2965))
[ ] //
[ ] // (NOTE: if we were connected the foreign address would point to us, and
[ ] // "LISTENING" would be replaced by "ESTABLISHED")
[ ] //
[ ] // (NOTE: oh, yeah... we get the PID of the Agent too.)
[ ] //
[ ] //
[ ] // PsExec v1.63 - Execute processes remotely
[ ] // Copyright (C) 2001-2005 Mark Russinovich
[ ] // Sysinternals - www.sysinternals.com
[ ] //
[ ] //
[ ] //
[ ] // Active Connections
[ ] //
[ ] // Proto Local Address Foreign Address State PID
[ ] // TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 768
[ ] // TCP 0.0.0.0:445 0.0.0.0:0 LISTENING 4
[ ] // TCP 10.10.10.55:139 0.0.0.0:0 LISTENING 4
[ ] // TCP 10.10.10.55:139 10.10.10.122:3162 SYN_RECEIVED 4
[ ] // TCP 10.10.10.55:445 10.10.10.122:3161 ESTABLISHED 4
[ ] // TCP 10.10.10.55:1041 10.10.10.122:5461 ESTABLISHED 376
[ ] // TCP 10.10.10.55:2965 0.0.0.0:0 LISTENING 376
[ ] // TCP 127.0.0.1:1028 0.0.0.0:0 LISTENING 112
[ ] // C:\WINDOWS\system32\netstat.exe exited on VMxpsp2 with error code 0.
[ ] //
[ ] //
[ ] //
[ ] // ... and if the Agent blew up, we get something like this:
[ ] // (NOTE: no agent listening, just like when it is unstarted)
[ ] //
[ ] // PsExec v1.63 - Execute processes remotely
[ ] // Copyright (C) 2001-2005 Mark Russinovich
[ ] // Sysinternals - www.sysinternals.com
[ ] //
[ ] //
[ ] //
[ ] // Active Connections
[ ] //
[ ] // Proto Local Address Foreign Address State PID
[ ] // TCP 0.0.0.0:135 0.0.0.0:0 LISTENING 768
[ ] // TCP 0.0.0.0:445 0.0.0.0:0 LISTENING 4
[ ] // TCP 10.10.10.55:139 0.0.0.0:0 LISTENING 4
[ ] // TCP 10.10.10.55:139 10.10.10.122:3170 SYN_RECEIVED 4
[ ] // TCP 10.10.10.55:445 10.10.10.122:3169 ESTABLISHED 4
[ ] // TCP 10.10.10.55:1043 10.10.10.122:5461 ESTABLISHED 408
[ ] // TCP 127.0.0.1:1028 0.0.0.0:0 LISTENING 112
[ ] // C:\WINDOWS\system32\netstat.exe exited on VMxpsp2 with error code 0.
[ ]
[+] for each sLine in lsActiveTCP
[+] if ((StrPos(Str(this.iAgentPID), sLine) != 0) && (StrPos(":" + Str(this.iAgentTCP), sLine) != 0))
[ ] bReturn = TRUE
[ ] return bReturn
[+] BOOLEAN StartAgent (INTEGER iPort optional)
[+] if (iPort == NULL)
[ ] iPort = DEFAULT_AGENT_PORT
[ ] const STRING sStartAgent = '{PS_BIN_DIR}psexec \\{this.sVMName} -u {VM_USER} -p {VM_PASSWORD} -d -i "C:\Program Files\Segue\SilkTest\Agent.exe" -p {iPort}' // To-do: move this to psinfo.inc
[ ] Log.Write ("Starting the Agent on machine: {this.sVMName}.", "INFO", TRACE_WARNING)
[ ] bReady = FALSE
[ ] INTEGER iRestartCounter = 0
[+] while (! bReady && (iRestartCounter < MAX_AGENT_START_RETRIES))
[ ] lsResults = {}
[ ] iReturnValue = hHost->SYS_Execute (sStartAgent, lsResults)
[ ] this.iAgentPID = iReturnValue // Agent is running. Its connectability is still debatable...
[ ] this.iAgentTCP = iPort
[ ] Sleep(2) // Let the system stableize before the connect.
[+] if this.AgentRunningCorrectly ()
[ ] Log.Write("Agent Running Correctly.", "INFO", TRACE_DEBUG)
[ ] return TRUE
[+] else
[ ] // if port/PID not found, FAILED and retry
[ ] Log.Write("Agent did not start properly. Restarting the license server and retrying.", "DEBUG", TRACE_DEBUG)
[ ] iRestartCounter ++ // To-do: actually use this value.
[ ] this.StopAgent ()
[ ] this.iAgentPID = NULL
[ ] this.iAgentTCP = NULL
[ ] lsResults = {}
[ ] RestartLicenseServer ()
[ ] Sleep (5) // Allow server to stabilize.
[ ] Log.Write("StartAgent... didn't. Too many retries.", "FAIL", TRACE_ALL)
[ ] return FALSE // if we're here, we failed.
[+] BOOLEAN StopAgent ()
[+] if ((this.iAgentPID == NULL) && (this.iAgentTCP == NULL))
[ ] return TRUE
[ ] const STRING sKillAgent = "{PS_BIN_DIR}pskill -t \\{this.sVMName} -u {VM_USER} -p {VM_PASSWORD} Agent.exe"
[ ] lsResults = {}
[ ] // If connected, disconnect.
[+] if (this.hVMHandle != NULL)
[ ] this.VMDisconnect ()
[ ] hHost->SYS_Execute (sKillAgent, lsResults)
[+] if ! AgentRunningCorrectly ()
[ ] this.iAgentPID = NO_AGENT
[ ] this.iAgentTCP = NO_AGENT
[ ] return TRUE
[+] else
[ ] return FALSE
[+] BOOLEAN VMIsConnected ()
[ ] return IsConnected (this.sVMName)
[+] BOOLEAN VMConnect ()
[ ] HMACHINE hTemp = NULL
[ ] hTemp = Connect (this.sVMName + ":" + Str(this.iAgentTCP))
[+] if (hTemp != NULL)
[ ] this.hVMHandle = hTemp
[ ] Log.Write("VMConnect suceeded.", "DEBUG", TRACE_DEBUG)
[ ] return TRUE
[+] else
[ ] Log.Write("VMConnect... didn't.", "DEBUG", TRACE_DEBUG)
[ ] this.hVMHandow = NULL
[ ] return FALSE
[+] BOOLEAN VMDisconnect ()
[ ] Disconnect (this.hVMHandle)
[ ] this.hVMHandle = NULL
[ ] return TRUE
[+] VOID VMSetMachine ()
[ ] SetMachine (this.hVMHandle)
[+] property Name
[-] STRING Get ()
[ ] return sVMName
[+] property MachineInfo
[-] LIST OF STRING Get ()
[ ] return lsMachineInfo
[+] property VMHandle
[+] HANDLE Get ()
[ ] return hVMHandle
[ ]
[+] window DialogBox AboutVirtualPC
[ ] tag "About Virtual PC"
[+] DialogBox DialogBox1
[ ] tag "$0"
[+] CustomWin AfxWnd70s1
[+] msw multitag "[AfxWnd70s]#1"
[ ] "[AfxWnd70s]$2022"
[+] PageList PageList1
[+] multitag "#1"
[ ] "$12320"
[+] VMachine VMachineConstructor(STRING sName) // To-do: FAIL if VM already exists.
[ ] // Alternative: close and restart VM?
[+] // Description:
[ ] // The use of an outside Constructor function allows us to set up the Window tag accurately.
[ ] // This allow the Engineer to affect the VMWindow directly -- if they have an active agent on
[ ] // the host, that is.
[ ]
[ ] // To-do: Fail if VM already exists. Alternately, you could kill the other VM and recreate it.
[ ] return VMachineClass ("{sName}*") // Full tag would be "{sName} - Microsoft Virtual PC 2004"
[ ]
[ ] type VMachine is WINDOW
[ ]
[ ] // // NOTE: The testcases refer to machines named "VMxpsp2" and "VM601xp".
[ ] // // you will need to change these machine names to match your system prior
[ ] // // to running these testcases.
[ ] //
[ ] // // Also note you must have 2 agent licenses to run the 2-machine testcases!
[+] // testcase SimpleTest_1_Machine ()
[ ] // VMachine VMxpsp2 = VMachineConstructor ("VMxpsp2")
[ ] // VMxpsp2.StartAgent ()
[ ] // VMxpsp2.VMConnect ()
[ ] //
[ ] // VMxpsp2.VMSetMachine()
[ ] // Agent.DisplayMessage ("{VMxpsp2.sVMName}", "Can you hear me?")
[ ] //
[ ] // VMxpsp2.Destructor ()
[+] // testcase SimpleTest_2_Machines ()
[ ] // VMachine VMxpsp2 = VMachineConstructor ("VMxpsp2")
[ ] // VMxpsp2.StartAgent ()
[ ] // VMxpsp2.VMConnect ()
[ ] //
[ ] // VMachine VM521xpsp2 = VMachineConstructor ("VM601xp")
[ ] // VM601xp.StartAgent ()
[ ] // VM601xp.VMConnect ()
[ ] //
[ ] // VMxpsp2.VMSetMachine()
[ ] // Agent.DisplayMessage ("{VMxpsp2.sVMName}", "Can you hear me?")
[ ] //
[ ] // VM601xp.VMSetMachine ()
[ ] // Agent.DisplayMessage ("{VM601xp.sVMName}", "Can you hear me now?")
[ ] //
[ ] // VMxpsp2.Destructor ()
[ ] // VM601xp.Destructor ()
[ ] //
[+] // testcase List_2_Machines ()
[ ] // LIST OF VMachine lwMachines = {}
[ ] // VMachine vmTemp = NULL
[ ] //
[ ] // const SERVER = 1
[ ] // vmTemp = VMachineConstructor ("VMxpsp2")
[ ] // ListAppend (lwMachines, vmTemp)
[ ] //
[ ] // Print ("The name of the server is Babylon 5.. Er, no. It is actually: " + lwMachines[SERVER].Name)
[ ] //
[ ] // const CLIENT = 2
[ ] // vmTemp = VMachineConstructor ("VM601xp")
[ ] // ListAppend (lwMachines, vmTemp)
[ ] //
[ ] // Print ("The name of the client is Babylon 4.. Er, no. It is actually: " + lwMachines[CLIENT].Name)
[ ] //
[ ] // lwMachines[SERVER].StartAgent ()
[ ] // lwMachines[SERVER].VMConnect ()
[ ] // lwMachines[CLIENT].StartAgent ()
[ ] // lwMachines[CLIENT].VMConnect ()
[ ] //
[ ] //
[-] // for each vmTemp in lwMachines
[-] // spawn
[ ] // vmTemp.hVMHandle->Agent.DisplayMessage (vmTemp.sVMName, "How's it hangin'?")
[ ] // rendezvous
[ ] //
[ ] // [lwMachines[CLIENT].hVMHandle]Agent.DisplayMessage (lwMachines[CLIENT].Name, "Are you seein' this?")
[ ] //
[-] // for each vmTemp in lwMachines
[ ] // vmTemp.Destructor ()
[ ]



Post Extras: Print Post   Remind Me!   Notify Moderator  
KaNoN
Member


Reged: 04/20/06
Posts: 293
Re: Donate a user defined function to this topic
      #26232 - 06/29/06 10:02 AM

I'll join to this thread too. The following functions allow to search for files containing specified text. Result is list of string containing full names of files matching search criteria.
code:
[ ] //*************************************************************************************************
[+] //* Function: BOOLEAN HasFileString(STRING sFileName,STRING sText)
[ ] //* Description: Retreives file contents and verifies that required string is present
[ ] //* Arguments: STRING sFileName - file name to search in
[ ] //* STRING sText - string to search for
[ ] //* Return Values: TRUE - required string is avaliable, FALSE - otherwise
[ ] //*************************************************************************************************
[+] BOOLEAN HasFileString(STRING sFileName,STRING sText)
[ ] LIST OF STRING lsValue = SYS_GetFileContents(sFileName)
[ ] STRING sValue
[ ]
[+] for each sValue in lsValue
[+] if( MatchStr("*{sText}*",sValue) )
[ ] return TRUE
[ ]
[ ] return FALSE
[ ]
[ ] //*************************************************************************************************
[+] //* Function: LIST OF STRING FindFiles( STRING sDir , STRING sFilePattern NULL optional, STRING sContainingText NULL optional )
[ ] //* Description: Searches for files in specified directory, by specified pattern and containing
[ ] //* specified text
[ ] //* Arguments: STRING sDir - directory to search in
[ ] //* STRING sFilePattern - (optional) file pattern to search for
[ ] //* STRING sContainingText - (optional) text to search in files
[ ] //* Return Values: List of filenames matching search criteria
[ ] //*************************************************************************************************
[+] LIST OF STRING FindFiles( STRING sDir , STRING sFilePattern NULL optional, STRING sContainingText NULL optional )
[ ] LIST OF FILEINFO lpInf
[ ] FILEINFO pInf
[ ] LIST OF STRING lsFiles = {}
[ ] LIST OF STRING lsValue
[ ] STRING sValue
[ ]
[+] if( !SYS_DirExists(sDir) )
[ ] return lsFiles
[ ]
[+] if( IsNull(sFilePattern) || sFilePattern == "" )
[ ] sFilePattern = "*"
[ ]
[ ] lpInf = SYS_GetDirContents(sDir)
[+] for each pInf in lpInf
[+] if( pInf.bIsDir )
[ ] lsValue = FindFiles(sDir+"\{pInf.sName}",sFilePattern,sContainingText)
[+] for each sValue in lsValue
[ ] ListAppend(lsFiles,sValue)
[+] else
[+] if(MatchStr(sFilePattern,pInf.sName))
[+] if( IsNull(sContainingText) || Trim(sContainingText) == "" )
[ ] ListAppend(lsFiles,sDir+"\{pInf.sName}")
[+] else if( HasFileString(sDir+"\{pInf.sName}",sContainingText) )
[ ] ListAppend(lsFiles,sDir+"\{pInf.sName}")
[ ]
[ ] return lsFiles
[ ]



Post Extras: Print Post   Remind Me!   Notify Moderator  
Kot Matroskin
Member


Reged: 04/04/06
Posts: 69
Loc: Toronto, Canada
Re: Donate a user defined function to this topic
      #26233 - 07/11/06 09:25 AM

Here is my little bit. Probably this code can be written by most of us pretty quickly, but anyway, not everyone comes in testing with much programming experience.

Compare two directories (except modification and creation dates). I use it to verify that copy or move command was successful.

code:
 [ ] //dir1 and dir2 - full paths to the directories to compare
[-] public compare_directories (String dir1, String dir2)
[ ] LIST OF FILEINFO files1 = SYS_GetDirContents (dir1)
[ ] LIST OF FILEINFO files2 = SYS_GetDirContents (dir2)
[ ] //compare direcories
[ ] //count number of items first
[ ] int numfiles1 = ListCount (files1)
[ ] int numfiles2 = ListCount (files2)
[-] if (numfiles1 != numfiles2)
[-] do
[ ] raise 1, "*** Error: comparing " + dir1 + " and " + dir2 + ". Number of files not equal. "+ Str(numfiles1) + " and " + Str(numfiles2)
[-] except
[ ] reraise
[ ]
[ ] int i
[-] for (i = 1; i <= numfiles1; ++i)
[ ] //compare attributes of all files, except last modified and created
[-] if (files1[i].sName != files2[i].sName || files1[i].bIsDir != files2[i].bIsDir || files1[i].iSize != files2[i].iSize || files1[i].iAttributes != files2[i].iAttributes)
[-] do
[ ] raise 1, "*** Error: comparing " + dir1 + " and " + dir2 + ". File attributes are not the same"
[-] except
[ ] reraise
[ ] //compare the files in currect directories
[ ] String file1 = dir1 + "\" + files1[i].sName
[ ] String file2 = dir2 + "\" + files2[i].sName
[ ] //and call comparision recursively on subdirectoris
[-] if (!files1[i].bIsDir)
[-] if (!SYS_CompareBinary (file1,file2 ))
[-] do
[ ] raise 1, "*** Error: comparing files" + file1 + " and " + file2 + " . Files not the same"
[-] except
[ ] reraise
[-] else
[ ] compare_directories (file1, file2)
[ ]
[ ]
[ ]
[ ] //dir - the full path of the directory of which to caculate the size
[-] public Real directory_size (String dir)
[ ] LIST OF FILEINFO files = SYS_GetDirContents (dir)
[ ] int numfiles = ListCount (files)
[ ] int i
[ ] Real dirsize=0
[-] for (i = 1; i <= numfiles; ++i)
[ ] String file = dir + "\" + files[i].sName
[-] if (!files[i].bIsDir)
[ ] dirsize = dirsize + files[i].iSize
[-] else
[ ] dirsize = dirsize + directory_size (file) //call directory size recursively
[ ] return dirsize
[ ]
[ ]
[ ]

Calculate size of the directory in bytes, kilobytes, megabytes or gigabytes
code:
[ ] //dir - the full path of the directory of which to caculate the size
[ ] //units - DS_GIGABYTES, etc
[ ] //returns the size in speficied or in bytes if nothing was specified
[ ] //Note: can use Str() or printf () to control number of decimal points when outputting
[-] public Real dir_size (String dir, Int units optional)
[ ] Real result = directory_size (dir)
[ ] //print (result)
[-] if units == DS_GIGABYTES
[ ] result = result/1024/1024/1024.0
[-] else if units == DS_MEGABYTES
[ ] result = result/1024.0/1024.0
[ ] //print (result)
[-] else if units == DS_KILOBYTES
[ ] result = result/1024.0
[ ] //print (result)
[ ] return result



Post Extras: Print Post   Remind Me!   Notify Moderator  
jamessoModerator
Moderator


Reged: 07/31/01
Posts: 1891
Loc: Earth
Re: Donate a user defined function to this topic
      #26234 - 07/25/06 08:47 AM

Function to get the Target of a shortcut item from the desktop (minimizing all windows if needed):

code:
[ ] const KEYEVENTF_KEYUP    = 0x0002
[ ] const VK_LWIN = 0x5B // Left Windows key (Microsoft Natural Keyboard)
[ ] const VK_RWIN = 0x5C // Right Windows key (Microsoft Natural Keyboard)
[ ] const VK_SNAPSHOT = 0x2C // PrintScreen key
[ ] const VK_MENU = 0x12 // ALT key
[ ] const VK_CTRL = 0x11 // CTRL key
[ ] const VK_D = 0x44 // D key
[ ] const VK_R = 0x52 // R key
[ ] const VK_V = 0x56 // (the V key for e.g. CTRL+V)
[ ] const VK_M = 0x4d // M Key
[ ] const VK_LSHIFT = 0x10 // Left Shift Key
[ ]
[ ]
[-] dll "user32.dll"
[ ] void keybd_event(UNSIGNED CHAR bVk, UNSIGNED CHAR bScan, UNSIGNED LONG dwFlags, UNSIGNED LONG dwExtra)
[ ]
[ ]
[ ] // Minimize all open applications by pressing LeftWindows+M keys
[+] void MinimizeAll()
[ ] keybd_event(VK_LWIN, 0, 0, 0)
[ ] keybd_event(VK_M, 0, 0, 0)
[ ] keybd_event(VK_M, 0, KEYEVENTF_KEYUP, 0)
[ ] keybd_event(VK_LWIN, 0, KEYEVENTF_KEYUP, 0)
[ ]
[ ] // Maximize all open applications by pressing Shift+LeftWindows+M keys
[+] void MaximizeAll()
[ ] keybd_event(VK_LWIN, 0, 0, 0)
[ ] keybd_event(VK_LSHIFT, 0, 0, 0)
[ ] keybd_event(VK_M, 0, 0, 0)
[ ] keybd_event(VK_M, 0, KEYEVENTF_KEYUP, 0)
[ ] keybd_event(VK_LWIN, 0, KEYEVENTF_KEYUP, 0)
[ ]
[+] STRING GetItemTarget (LISTITEM lItem)
[ ] // make sure desktop is visible
[ ] MinimizeAll()
[ ]
[ ] WINDOW w = DialogBox("Program Manager").ListView("#1|$1")
[ ] DialogBox("Program Manager").SetActive ()
[ ]
[ ] // right click on item and get properties window up
[ ] RECT r = w.GetItemRect (lItem)
[ ] w.Click (2, r.xPos+2, r.yPos+2)
[ ] w.TypeKeys ("<Up-2>")
[ ] w.TypeKeys ("<Enter>")
[ ] // get text from properties window
[ ] STRING sRtn = DialogBox("*Properties").DialogBox("Shortcut|$0").TextField("Application[2]|$13058").GetText ()
[ ] DialogBox("*Properties").Typekeys ("<Esc>")
[ ]
[ ] // restore desktop
[ ] MaximizeAll()
[ ] return sRtn
[-] testcase GetDesktopShortcut() appstate none
[ ] Print (GetItemTarget ("SilkTest"))
[ ]
[ ]



Post Extras: Print Post   Remind Me!   Notify Moderator  
Kot Matroskin
Member


Reged: 04/04/06
Posts: 69
Loc: Toronto, Canada
Re: Donate a user defined function to this topic
      #26235 - 08/04/06 08:43 AM

Quick correction to the above funtion:
there is a key_up even missing for Shift key in MaximizeAll function, it should look like:
code:
[+] void MaximizeAll()	
[ ] keybd_event(VK_LWIN, 0, 0, 0)
[ ] keybd_event(VK_LSHIFT, 0, 0, 0)
[ ] keybd_event(VK_M, 0, 0, 0)
[ ] keybd_event(VK_M, 0, KEYEVENTF_KEYUP, 0)
[ ] keybd_event(VK_LWIN, 0, KEYEVENTF_KEYUP, 0)
[ ] keybd_event(VK_LSHIFT, 0, KEYEVENTF_KEYUP, 0)

Unpressed shift affects other key combinations and clicks done after this function call



Post Extras: Print Post   Remind Me!   Notify Moderator  
Chris Mead
Super Member


Reged: 07/08/03
Posts: 1282
Loc: Boulder, CO
Re: Donate a user defined function to this topic
      #26236 - 08/08/06 04:29 PM

Here is a class of handy functions. There is a DLL needed. You can get it at:

http://www.mobie.us/code/qaUtils.zip

Unzip it and put this DLL in system32. It is not a virus. The C++ source code is posted elsewhere in the forum.

code:
[ ] use "mswtype.inc"
[ ] use "registry.inc"
[ ]
[+] dll "user32.dll"
[ ] LONG GetDesktopWindow()
[+] dll "psapi.dll"
[ ] long EnumProcesses (inout ARRAY[1024] OF LONG lpidProcess,inout LONG cb,inout LONG cbNeeded)
[ ] long EnumProcessModules (in LONG hProcess,inout ARRAY[1024] OF LONG lphModule, inout LONG cb,inout LONG cbNeeded)
[ ] long GetModuleBaseName (in LONG hProcess,in LONG hModule,inout STRING lpFileName,in LONG nSize) alias "GetModuleBaseNameA"
[ ] long GetModuleFileNameEx (in LONG hProcess,in LONG hModule,inout STRING lpFileName,in LONG nSize) alias "GetModuleFileNameExA"
[+] dll "kernel32.dll"
[ ] long OpenProcess (in LONG dwDesiredAccess,in LONG InheritHandle,in LONG dwProcessId)
[ ] BOOL CloseHandle (LONG hObject)
[ ] BOOL TerminateProcess(in LONG hProcess, UINT exitCode)
[ ] long GetLastError()
[ ] BOOL CreateProcess(STRING appName,STRING fullPath,in LONG procAttribs,in LONG secAttribs,in LONG inheritHandles,LONG creationFlags,LONG lpEnviron,STRING currentDir,inout Array[1024] of LONG starupInfo,inout Array[1024] of LONG processinfo)
[+] dll "shell32"
[ ] int ShellExecuteA (int hwnd, String lpOperation, String lpFile, string lpParameters,String lpDirectory, int nShowCmd)
[+] dll "ntdll.dll"
[ ] NtQueryInformationProcess(in LONG processHandle, in LONG processInfoClass, inout LONG processInfo, in long length, out long pulength)
[+] dll "qaUtils.dll"
[ ] LONG GetRunningProcesses(inout ARRAY OF CHAR longString, inout LONG bufferNeed, LONG onlyGetBufferSize)
[ ]
[+] winclass MachineUnderTest
[ ]
[+] LIST OF STRING ListProcesses()
[ ]
[ ] LIST OF STRING outList = {}
[+] do
[ ] ARRAY[1] OF CHAR tinyString
[ ]
[ ] LONG bufferNeeded = 0
[ ] LONG getBufferSizeOnly = 1
[ ] LONG firstReturn
[ ] firstReturn = GetRunningProcesses(tinyString, bufferNeeded, getBufferSizeOnly)
[ ]
[ ] LONG secondReturn
[ ] LONG getProcList = 0
[ ] int newSize = bufferNeeded+1
[ ] ARRAY[newSize] OF CHAR longString
[ ] secondReturn = GetRunningProcesses(longString, bufferNeeded, getProcList)
[ ]
[ ] STRING aChar
[ ] CHAR loopIndex
[ ] STRING outPart = ""
[+] for each loopIndex in longString
[+] if (loopIndex != 0)
[ ] aChar = Chr(loopIndex)
[+] if (aChar != ",")
[ ] outPart += aChar
[+] else
[ ] ListAppend(outList, outPart)
[ ] outPart = ""
[+] except
[ ] ExceptPrint()
[ ]
[ ] return outList
[ ]
[ ]
[+] INT KillByPid(LONG killPID)
[ ]
[ ] LONG ERROR_SUCCESS = 0
[ ] LONG rc = ERROR_SUCCESS
[ ]
[ ] LONG PROCESS_TERMINATE = 1
[ ] LONG InheritHandle = 0
[ ] LONG hProc = OpenProcess(PROCESS_TERMINATE,InheritHandle,killPID)
[ ]
[ ] //if (!hProc || hProc == INVALID_HANDLE_VALUE)
[+] if (!hProc)
[ ] rc = GetLastError()
[ ]
[+] if (rc == ERROR_SUCCESS)
[+] if (!TerminateProcess(hProc,0))
[ ] rc = GetLastError()
[ ]
[ ]
[ ] CloseHandle(hProc)
[ ]
[ ] return rc
[ ]
[ ]
[+] BOOLEAN StartApp (string p_sEXEName, string p_sEXEParams optional, string p_sWorkingDir optional, BOOLEAN skipVerify optional)
[ ]
[ ] const SHELL_CMD_OPEN = "open"
[ ] const SW_SHOW = 5
[ ]
[+] if IsNull(p_sEXEParams)
[ ] p_sEXEParams = " "
[+] else
[+] if p_sEXEParams == ""
[ ] p_sEXEParams = " "
[ ]
[+] if IsNull(p_sWorkingDir)
[ ] p_sWorkingDir = ""
[ ]
[ ]
[+] if IsNull(skipVerify)
[ ] skipVerify = FALSE
[ ]
[ ] // Sets iHandle = to the window handle for the desktop
[ ] INT iHandle = GetDesktopWindow()
[ ] //int iHandle = this.Desktop.GetHandle()
[ ]
[ ]
[ ] // The operation that is to be carried out
[ ] string lpOperation = SHELL_CMD_OPEN
[ ] // The file on which this operation will be carried out
[ ] string lpFile = p_sEXEName
[ ] // Any additional parameters to the commandline
[ ] string lpParameters = p_sEXEParams
[ ] // The working directory in which this will be run
[ ] string lpDirectory = p_sWorkingDir
[ ] // a flag that determines how the command will be shown
[ ] int iShowCmd = SW_SHOW
[ ]
[ ]
[ ] ShellExecuteA (iHandle,lpOperation,lpFile,lpParameters,lpDirectory,iShowCmd)
[ ]
[+] if (!skipVerify)
[ ] Sleep (3)
[ ]
[+] if (EXEisRunning(p_sEXEName))
[ ] return TRUE
[+] else
[ ] return FALSE
[+] else
[ ] return TRUE
[ ]
[ ] // Case insensitive
[+] BOOLEAN EXEisRunning(STRING exeName)
[ ]
[ ] LIST OF STRING currentProcessSnapshot
[ ]
[ ] currentProcessSnapshot = ListProcesses()
[ ]
[ ] // debug
[ ] //ListPrint (currentProcessSnapshot)
[ ]
[ ] STRING shortName = GetFileName(exeName)
[ ] STRING aProcess
[+] for each aProcess in currentProcessSnapshot
[ ]
[+] if MatchStr(Lower("*{shortName}*"), Lower(aProcess))
[ ] return TRUE
[ ]
[ ] return FALSE
[ ]
[+] private STRING GetFileName (STRING sFileName)
[ ] INT iCounter, iPos
[ ] BOOLEAN Found
[ ]
[ ] //Set start point to be end of string
[ ] iCounter = Len (sFileName)
[ ] Found = FALSE
[ ]
[ ] //Until end of string or slash is found
[+] while ((! Found) && (iCounter > 0))
[ ] //If a slash is found, then set flag to true and set location pointer
[+] if (sFileName[iCounter] == "\")
[ ] Found = TRUE
[ ] iPos = iCounter
[+] else
[ ] iCounter--
[ ]
[+] if (Found)
[ ] return (SubStr (sFileName, iPos + 1))
[+] else
[ ] return (sFileName)
[ ]
[ ]
[ ] // TODO: Add a dash '-'
[+] BOOLEAN PIDisRunning(INT PID)
[ ]
[ ]
[ ] LIST OF STRING currentProcessSnapshot
[ ]
[ ] currentProcessSnapshot = ListProcesses()
[ ]
[ ] STRING aProcess
[+] for each aProcess in currentProcessSnapshot
[ ]
[+] if MatchStr(Lower("*{PID}*"), Lower(aProcess))
[ ] return TRUE
[ ]
[ ] return FALSE
[ ]
[ ]
[ ] // Call in a loop to ensure all instances are killed
[+] BOOLEAN KillByExeName(STRING exeName, BOOLEAN skipVerify optional)
[ ]
[+] if (skipVerify == null)
[ ] skipVerify = FALSE
[ ]
[ ] LIST OF STRING nowRunning = ListProcesses()
[ ]
[ ] INT firstPIDrow = 1
[ ]
[ ] STRING aString
[+] for each aString in nowRunning
[+] if MatchStr("*{exeName}*", aString)
[ ] break
[+] else
[ ] firstPIDrow++
[ ]
[ ] int dashpos = StrPos("-", nowRunning[firstPIDrow])
[ ]
[ ] INT len = Len(nowRunning[firstPIDrow])
[ ] STRING pidStr = Right(nowRunning[firstPIDrow], len - dashpos-1)
[ ]
[ ] int killpid = Val(pidStr)
[ ] KillByPid(killpid)
[ ]
[+] if (!skipVerify)
[ ] Sleep (1)
[ ]
[+] if (PIDisRunning(killpid))
[ ] return FALSE
[+] else
[ ] return TRUE
[+] else
[ ] return TRUE
[ ]
[ ]
[+] BOOLEAN ExecuteVBScript (STRING scriptname, LIST OF STRING script, BOOLEAN asynchronous optional)
[ ]
[ ] //const STRING whichEngine = "CScript.exe" // visible window
[ ] const STRING whichEngine = "WScript.exe" // hidden
[ ]
[ ] string tempDirName = "temp"
[ ]
[+] if (IsNull(asynchronous))
[ ] asynchronous = FALSE
[ ]
[ ] HFILE FileHandle
[ ]
[+] do
[ ]
[+] do
[+] if (!SYS_DirExists("C:\{tempDirName}"))
[ ] SYS_MakeDir("C:\{tempDirName}")
[+] except
[ ] ExceptPrint()
[ ]
[+] if (SYS_FileExists ("C:\{tempDirName}\{scriptname}"))
[ ] SYS_RemoveFile("C:\{tempDirName}\{scriptname}")
[ ] Sleep (2)
[ ]
[ ] FileHandle = SYS_FileOpen ("C:\{tempDirName}\{scriptname}", FM_WRITE, FS_DENY_NONE)
[ ] STRING aLine
[+] for each aLine in script
[ ] SYS_FileWriteLine (FileHandle, aLine)
[ ] SYS_FileClose (FileHandle)
[ ] Sleep (1)
[ ]
[+] if (asynchronous)
[ ] StartApp(whichEngine, "C:\{tempDirName}\{scriptname}", "", TRUE)
[ ]
[+] else
[ ] LIST OF STRING outputStuff
[ ] //STRING longCommand = "CScript C:\WSATT\{scriptname}"
[ ] STRING longCommand = "{whichEngine} C:\{tempDirName}\{scriptname}"
[ ] SYS_EXECUTE(longCommand, outputStuff)
[+] except
[ ] ExceptPrint()
[ ] return FALSE
[ ]
[ ] return TRUE
[ ]
[+] BOOLEAN KillWithAltF4(STRING windowTag, BOOLEAN skipVerify optional)
[ ]
[+] if (skipVerify == NULL)
[ ] skipVerify = TRUE
[ ]
[ ] BOOLEAN isDialog = FALSE
[ ]
[ ] WINDOW useThisWindow
[ ]
[+] do
[ ] MainWin(windowTag).SetActive()
[ ] useThisWindow = MainWin(windowTag)
[+] except
[ ] isDialog = TRUE
[ ] DialogBox(windowTag).SetActive()
[ ] useThisWindow = DialogBox(windowTag)
[ ]
[ ] //debug
[ ] Print (useThisWindow)
[ ]
[ ] useThisWindow.TypeKeys("<ALT-F4>")
[ ]
[+] if (!skipVerify)
[ ] Sleep (2)
[+] if (useThisWindow.Exists(2))
[ ] return FALSE
[+] else
[ ] return TRUE
[+] else
[ ] return TRUE
[ ]
[+] BOOLEAN TestDriveMapped(string driveLetter)
[ ]
[ ] LIST OF STRING outStuff
[ ] SYS_EXECUTE("dir {driveLetter}:\*.*", outStuff)
[ ]
[+] if (MatchStr("*cannot find the*", outStuff[1]))
[ ] return FALSE
[+] else
[ ] return TRUE
[ ]
[ ]
[ ]
[+] BOOLEAN MapTestDrive(string networkPath, string username, string password, string driveLetter)
[ ]
[+] if (TestDriveMapped(driveLetter))
[ ] return TRUE
[ ]
[+] LIST OF STRING mapDriveScript = {...}
[ ] "Dim clDrives"
[ ] "Set WshNetwork = WScript.CreateObject(""WScript.Network"")"
[ ] "Set oFSO = WScript.CreateObject(""Scripting.FileSystemObject"")"
[ ] "NetDriveLetter=""{driveLetter}:"""
[ ] "WScript.Sleep 5000"
[ ] "Set clDrives = WshNetwork.EnumNetworkDrives"
[ ] "For i = 0 to clDrives.Count -1 Step 2"
[ ] " If clDrives.Item(i)=NetDriveLetter Then"
[ ] " WshNetwork.RemoveNetworkDrive NetDriveLetter,True,True"
[ ] " End If"
[ ] "Next"
[ ] "WshNetwork.MapNetworkDrive NetDriveLetter, ""{networkPath}"", True, ""{username}"", ""{password}"""
[ ] "Set OFSO = nothing"
[ ] "Set ODrives = nothing"
[ ] "Set WshNetwork = nothing"
[ ]
[ ] int tries = 1
[+] while (TRUE)
[+] do
[+] if (!this.ExecuteVBScript("mapdrives.vbs", mapDriveScript, TRUE))
[ ] return FALSE
[ ] Sleep (10)
[+] if (TestDriveMapped(driveLetter))
[ ] return TRUE
[+] except
[ ] tries++
[+] if (tries < 10)
[ ] Sleep (2)
[+] else
[ ] LogError("")
[ ] return FALSE
[ ]
[ ]
[ ]
[ ]
[+] INT getProcessHandleCountStr (STRING PID)
[ ]
[+] do
[ ] LONG nPID = Val(PID)
[ ] LONG dwDesiredAccess = 1040
[ ] LONG InheritHandle = 0
[ ] LONG thisProcessHandle = OpenProcess (dwDesiredAccess, InheritHandle, nPID)
[ ]
[ ] const LONG ProcessHandleCount = 20
[ ] LONG numHandles
[ ] const LONG oneWord = 4
[ ] LONG tooBig
[ ] NtQueryInformationProcess(thisProcessHandle, ProcessHandleCount, numHandles, oneWord, tooBig)
[ ]
[+] if (tooBig > 4)
[ ] LogError("")
[ ]
[+] except
[ ] ExceptPrint()
[ ]
[ ] CloseHandle(thisProcessHandle)
[ ] return numHandles
[ ]
[+] INT getProcessHandleCount (int PID)
[ ] return this.getProcessHandleCountStr(Str(PID))
[ ]
[ ] // Must call in a loop if multiple instances could be running
[+] INT GetPID(string exeName)
[ ]
[ ] LIST OF STRING currentProcessSnapshot
[ ]
[ ] currentProcessSnapshot = ListProcesses()
[ ]
[ ] STRING aProcess
[ ] STRING pidLine
[+] for each aProcess in currentProcessSnapshot
[+] if MatchStr(Lower("*{exeName}*"), Lower(aProcess))
[ ] pidLine = Lower(aProcess)
[ ] break
[ ]
[ ] int dashPos = StrPos("-", pidLine)
[ ] string pidOnly = SubStr(pidLine, dashPos + 2)
[ ]
[ ] return Val(pidOnly)
[ ]
[ ]
[ ] window MachineUnderTest MUT
[ ]



[ 08-08-2006, 04:37 PM: Message edited by: Chris Mead ]


Post Extras: Print Post   Remind Me!   Notify Moderator  
Chris Mead
Super Member


Reged: 07/08/03
Posts: 1282
Loc: Boulder, CO
Re: Donate a user defined function to this topic
      #26237 - 08/08/06 04:39 PM

Here is a unit test script that explains the previous post:

code:
[ ] use "mut.inc"
[ ]
[-] main()
[ ]
[ ] ListPrint(MUT.ListProcesses())
[ ]
[ ] // Find a safe PID to kill
[ ] //MUT.KillByPID(4024)
[ ]
[-] //if (MUT.EXEisRunning("iexplore.exe"))
[ ] //Print("explorer is running")
[-] //else
[ ] //Print("explorer is not running")
[ ]
[ ] // starts app & verifies that it starts
[ ] //MUT.StartApp("C:\WINNT\Notepad.exe")
[ ]
[ ] // does not verify that it starts
[ ] // specifies params
[ ] // specifies working directory
[ ] //MUT.StartApp("C:\WINNT\Notepad.exe", "ODBC.ini", "C:\WINNT", TRUE)
[ ]
[ ] //MUT.StartApp("c:\winnt\notepad.exe", null, null, TRUE) // does not wait
[ ] //Sleep (2)
[-] //if (MUT.EXEisRunning("notepad.exe"))
[ ] //Print ("pass")
[-] //else
[ ] //Print ("fail")
[ ]
[ ] //MUT.StartApp("c:\winnt\notepad.exe") // does verify
[ ] // so, don't need to sleep
[-] //if (MUT.EXEisRunning("notepad.exe"))
[ ] //Print ("pass")
[ ]
[ ]
[-] //if (MUT.PIDisRunning(761))
[ ] //Print("pass")
[ ]
[ ] //MUT.KillByExeName("notepad.exe")
[ ]
[ ] //MUT.KillWithAltF4("Untitled - Notepad")
[ ]
[ ]
[ ] // maps to w
[ ] // needs a real username and password
[ ] // MUT.MapTestDrive("\\machine\shareName", "username", "password", "w")
[ ]
[-] //if(MUT.TestDriveMapped("W"))
[ ] //Print ("pass")
[ ]
[ ]
[ ] //int agentPID = MUT.GetPID("agent.exe")
[ ] //Print ("agent PID = {agentPID}")
[ ] //Print (MUT.getProcessHandleCount(agentPID))
[ ]

Methods:

LIST OF STRING ListProcesses()
Uses a DLL called qautils.dll If you get DLL error 126 you have a path problem (MUT.inc and qautils.DLL need to be in the same directory)
Many of the other methods use this one. It is implemented in C++ and is very fast.

INT KillByPid(LONG killPID)
Calls TerminateProcess in kernel32.dll via DLL wrapping
KillByExeName uses this one

BOOLEAN StartApp (string p_sEXEName, string p_sEXEParams optional, string p_sWorkingDir optional, BOOLEAN skipVerify optional)
Partial replacement for SYS_Execute and Start()
You can provide params and specify the desired working directory
The last param controls whether or not ListProcesses() is used to verify the launch success for you
Calls ShellExecuteA in shell32.dll

BOOLEAN EXEisRunning(STRING exeName)
Uses ListProcesses()

BOOLEAN PIDisRunning(INT PID)
Uses ListProcesses()

BOOLEAN KillByExeName(STRING exeName, BOOLEAN skipVerify optional)
Uses KillByPid and, optionally, ListProcesses

BOOLEAN ExecuteVBScript (STRING scriptname, LIST OF STRING script, BOOLEAN asynchronous optional)
Used to execute a vb script that is embedded inside 4Test code (see mapDriveScript in MapTestDrive). Doing this makes it very easy to use paramaterized vbscripts without having to write command line parsing code in the vbscript
You have to use two 4Test quotes ("") to represent one quote in the vbscript file, otherwise you can pretty much paste a script in and make it a LIST OF STRING
It is using C:\temp right now for the vbscripts that it actually runs
It uses StartApp for asynchronous launches and SYS_Execute for synchronous execution of the target exe (the usual SYS_Execute)

BOOLEAN KillWithAltF4(STRING windowTag, BOOLEAN skipVerify optional)
Takes a tag and first tries using the MainWin class implementation of TypeKeys and falls back on the DialogBox implementation if the MainWin method fails

BOOLEAN TestDriveMapped(string driveLetter)
Checks to see if a drive letter is mapped
Intended for use with MapTestDrive

BOOLEAN MapTestDrive(string networkPath, string username, string password, string driveLetter)
Map a network drive for you
Uses ExecuteVBScript and has an embedded script in it

INT getProcessHandleCountStr (STRING PID)
Gets the handle count from a process
Basically an example of how to use OpenProcess in kernel32.dll to get any info you need for advanced debugging.

INT getProcessHandleCount (int PID)
Silk doesn't allow overloading. This is a way to work around it

INT GetPID(string exeName)
Get a process ID given an exe name


Much thanks to anyone who contributed to this via this forum!


Post Extras: Print Post   Remind Me!   Notify Moderator  
TonyM
Active Member


Reged: 11/22/99
Posts: 1036
Loc: Eagle, ID,USA
Re: Donate a user defined function to this topic [Re: Chris Mead]
      #331493 - 09/21/06 02:21 PM

Function to get the maximum input allowed for a text field:

Code:

[ ] use "msw.inc"
[-] integer intHex2Dec(string sHex)
[+] // About
[ ] //********
// @func integer | intHex2Dec |
// Returns an integer form the decimal representation of the hexidecimal value in sDec
// @parm string | sHex |
// sHex is a hexidecimal string value like "1a4c"
// @rdesc returns an integer where the hexidecimal value is converted to decimal
// @end
//********
[ ] integer iCounter, iResult = 0
[ ] sHex = Replicate("0", 8 - Len(sHex)) + Upper(sHex)
[ ]
[-] for (iCounter = 7; iCounter >= 0; iCounter--)
[-] switch sHex[8-iCounter]
[-] case "0","1","2","3","4","5","6","7","8","9"
[ ] iResult = iResult + Val(sHex[8-iCounter]) * 16**iCounter
[-] case "A","B","C","D","E","F"
[ ] iResult = iResult + (Asc(sHex[8-iCounter])-55) * 16**iCounter
[ ] return iResult
[ ]
[-] winclass TextField : TextField // Additional and overridden methods for built-in class
[-] long GetMaxInput()
[+] // About
[ ] //********
// @mfunc long | TextField | GetMaxInput | Returns the maximum number of characters allowed for input
//********
[ ] integer hTxt
[ ] long lMaxLngth
[ ] hTxt = this.GetHandle()
[ ]
[ ] lMaxLngth = SendMessage(hTxt,intHex2Dec("&HD5"),0,0)
[ ] return lMaxLngth
[ ]
[ ]
[-] testcase TestTextFieldLength() appstate none
[ ]
[ ] print(MyWindow.MyTextField.GetMaxInput())



--------------------
Have you ever noticed? Anybody going slower than you is an idiot, and anyone going faster than you is a maniac.


Post Extras: Print Post   Remind Me!   Notify Moderator  
Chris Mead
Super Member


Reged: 07/08/03
Posts: 1282
Loc: Boulder, CO
Re: Donate a user defined function to this topic [Re: TonyM]
      #332049 - 09/25/06 03:12 PM

Here is the International/2006 version of the DLL and the corresponding declaration. My MUT posting above also requires that you change ShellExecuteA to ShellExecuteW with International/2006.

http://www.mobie.us/code/qaUtilsW.zip

Code:

dll "qaUtilsW.dll"
LONG GetRunningProcessesW(inout ARRAY OF CHAR longString, inout LONG bufferNeed, LONG onlyGetBufferSize)



--------------------
Chris R Mead

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.


Post Extras: Print Post   Remind Me!   Notify Moderator  
chinna_you
Member


Reged: 07/12/04
Posts: 152
Loc: San Clemente, CA
Re: Donate a user defined function to this topic [Re: Chris Mead]
      #333272 - 10/02/06 12:26 PM

To Set Focus of any window/application using handle

PostMessage(hanApp,WM_ACTIVATE, VK_RETURN, 0)

Thanks
Subbu


Post Extras: Print Post   Remind Me!   Notify Moderator  
chinna_you
Member


Reged: 07/12/04
Posts: 152
Loc: San Clemente, CA
Re: Donate a user defined function to this topic [Re: chinna_you]
      #333274 - 10/02/06 12:32 PM

//GetColor() - Silk 8.0
Code:

[-] dll "gdi32.dll"
[ ] LONG GetPixel (LONG hDC,LONG x, LONG y)
[-] dll "user32.dll"
[ ] LONG GetWindowDC (int hWnd)


[-] INTEGER GetColor()
[ ] int hWnd
[ ] LONG temp
[ ] POINT pCursor
[ ] hWnd = [App/obj].GetHandle()
[ ] temp = GetWindowDC (hWnd)
[ ] pCursor = Cursor.GetPosition ()
[ ] return(GetPixel(temp,pCursor.x,pCursor.y))



Edited by jamesso (10/19/07 01:22 PM)


Post Extras: Print Post   Remind Me!   Notify Moderator  
rick_weth
Member


Reged: 09/02/99
Posts: 335
Loc: San Jose,CA,USA
Re: Donate a user defined function to this topic [Re: chinna_you]
      #338647 - 11/01/06 03:13 PM

Good topic:

Code:

[+] boolean ListContains (list of string tlist, string patt)
[ ] boolean ret_val = false
[ ] string thing
[+] for each thing in tlist
[+] if MatchStr(patt,thing)
[ ] ret_val = true
[ ] break
[ ]
[ ] return ret_val
[ ]
[ ]
[+] list of string SplitString(string target,string splitstr)
[ ] // makes up for Segues increadible lack of fore sight
[ ] string frag_ment = null
[ ] string sub_frag = null
[ ] boolean target_empty = FALSE
[ ] List Of String ret_list = {}
[ ] integer frag_pos = 0
[ ] integer ss_len = Len(splitstr)
[ ] integer nop = 0
[ ]
[ ] frag_ment = target
[+] while (! target_empty)
[ ] frag_pos = StrPos(splitstr,frag_ment)
[+] if frag_pos == 0
[ ] target_empty = TRUE
[+] if Len(frag_ment) > 0
[ ] ListAppend(ret_list,frag_ment)
[ ] continue
[+] else
[ ] sub_frag = SubStr(frag_ment,1,frag_pos - 1)
[ ] ListAppend(ret_list,sub_frag)
[ ] frag_ment = SubStr(frag_ment,frag_pos + ss_len)
[ ]
[+] if Len(frag_ment) > 0
[ ] nop++
[+] else
[ ] target_empty = TRUE
[ ]
[ ] return ret_list
[ ]
[+] list of int Range(int beg,int end optional)
[ ] list of int ret_lst = {}
[ ]
[+] if end == null
[ ] end = beg
[ ] beg = 1
[+] if beg == null
[ ] beg = 1
[ ]
[ ] int i
[+] for(i=beg;i<=end;i++)
[ ] ListAppend (ret_lst, i)
[ ]
[ ]
[ ] return ret_lst



--------------------
Smoke me a kipper, I'll be back for breakfast!
Sincerely
Richard Weth
Sr. QA Engineer


Post Extras: Print Post   Remind Me!   Notify Moderator  
spaceraider
Member


Reged: 09/27/02
Posts: 113
Loc: ONDlodnol
Re: Donate a user defined function to this topic [Re: chinna_you]
      #370889 - 04/04/07 10:29 AM

Here is a function that converts the Data&Time for a OLE object.

Code:
  
[-] private Match_DateTime()//compares date/time values from OLE fields
[ ] string sYear
[ ] string sMonth
[ ] string sDay
[ ] string sHour
[ ] string sMinute
[ ] string sAMPM
[ ] string sNum
[ ] datetime dtEnd
[ ] datetime dtStart
[ ] integer iMonth
[ ] integer iYear
[ ] integer iDay
[ ] integer iHour
[ ] integer iMinute
//Get the Time and Date from the Commint D/T field
[ ] iMonth = CMiscReport.SSScrollBase.FrameB1.OLEDTPicker("Commt D?T").iMonth//get the value of field in integer
[ ] sNum = Str (iMonth)//convert to string
[ ] MatchStr(sNum, sMonth)//match the 2 strings
[-] if sNum == sMonth//test comparing the 2 values
[ ] iYear = CMiscReport.SSScrollBase.FrameB1.OLEDTPicker("Commt D?T").iYear//get the value of field in integer
[ ] sNum = Str (iYear)//convert to string
[ ] MatchStr(sNum, sYear)//match the 2 strings
[-] if sNum == sYear//test comparing the 2 values
[ ] iDay = CMiscReport.SSScrollBase.FrameB1.OLEDTPicker("Commt D?T").iDay//get the value of field in integer
[ ] sNum = Str (iDay)//convert to string
[ ] MatchStr(sNum, sDay)//match the 2 strings
[-] if sNum == sDay//test comparing the 2 values
[ ] iHour = CMiscReport.SSScrollBase.FrameB1.OLEDTPicker("Commt D?T").iHour//get the value of field in integer
[ ] sNum = Str (iHour)//convert to string
[ ] MatchStr(sNum, sHour)//match the 2 strings
[-] if sNum == sHour//test comparing the 2 values
[ ] iMinute = CMiscReport.SSScrollBase.FrameB1.OLEDTPicker("Commt D?T").iMinute//get the value of field in integer
[ ] sNum = Str (iMinute)//convert to string
[ ] MatchStr(sNum, sMinute)//match the 2 strings
[-] if sNum == sMinute//test comparing the 2 values
[ ] sNum = Str(iMinute)//convert to string
[ ] MatchStr(sNum, sMinute)//match the 2 strings
//Formats the system time and date
[ ] dtStart = GetDateTime ()
[ ] sYear = FormatDateTime (dtStart, "yyyy")//year
[ ] sMonth = FormatDateTime (dtStart, "m")//month
[ ] sDay = FormatDateTime(dtStart, "dd") //day
[ ] sHour = FormatDateTime (dtStart, "hh")//hour
[ ] sMinute = FormatDateTime (dtStart, "nn")//minute
[ ] sAMPM = FormatDateTime (dtStart, "AM/PM")//time mode
[ ] dtEnd = "{sMonth}/{sDay}/{sYear} {sHour}:{sMinute}: {sAMPM}"//bring formatting togther
//compare and matches the time and date from commint D/T field
[ ] MatchStr(sNum, sYear)
[-] if sNum == sYear
[ ] print ("The Year field match")
[-] else
[ ] // val
[ ] LogError("The Year field doesn't match")
[ ] MatchStr(sNum, sMonth )
[-] if sNum == sMonth
[ ] print("The Month field match")
[-] else
[ ] LogError("The Month field doesn't match")
[ ] MatchStr(sNum, sDay )
[-] if sNum == sDay
[ ] print("The Day field match")
[-] else
[ ] LogError("The Day field doesn't match")
[ ] MatchStr(sNum, sHour )
[-] if sNum == sHour
[ ] print("The Hour field match")
[-] else
[ ] LogError("The Hour field doesn't match")
[ ] MatchStr(sNum, sMinute )
[-] if sNum == sMinute
[ ] print("The Minute field match")
[-] else
[ ] LogError("The Minute field doesn't match")
[ ]
[ ]
[ ] //***********************************************************************/




--------------------
Goodness is a part of life just like the Devil

Edited by spaceraider (04/04/07 10:55 AM)


Post Extras: Print Post   Remind Me!   Notify Moderator  
bhanukiran
Newbie


Reged: 03/05/07
Posts: 7
Re: Donate a user defined function to this topic [Re: TonyM]
      #374873 - 04/22/07 03:47 AM

Hi Tony Thanks for provding very useful method, i used above user defined method(to get max input allowed in a textbox) but i am getting 'DLL can't be loaded -Error 193
error in test report.
I am using Browser:IE 6.0 DOM, SP2,OS: Windows XP, Tool:SilkTest 6.5.
I chaged HtmalTextField inplace of TestField class as i am using it in webapplication testing.

Can you please guide me why i am getting above problem, do I need to change anything in my script or any changes in tool or browser settings.

-Thanks
Bhanu


Post Extras: Print Post   Remind Me!   Notify Moderator  
bhanukiran
Newbie


Reged: 03/05/07
Posts: 7
Re: Donate a user defined function to this topic [Re: TonyM]
      #375003 - 04/23/07 03:59 AM

Hi Tony thanks for providing very useful method, i used above user defind method(to get max input allowed in a textbox) but i am gettubg 'DLL can't be loaded-Error 193'
I am using Browser: IE 6 DOM,SP2, Openration system: WindowsXp SilkTest 6.5

I changed HTMLTextFiled inplace of TextField class as i am using a webapllication for testing.

Can you please guide me why i am getting above problem, do i need to change anything in my script or any changes in tool or broser settings .

Thanks
Bhanu


Post Extras: Print Post   Remind Me!   Notify Moderator  
April_20
Junior Member


Reged: 02/24/06
Posts: 195
Loc: Princeton, NJ
Re: Donate a user defined function to this topic [Re: bhanukiran]
      #377632 - 05/02/07 01:23 PM

GetMaxInput() method would only work on TextField class. To work with HtmlTextField use GetMaxLength() method from the class below:

Code:
 
use "msw32.inc"

[-] public winclass TextField: TextField
[ ] //*********************************************************************
[ ] // This class extends standard TextField class.
[ ] //*********************************************************************
[ ]
[-] hidecalls INT GetMaxLength()// Returns max length of HtmlTextField:
[ ] //the max number of characters stored in it.
[ ] //***** Warning: this method should only be used on HtmlTextField
[ ] //class only. Extending HtmlTextField class causes compilation error.
[ ] return Val(this.ExecMethod('getAttribute("maxlength")'))
[-] hidecalls LONG GetMaxInput()// Returns max length of standard TextField:
[ ] integer hTxt
[ ] long lMaxLngth
[ ]
[ ] hTxt = this.GetHandle()
[ ] lMaxLngth = SendMessage(hTxt,213,0,0)
[ ] return lMaxLngth




Post Extras: Print Post   Remind Me!   Notify Moderator  
manoj3
Junior Member


Reged: 06/24/02
Posts: 8
Loc: Bay Area, CA
Re: Donate a user defined function to this topic [Re: chinna_you]
      #417984 - 09/20/07 04:04 PM

Here is a simple function to Verify the Credit Card type with the number intered in the CC field.
Code:

[ ] // **** Function to Get the CC Type ***** //
[ ] // Parameters
[ ] // sCCNumber ------------> Credit Card Number
[ ] // Returns the CCType based on the First Number
[ ] // **** ***** //
[+] STRING GetCCType (STRING sCCNumber)
[ ] STRING sFirstNum = SubStr(sCCNumber,1,1)
[ ] print(SubStr(sCCNumber,1,1))
[+] switch(Val(sFirstNum))
[+] case(3)
[ ] print("American Express")
[ ] return "American Express"
[+] case(4)
[ ] print("VISA")
[ ] return "VISA"
[+] case(5)
[ ] print("Mastercard")
[ ] return "Mastercard"
[+] case(6)
[ ] print("Discover")
[ ] return "Discover"
[+] default
[ ] LogError ("Type for the Credit Card with CC Number {sCCNumber} is not Automated")
[ ] return NULL
[ ]
[ ]
[ ]



Edited by jamesso (10/19/07 01:21 PM)


Post Extras: Print Post   Remind Me!   Notify Moderator  
dimaj
Active Member


Reged: 05/05/05
Posts: 828
Loc: Fremont, CA
Re: Donate a user defined function to this topic [Re: manoj3]
      #420851 - 10/02/07 09:37 AM Attachment (431 downloads)

Hello All!

Here's an API that I have compiled to use SilkTest with ABBYY ScreenShot Reader.

NOTE: API is in the attached to the message (ABBYY_ScreenShot_Reader.zip)

Hope this is useful.

dimaj

Edited by dimaj (10/02/07 09:38 AM)


Post Extras: Print Post   Remind Me!   Notify Moderator  
dimaj
Active Member


Reged: 05/05/05
Posts: 828
Loc: Fremont, CA
Re: Donate a user defined function to this topic [Re: dimaj]
      #426806 - 10/23/07 05:56 PM

Here's a function that I wrote to disable any Device class (i.e. "mouse"). It talks to DevCon.exe. DevCon.exe is an application developed by Microsoft as a command line alternative to "Device Manager" for Windows.

This function was written for 1 reason: disable mouse devices during testcase execution. Sometimes you can accidentally touch your mouse and your entire testcase fails.

NOTE: Please use this at your own risk. There might be a possibility that enable/disable will fail and you will have to manually enable those devices using actual device manager or reboot your machine.

Here's my code:
Code:

[+] // Function Description
[ ] // This function is going to disable / enable a hardware device installed on your computer
[+] // Input parameters
[ ] // STRING sDeviceClass = Class of a device as showd in the DeviceManager (i.e. Mouse)
[ ] // BOOLEAN bEnable = if TRUE device will be enabled, otherwise it will be disabled
[ ] // STRING sDevConPath = Path to DevCon application
[+] // Example of usage
[ ] // to enable, do this HardwareManipulation ("Mouse", TRUE, "C:\Tools\DevCon\i386\DevCon.exe")
[ ] // to disable, do this HardwareManipulation ("Mouse", FALSE, "C:\Tools\DevCon\i386\DevCon.exe")
[-] Void EnableDisableHardware (STRING sDeviceClass, BOOLEAN bEnable, STRING sDevConPath)
[ ] // local variables
[ ] LIST OF STRING lsRetVal
[ ] STRING sCommand
[ ]
[ ] // check if path exists
[+] if (!SYS_FileExists (sDevConPath))
[ ] raise 1, "File '{sDevConPath}' does not exist!"
[ ]
[ ] // generate a commnad line to execute to get list of all devices under a device class
[+] if (bEnable)
[ ] sCommand = '"{sDevConPath}" enable ={sDeviceClass}'
[+] else
[ ] sCommand = '"{sDevConPath}" disable ={sDeviceClass}'
[ ]
[ ] // check if program exuted correctly
[+] if (iProgramExitCode != 0)
[+] switch (iProgramExitCode)
[+] case 1
[ ] raise 1, "Computer restart is required to complete this action"
[+] case 2
[ ] raise 1, "Couldn't complete requested action"
[+] case 3
[ ] raise 1, "There was an error while executing application"


[-] testcase TestEnableDisableHardware () appstate none
[ ] HardwareManipulation ("Mouse", FALSE, "C:\tools\DevCon\i386\DevCon.exe")
[ ] sleep (10)
[ ] HardwareManipulation ("Mouse", TRUE, "C:\tools\DevCon\i386\DevCon.exe")



dimaj


Post Extras: Print Post   Remind Me!   Notify Moderator  
dimaj
Active Member


Reged: 05/05/05
Posts: 828
Loc: Fremont, CA
Re: Donate a user defined function to this topic [Re: dimaj]
      #427063 - 10/24/07 07:59 AM

Sorry guys,

I forgot to include the SYS_Execute (sCommand, lsRetVal) right before the if (iProgrameExitCode)

dimaj


Post Extras: Print Post   Remind Me!   Notify Moderator  
solutionprovider
Junior Member


Reged: 03/28/01
Posts: 34
Loc: USA
Re: Donate a user defined function to this topic [Re: chinna_you]
      #436876 - 11/28/07 07:16 AM

Restart a Computer using VBS

http://searchcode.tm-sol.com/codeid.php?Code_ID_Code=114&dowhattodo=

reading a config file to be used in QTP which can be loaded as Env variables

http://searchcode.tm-sol.com/codeid.php?Code_ID_Code=127&dowhattodo=

--------------------
Cheers,
Solution Provider

http://searchcode.tm-sol.com
Post and find code for quite a lot of problems.


Post Extras: Print Post   Remind Me!   Notify Moderator  
hemangihere
Junior Member


Reged: 06/09/05
Posts: 37
Loc: Bangalore
Re: Donate a user defined function to this topic [Re: chinna_you]
      #444428 - 12/28/07 02:41 AM

Hi Friends I would like to share the code to get the recursive children for a window.
(wWin.GetChildren()-Gives the Children of only 1 Hierarchy level)
Code:

[+] type CHILD is record
[+] //@HELP
[ ] //==================================
[ ] // Data Type name : CHILD
[ ] // Purpose : To get the all components of a window
[ ] // Input : Null
[ ] // Output : Null
[ ] // Created on : 12th Dec 07
[ ] // Updated on :
[ ] //Created By : Hemangi
[ ] //==================================
[ ] LIST OF WINDOW lwWin
[ ] DATACLASS dcClass
[ ] STRING sCaption
[ ] LIST OF STRING lsChildCaption
[ ] INT Count
[ ]
[-] CHILD GetChild(WINDOW wName)
[+] //@HELP
[ ] //==================================
[ ] // Function name : GetChild
[ ] // Purpose : To get the all Child components of the input window
[ ] // Input : window name
[ ] // Output : 1) List of child objects for this window 2) Count of the objects
[ ] // Created on : 12th Dec 07
[ ] // Updated on :
[ ] //Created By : Hemangi
[ ] //==================================
[ ] CHILD chC
[ ] LIST OF WINDOW lwWin
[ ] chC.lwWin = wName.GetChildren()
[ ] chC.Count =ListCount(chC.lwWin)
[ ] return chC
[ ]
[+] LIST OF WINDOW GetRecursiveChildren(WINDOW wx)
[+] //@HELP
[ ] //==================================
[ ] // Function name : GetRecursiveChildren
[ ] // Purpose : To get the all Child components of the input window recursively(all the objects within objects)
[ ] // Input : window name
[ ] // Output : all child components of all the window objects
[ ] // Created on : 12th Dec 07
[ ] // Updated on :
[ ] //Created By : Hemangi
[ ] //==================================
[ ] ARRAY [1000] OF CHILD aC1
[ ] List of window lwWin1,lwWin2
[ ] iCnt=1
[ ] aC1[iCnt] = GetChild( wx)
[ ] lwWin1 = aC1[iCnt].lwWin
[ ] window wWin
[-] if ListCount(lwWin1) !=0
[-] for each wWin in lwWin1
[ ] //Print(lwWin1)
[ ] ListAppend (lwWin2,wWin)
[ ] //Print(lwWin2)
[-] if ListCount(lwWin2) != 0
[ ] ListMerge(lwWin,lwWin2)
[-] if aC1[iCnt].Count !=0
[ ] iCnt++
[-] for each wWin in aC1[iCnt-1].lwWin
[ ] GetRecursiveChildren (wWin)
[ ] return lwWin
[ ]
[-] testcase GetRecChildrenTC() appstate none
[ ] MainWin_GMO.SetActive()
[ ] Browser.Maximize()
[ ] Print( GetRecursiveChildren(MainWin_GMO))
[ ]



--------------------
Thanks & Regards,
-Hemangi

Edited by jamesso (11/19/08 07:29 AM)


Post Extras: Print Post   Remind Me!   Notify Moderator  
PixelJunction
Member


Reged: 12/14/07
Posts: 110
Loc: Boston, MA - USA
Re: Donate a user defined function to this topic [Re: Bapanna Setti]
      #444969 - 01/02/08 04:58 AM

Here are a couple simple functions I use a lot in my automation to make the experience as random as possible:
Code:

// ANYTYPE Functions
[-] ANYTYPE ReturnRandomSingle(LIST OF ANYTYPE laPassedIn)
[ ] return laPassedIn[RandInt(1,ListCount(laPassedIn))]
[ ]
[ ] // LIST OF ANYTYPE Functions
[-] LIST OF ANYTYPE ReturnRandomList(INTEGER iCount, LIST OF ANYTYPE laPassedIn)
[ ] LIST OF ANYTYPE laRandomItems
[ ] INTEGER iLoop
[ ]
[-] for iLoop = 1 to iCount
[ ] ListAppend(laRandomItems, ReturnRandomSingle(laPassedIn))
[ ]
[ ] return laRandomItems

And since our code uses records (pulled from XLS files) for a large portion of the verification, a function to compare two records:

[-] VOID Compare2Records(ANYTYPE aRecord1, ANYTYPE aRecord2, LIST OF STRING lsFieldsIgnore)
[ ] STRING sField
[ ]
[ ] // Make sure both records are the same type.
[-] if(TypeOf(aRecord1) != TypeOf(aRecord2))
[ ] LogError("*** Type of aRecord1: {TypeOf(aRecord1)} is not equal to the type of aRecord2: {TypeOf(aRecord2)} ***")
[ ]
[ ] // Pull all the record values to be compared.
[ ] LIST OF STRING lsRecordFields = FieldsOfRecord(TypeOf(aRecord1))
[ ]
[ ] // Loop through to compare each value in the records.
[-] for each sField in lsRecordFields
[ ]
[ ] // If the current field is contained in lsFieldsIgnore, skip to next one.
[-] if(ListFind(lsFieldsIgnore,sField))
[ ] continue
[ ]
[ ] Print("Comparing: {aRecord1.@(sField)} with {aRecord2.@(sField)}")
[ ]
[ ] // Compare the current field from the record.
[-] if(aRecord1.@(sField) != [Email]aRecord2.@(sField))[/Email]
[ ] LogError("*** Error: Records values not equal --> {aRecord1.@(sField)}, {aRecord2.@(sField)} ***")



--------------------
Co-Founder
Pixel Junction - Websites Done Right!
www.mypixeljunction.com

Edited by jamesso (11/19/08 07:36 AM)


Post Extras: Print Post   Remind Me!   Notify Moderator  
smahmed
Junior Member


Reged: 11/21/04
Posts: 18
Loc: India
Re: Donate a user defined function to this topic [Re: PixelJunction]
      #456757 - 02/10/08 11:59 PM

Here is the function which reads the Directory frecursively and write the result to Out Put file.
Code:

[+] void Dir_Contents (String dirname,String sOutFileName)
[ ]
[ ] List of FILEINFO LfiFolderContents
[ ]
[ ]
[ ] INTEGER iCount
[ ] // print (dirname)
[ ] SYS_SetDir (dirname)
[ ] LfiFolderContents = SYS_GetDirContents (dirname)
[ ]
[-] for iCount = 1 to ListCount (LfiFolderContents)
[-] if !(LfiFolderContents[iCount].bIsDir )
[ ] Listappend (GlsFoldervalues,"{dirname}"+"\"+"{LfiFolderContents[iCount].sName}" )
[-] else
[ ] // print ("{dirname}"+"\"+"{LlsFolderContents[iCount].sName}")
[ ] Listappend (GlsFoldervalues,"{dirname}"+"\"+"{LfiFolderContents[iCount].sName}" )
[ ] Dir_Contents ("{dirname}"+"\"+"{LfiFolderContents[iCount].sName}")
[ ]
[ ] ListWrite (GlsFoldervalues,"{sOutFileName}")



thanks
Syed

Edited by jamesso (11/19/08 07:35 AM)


Post Extras: Print Post   Remind Me!   Notify Moderator  
tmpalaniselvam
Veteran


Reged: 09/18/01
Posts: 2511
Loc: Bangalore,India
Re: Donate a user defined function to this topic [Re: smahmed]
      #457559 - 02/13/08 01:30 AM

This function is useful, if user tries to get all children of particular CLASS object. I have used recursive technique here.
I have put few code snippets here Silktest tips

Code:


[-] public LIST OF WINDOW GetChildObjects(Window wContainer, DATACLASS dcObject)
[ ] // To get All child objects.
[ ] // Used recursive method.
[ ] LIST OF WINDOW lwndObjects, lwTemp1, lwTemp2
[ ] LIST OF WINDOW lwndChildren = {...}
[ ] WINDOW wParent, wChild, wTemp
[ ]
[-] do
[-] if (wContainer.Exists (10))
[ ] lwndChildren = wContainer.GetChildren (TRUE, FALSE)
[ ]
[-] for each wChild in lwndChildren
[-] if wChild.IsOfClass(dcObject)
[ ] ListAppend (lwndObjects,wChild)
[-] else
[ ] lwTemp1 = wChild.GetChildren(TRUE, FALSE)
[-] if (ListCount(lwTemp1) > 1)
[ ] lwTemp2 = GetChildObjects(wChild,dcObject) //To get particular objects
[-] if (ListCount(lwTemp2) > 0)
[ ] ListMerge (lwndObjects, lwTemp2)
[-] else
[ ] Print ("Container {[STRING]wContainer} window is not available.")
[+] except
[ ] ExceptLog ()
[ ]
[ ] return lwndChildren




--------------------
Thanks & Regards,
Palani.
http://tips-testing.blogspot.com/index.html
Quote: Dont hesitate to initiate!

Edited by tmpalaniselvam (02/13/08 01:33 AM)


Post Extras: Print Post   Remind Me!   Notify Moderator  
dimaj
Active Member


Reged: 05/05/05
Posts: 828
Loc: Fremont, CA
Re: Donate a user defined function to this topic [Re: tmpalaniselvam]
      #458943 - 02/18/08 09:41 AM

Here's a function to check current CPU usage of a computer.

Code:

[-] dll "Kernel32.dll"
[ ] long GetSystemTimes(out long lpIdleTime, out long lpKernelTime, out long lpUserTime)

[+] // Function Description
[ ] // This function is going to loop until CPU usage drops to a desired %
[ ]
[+] // INPUT PARAMETERS
[ ] // LONG - value of CPU usage at which loop gets terminated
[ ] // BOOLEAN - Output readings into result file
[+] // RETURN
[ ] // VOID
[+] // EXAMPLE
[ ] // WaitForCPU (20, TRUE)
[ ] // WaitForCPU (20, FALSE)
[+] void WaitForCPU (long lCPUThreshold, boolean bPrintReading optional)
[ ] // initialize bPrintReading if it hasn't been passed in
[+] if (bPrintReading == null)
[ ] bPrintReading = false
[ ]
[ ] // open a list for CPU reading results
[+] if (bPrintReading)
[ ] ResOpenList ("Processor Times")
[ ]
[ ] // local vars
[ ] long lCurIdleReading, lCurKernelReading, lCurUserReading
[ ] long lPrevIdleReading, lPrevKernelReading, lPrevUserReading
[ ] long lIdle, lKernel, lUser, lSys, lCPULoad
[ ]
[ ] // get system times
[ ] GetSystemTimes (lCurIdleReading, lCurKernelReading, lCurUserReading)
[ ] lPrevIdleReading = lCurIdleReading
[ ] lPrevKernelReading = lCurKernelReading
[ ] lPrevUserReading = lCurUserReading
[ ]
[ ] // get system time
[ ] lSys = lCurUserReading + lCurKernelReading
[ ]
[ ] // get CPU load time
[+] if (lSys == 0)
[ ] lCPULoad = 0
[+] else
[ ] lCPULoad = ((lSys - lCurIdleReading) * 100) / lSys
[ ]
[+] if (bPrintReading)
[ ] print ("{lCPULoad}")
[ ]
[ ] // loop until desired value is not reached
[+] while ((lCPULoad > lCPUThreshold) || (lCPULoad == 0))
[ ] sleep (1)
[ ] // get system times
[ ] GetSystemTimes (lCurIdleReading, lCurKernelReading, lCurUserReading)
[ ]
[ ] // assign current times to the last times
[ ] lIdle = lCurIdleReading - lPrevIdleReading
[ ] lKernel = lCurKernelReading - lPrevKernelReading
[ ] lUser = lCurUserReading - lPrevUserReading
[ ]
[ ] lPrevIdleReading = lCurIdleReading
[ ] lPrevKernelReading = lCurKernelReading
[ ] lPrevUserReading = lCurUserReading
[ ]
[ ] lSys = lUser + lKernel
[ ]
[+] if (lSys == 0)
[ ] lCPULoad = 0
[-] else
[ ] lCPULoad = ((lSys - lIdle) * 100) / lSys
[ ]
[+] if (bPrintReading)
[ ] print ("{lCPULoad}")
[ ]
[ ]
[ ] // close list of CPU Readings
[+] if (bPrintReading)
[ ] ResCloseList ()



dimaj


Post Extras: Print Post   Remind Me!   Notify Moderator  
Bond1984
Newbie


Reged: 12/10/06
Posts: 24
Re: Donate a user defined function to this topic [Re: dimaj]
      #463093 - 03/03/08 11:51 AM

Code:

// returns the extension from a filepath string
[+] STRING GetFileExtension (STRING s)
[ ] INTEGER iLen = Len(s)
[ ] INTEGER iDot = 0
[ ] INTEGER j
[ ] STRING sExt = NULL
[-] for j = 0 to iLen-1
[ ] INTEGER iPos = iLen-j
[ ] STRING sChar = SubStr (s, iPos, 1)
[-] if sChar == "."
[ ] iDot = iPos
[ ] break
[-] if iDot > 0
[ ] sExt = SubStr (s, iDot+1, iLen-iDot)
[ ] return sExt



--------------------
~AK

Edited by jamesso (11/19/08 07:30 AM)


Post Extras: Print Post   Remind Me!   Notify Moderator  
PiseAmol
Member


Reged: 07/09/07
Posts: 33
Re: Donate a user defined function to this topic [Re: Bond1984]
      #468387 - 03/19/08 11:56 PM

During the execution of test script, if your application is scrolling either upward or downward abnormally then try the following line of code...

Agent.SetOption (OPT_SCROLL_INTO_VIEW, False)

Thanks,
Amol Pise.


Post Extras: Print Post   Remind Me!   Notify Moderator  
April_20
Junior Member


Reged: 02/24/06
Posts: 195
Loc: Princeton, NJ
Re: Donate a user defined function to this topic [Re: Chris Mead]
      #473922 - 04/09/08 10:51 AM

Quote:

Here is the International/2006 version of the DLL and the corresponding declaration. My MUT posting above also requires that you change ShellExecuteA to ShellExecuteW with International/2006.

http://www.mobie.us/code/qaUtilsW.zip

Code:

dll "qaUtilsW.dll"
LONG GetRunningProcessesW(inout ARRAY OF CHAR longString, inout LONG bufferNeed, LONG onlyGetBufferSize)





Small correction:
function declaration should read:
Code:
  
Code:

dll "qaUtilsW.dll"
LONG GetRunningProcesses(inout ARRAY OF CHAR longString, inout LONG bufferNeed, LONG onlyGetBufferSize)


without W at the end.


Post Extras: Print Post   Remind Me!   Notify Moderator  
KrisrisK
Member


Reged: 04/21/08
Posts: 340
Loc: Hyderabad
Re: Donate a user defined function to this topic [Re: chinna_you]
      #490235 - 06/10/08 03:28 AM

Code:

[ ] //******************************************************
[ ] // Function NumberInWords() - converts a number in to words and returns that string
[ ] //******************************************************
[ ]
[+] STRING NumberInWords(INTEGER iNumber)
[ ]
[ ] STRING sNumber = Str(iNumber)
[ ] STRING sNumberString = ""
[ ] INTEGER iLength = Len(sNumber)
[ ] STRING sOnes = ""
[ ] STRING sTens = ""
[ ] STRING sHundreds = ""
[ ] STRING sThousands = ""
[ ]
[-] switch(iLength)
[ ] // for single digit numbers
[+] case 1
[ ] sOnes = sNumber
[+] switch(sOnes)
[+] case "1"
[ ] sOnes = "One"
[+] case "2"
[ ] sOnes = "Two"
[+] case "3"
[ ] sOnes = "Three"
[+] case "4"
[ ] sOnes = "Four"
[+] case "5"
[ ] sOnes = "Five"
[+] case "6"
[ ] sOnes = "Six"
[+] case "7"
[ ] sOnes = "Seven"
[+] case "8"
[ ] sOnes = "Eight"
[+] case "9"
[ ] sOnes = "Nine"
[+] case "0"
[ ] sOnes = ""
[ ] sNumberString = sOnes
[ ]
[ ] // for 2 digit numbers
[+] case 2
[ ] sOnes = Right(sNumber,1)
[ ] sTens = Left(sNumber,1)
[+] switch(sOnes)
[+] case "1"
[ ] sOnes = "One"
[+] case "2"
[ ] sOnes = "Two"
[+] case "3"
[ ] sOnes = "Three"
[+] case "4"
[ ] sOnes = "Four"
[+] case "5"
[ ] sOnes = "Five"
[+] case "6"
[ ] sOnes = "Six"
[+] case "7"
[ ] sOnes = "Seven"
[+] case "8"
[ ] sOnes = "Eight"
[+] case "9"
[ ] sOnes = "Nine"
[+] case "0"
[ ] sOnes = ""
[+] switch(sTens)
[+] case "1"
[+] switch(sOnes)
[+] case "One"
[ ] sOnes = ""
[ ] sTens = "Eleven"
[+] case "Two"
[ ] sOnes = ""
[ ] sTens = "Twelve"
[+] case "Three"
[ ] sOnes = ""
[ ] sTens = "Thirteen"
[+] case "Four"
[ ] sOnes = ""
[ ] sTens = "Fourteen"
[+] case "Five"
[ ] sOnes = ""
[ ] sTens = "Fifteen"
[+] case "Six"
[ ] sOnes = ""
[ ] sTens = "Sixteen"
[+] case "Seven"
[ ] sOnes = ""
[ ] sTens = "Seventeen"
[+] case "Eight"
[ ] sOnes = ""
[ ] sTens = "Eighteen"
[+] case "Nine"
[ ] sOnes = ""
[ ] sTens = "Ninteen"
[+] case ""
[ ] sTens = "Ten"
[ ]
[+] case "2"
[ ] sTens = "Twenty"
[+] case "3"
[ ] sTens = "Thirty"
[+] case "4"
[ ] sTens = "Forty"
[+] case "5"
[ ] sTens = "Fifty"
[+] case "6"
[ ] sTens = "Sixty"
[+] case "7"
[ ] sTens = "Seventy"
[+] case "8"
[ ] sTens = "Eighty"
[+] case "9"
[ ] sTens = "Ninty"
[+] case "0"
[ ] sTens = ""
[ ]
[ ]
[ ] sNumberString = sTens +" " + sOnes
[ ]
[ ] // for 3 digit numbers
[+] case 3
[ ] sOnes = Right(sNumber,1)
[ ] sTens = SubStr(sNumber,2,1)
[ ] sHundreds = Left(sNumber,1)
[+] switch(sOnes)
[+] case "1"
[ ] sOnes = "One"
[+] case "2"
[ ] sOnes = "Two"
[+] case "3"
[ ] sOnes = "Three"
[+] case "4"
[ ] sOnes = "Four"
[+] case "5"
[ ] sOnes = "Five"
[+] case "6"
[ ] sOnes = "Six"
[+] case "7"
[ ] sOnes = "Seven"
[+] case "8"
[ ] sOnes = "Eight"
[+] case "9"
[ ] sOnes = "Nine"
[+] case "0"
[ ] sOnes = ""
[ ]
[+] switch(sTens)
[+] case "1"
[+] switch(sOnes)
[+] case "One"
[ ] sOnes = ""
[ ] sTens = "Eleven"
[+] case "Two"
[ ] sOnes = ""
[ ] sTens = "Twelve"
[+] case "Three"
[ ] sOnes = ""
[ ] sTens = "Thirteen"
[+] case "Four"
[ ] sOnes = ""
[ ] sTens = "Fourteen"
[+] case "Five"
[ ] sOnes = ""
[ ] sTens = "Fifteen"
[+] case "Six"
[ ] sOnes = ""
[ ] sTens = "Sixteen"
[+] case "Seven"
[ ] sOnes = ""
[ ] sTens = "Seventeen"
[+] case "Eight"
[ ] sOnes = ""
[ ] sTens = "Eighteen"
[+] case "Nine"
[ ] sOnes = ""
[ ] sTens = "Ninteen"
[+] case ""
[ ] sTens = "Ten"
[ ]
[+] case "2"
[ ] sTens = "Twenty"
[+] case "3"
[ ] sTens = "Thirty"
[+] case "4"
[ ] sTens = "Forty"
[+] case "5"
[ ] sTens = "Fifty"
[+] case "6"
[ ] sTens = "Sixty"
[+] case "7"
[ ] sTens = "Seventy"
[+] case "8"
[ ] sTens = "Eighty"
[+] case "9"
[ ] sTens = "Ninty"
[+] case "0"
[ ] sTens = ""
[ ]
[+] switch(sHundreds)
[+] case "1"
[ ] sHundreds = "One"
[+] case "2"
[ ] sHundreds = "Two"
[+] case "3"
[ ] sHundreds = "Three"
[+] case "4"
[ ] sHundreds = "Four"
[+] case "5"
[ ] sHundreds = "Five"
[+] case "6"
[ ] sHundreds = "Six"
[+] case "7"
[ ] sHundreds = "Seven"
[+] case "8"
[ ] sHundreds = "Eight"
[+] case "9"
[ ] sHundreds = "Nine"
[+] case "0"
[ ] sHundreds = ""
[ ]
[+] if sTens=="" && sOnes==""
[ ] sNumberString = sHundreds + " Hundred "
[+] else
[ ] sNumberString = sHundreds + " Hundred and "+ sTens + " " + sOnes
[ ]
[ ] // for 4 digit numbers
[+] case 4
[ ] sOnes = Right(sNumber,1)
[ ] sTens = SubStr(sNumber,3,1)
[ ] sHundreds = SubStr(sNumber,2,1)
[ ] sThousands = Left(sNumber,1)
[+] switch(sOnes)
[+] case "1"
[ ] sOnes = "One"
[+] case "2"
[ ] sOnes = "Two"
[+] case "3"
[ ] sOnes = "Three"
[+] case "4"
[ ] sOnes = "Four"
[+] case "5"
[ ] sOnes = "Five"
[+] case "6"
[ ] sOnes = "Six"
[+] case "7"
[ ] sOnes = "Seven"
[+] case "8"
[ ] sOnes = "Eight"
[+] case "9"
[ ] sOnes = "Nine"
[+] case "0"
[ ] sOnes = ""
[+] switch(sTens)
[+] case "1"
[+] switch(sOnes)
[+] case "One"
[ ] sOnes = ""
[ ] sTens = "Eleven"
[+] case "Two"
[ ] sOnes = ""
[ ] sTens = "Twelve"
[+] case "Three"
[ ] sOnes = ""
[ ] sTens = "Thirteen"
[+] case "Four"
[ ] sOnes = ""
[ ] sTens = "Fourteen"
[+] case "Five"
[ ] sOnes = ""
[ ] sTens = "Fifteen"
[+] case "Six"
[ ] sOnes = ""
[ ] sTens = "Sixteen"
[+] case "Seven"
[ ] sOnes = ""
[ ] sTens = "Seventeen"
[+] case "Eight"
[ ] sOnes = ""
[ ] sTens = "Eighteen"
[+] case "Nine"
[ ] sOnes = ""
[ ] sTens = "Ninteen"
[+] case ""
[ ] sTens = "Ten"
[ ]
[+] case "2"
[ ] sTens = "Twenty"
[+] case "3"
[ ] sTens = "Thirty"
[+] case "4"
[ ] sTens = "Forty"
[+] case "5"
[ ] sTens = "Fifty"
[+] case "6"
[ ] sTens = "Sixty"
[+] case "7"
[ ] sTens = "Seventy"
[+] case "8"
[ ] sTens = "Eighty"
[+] case "9"
[ ] sTens = "Ninty"
[+] case "0"
[ ] sTens = ""
[ ]
[+] switch(sHundreds)
[+] case "1"
[ ] sHundreds = "One"
[+] case "2"
[ ] sHundreds = "Two"
[+] case "3"
[ ] sHundreds = "Three"
[+] case "4"
[ ] sHundreds = "Four"
[+] case "5"
[ ] sHundreds = "Five"
[+] case "6"
[ ] sHundreds = "Six"
[+] case "7"
[ ] sHundreds = "Seven"
[+] case "8"
[ ] sHundreds = "Eight"
[+] case "9"
[ ] sHundreds = "Nine"
[+] case "0"
[ ] sHundreds = ""
[ ]
[+] switch(sThousands)
[+] case "1"
[ ] sThousands = "One"
[+] case "2"
[ ] sThousands = "Two"
[+] case "3"
[ ] sThousands = "Three"
[+] case "4"
[ ] sThousands = "Four"
[+] case "5"
[ ] sThousands = "Five"
[+] case "6"
[ ] sThousands = "Six"
[+] case "7"
[ ] sThousands = "Seven"
[+] case "8"
[ ] sThousands = "Eight"
[+] case "9"
[ ] sThousands = "Nine"
[+] case "0"
[ ] sThousands = ""
[ ]
[ ]
[+] select
[+] case sTens=="" && sOnes=="" && sHundreds==""
[ ] sNumberString = sThousands + " Thousand "
[+] case sHundreds==""
[ ] sNumberString = sThousands + " Thousand " + sTens + " " + sOnes
[+] case sTens=="" && sOnes==""
[ ] sNumberString = sThousands + " Thousand " + sHundreds + " Hundred "
[+] default
[ ] sNumberString = sThousands + " Thousand " + sHundreds + " Hundred and " + sTens + " " + sOnes
[ ]
[ ]
[ ] // other cases
[-] default
[ ] Print("*** Number length is invalid")
[ ]
[ ]
[ ]
[ ] return sNumberString



--------------------
Regards,
Krishna Chaitanya

=====================
Try and fail, but don't fail to try
=====================

Edited by jamesso (11/19/08 07:33 AM)


Post Extras: Print Post   Remind Me!   Notify Moderator  
KrisrisK
Member


Reged: 04/21/08
Posts: 340
Loc: Hyderabad
Re: Donate a user defined function to this topic [Re: chinna_you]
      #490237 - 06/10/08 03:33 AM

Code:

******************************************************
RandomSelect()- this method selects an item randomly
and returns the string
Note: can be applied to popup list, radio list etc.
******************************************************
[+] STRING RandomSelect()

[ ] INTEGER iRandSelect
[ ] STRING sSelectedItem
[ ] iRandSelect = RandInt (1,this.GetItemCount())
[ ] sSelectedItem = this.GetItemText(iRandSelect)
[ ] this.Select(sSelectedItem)
[ ] return sSelectedItem



--------------------
Regards,
Krishna Chaitanya

=====================
Try and fail, but don't fail to try
=====================

Edited by jamesso (11/19/08 07:31 AM)


Post Extras: Print Post   Remind Me!   Notify Moderator  
kotiatsqaforums
Member


Reged: 06/22/08
Posts: 67
Loc: Hyderabad, AndhraPradesh
Re: Donate a user defined function to this topic [Re: chinna_you]
      #493659 - 06/23/08 05:30 AM

This function is to search for a string the Source code of a web page.

Parameters:
Page -> Window
SearchStr -> String to search for

Return value: TRUE (if exists) or FALSE (if not exists)

Code:

[+] Boolean SearchString(Window Page, String SearchStr)
[ ] Page.SetActive()
[ ] lsFile=Page.GetPageSource(FALSE)
[-] for i=1 to ListCount(lsFile)
[-] if (StrPos(SearchStr,lsFile[i])!=0)
[ ] //Print(lsFile[i])
[ ] goto Done
[ ] Done:
[ ] bFound = MatchStr("*{SearchStr}*", lsFile[i])
[ ] //print(bFound)
[ ] return bFound



Edited by jamesso (11/19/08 07:27 AM)


Post Extras: Print Post   Remind Me!   Notify Moderator  
rakeshraghvani12345
Junior Member


Reged: 01/21/05
Posts: 336
Loc: UK
Re: Donate a user defined function to this topic [Re: kotiatsqaforums]
      #524515 - 10/15/08 07:02 AM

To BlockInput function blocks keyboard and mouse input events
Code:

[-] dll "user32.dll"
[ ] int BlockInput(int fBlockIt)
[-] testcase TestInput() appstate none
[ ] BlockInput(1)
[ ] Sleep(10)
[ ] BlockInput(0)


Press CTRL+ALT+DEL to recover, if your function fails to unblock input!

Edited by jamesso (11/19/08 07:28 AM)


Post Extras: Print Post   Remind Me!   Notify Moderator  
Rajanish_Thakur
Member


Reged: 03/06/08
Posts: 125
Loc: Bangalore,India
Re: Donate a user defined function to this topic [Re: chinna_you]
      #533444 - 11/21/08 03:49 AM

////////////////////////////////////Functions for removing double space between strings////////////////////


[+] STRING RemoveExtraSpace_Double(STRING sOriginal1, STRING sReplacement)
[ ] string sOriginal = AddSpace(sOriginal1)
[ ] STRING sResult = ""
[ ] STRING sTemp
[ ] INTEGER iCounter
[ ] int i =0
[-] for iCounter = 1 to Len(sOriginal)
[ ] ////Print("sOriginal[{iCounter}]",sOriginal[iCounter])
[ ] sTemp = sOriginal[iCounter]
[-] if((Asc(sTemp) != 32) )
[ ] i=0
[-] if ( (Asc(sTemp) == 32))
[-] if(i==0) || (i==1)
[ ] sResult = sResult + sTemp
[-] if(i !=0 ) && (i !=1 )
[ ] sResult = sResult + sReplacement
[ ] i = i+1
[ ]
[-] else
[ ] sResult = sResult + sTemp
[ ] return sResult



[+] string AddSpace(string Orig)
[ ] int i
[ ] string sChang=Orig
[ ] //Print(Orig)
[+] // for(i=1;i<=len(Orig);i++)
[ ] // sChang =""
[-] for(i=1;i<=len(Orig);i++)
[-] if(isdigit(Orig))
[-] if(isspace(Orig[i+1]))
[ ] sChang = Stuff (Orig,i+1,0," ")
[ ] Orig=sChang
[-] if(isalpha(Orig))
[ ]
[ ] //Print("Final Change",sChang)
[ ] return sChang

--------------------
Thanks & Regards,
RS_Thakur


Post Extras: Print Post   Remind Me!   Notify Moderator  
Rajanish_Thakur
Member


Reged: 03/06/08
Posts: 125
Loc: Bangalore,India
Re: Donate a user defined function to this topic [Re: Rajanish_Thakur]
      #533447 - 11/21/08 03:55 AM


///Fuctions for searching a string in text file//

[+] boolean grepfind38( string sFile,STRING sMatchItem,out string output)
[ ] HFILE OutputFileHandle
[ ] STRING sLine
[ ] FILESHARE fShare
[ ] fShare = FS_DENY_NONE
[ ] OutputFileHandle = FileOpen(sFile,FM_READ,fShare)
[-] while (FileReadLine (OutputFileHandle, sLine))
[-] if (MatchStr("*"+sMatchItem+"*",sLine))
[ ] output =sLine
[ ] return (true)
[-] else
[ ] output =" "
[ ] FileClose(OutputFileHandle)
[ ] return(false)

--------------------
Thanks & Regards,
RS_Thakur


Post Extras: Print Post   Remind Me!   Notify Moderator  
davidgenrich
Moderator


Reged: 06/30/99
Posts: 539
Loc: Fremont, CA, USA
Re: Donate a user defined function to this topic [Re: Rajanish_Thakur]
      #539536 - 12/18/08 01:07 PM

Why go through all the trouble of the RemoveExtraSpace_Double () function to remove double spaces when you can simply use the 4Test function StrTran ():

Code:

// replace double space with a single space
string myString = "This is a Test"


myString = StrTran (myString, " ", " ")




--------------------
David Genrich
david.genrich@e2open.com


Post Extras: Print Post   Remind Me!   Notify Moderator  
TesterDec06
Newbie


Reged: 12/31/08
Posts: 21
Re: Donate a user defined function to this topic [Re: Bapanna Setti]
      #546484 - 01/28/09 11:21 PM

Hi blacst,

Thanks for your function BOOLEAN SetBrowserEnvironment().I have a query in the function. In the function, you are using a variable called "HKEY_LOCAL_MACHINE". Can you please guide me where it is initalized. Because i am getting an error like "the variable is not defined"

Thanks in advance


Post Extras: Print Post   Remind Me!   Notify Moderator  
Ravindra_QA
Member


Reged: 09/18/08
Posts: 29
Loc: Bengaluru, Karnataka
Re: Donate a user defined function to this topic [Re: TesterDec06]
      #549718 - 02/11/09 07:17 AM

Here is a function that we can use to calculate page load times.
[-] Void timercode()
[ ] //Timer starts here
[ ] STRING sOverallTime
[ ] HTIMER TotalTimer
[ ] TotalTimer = TimerCreate ()
[ ] TimerStart (TotalTimer)
[ ] Browser.WaitForReady ()
[ ] TimerStop (TotalTimer) //stopping the timer
[ ] sOverallTime = TimerStr (TotalTimer)
[ ] Print ("The Page loads in {sOverallTime} seconds")
[ ] TimerDestroy (TotalTimer)

--------------------
------------
Ravindra

"If you have the inclination, you have the time"


Post Extras: Print Post   Remind Me!   Notify Moderator  
cyb_abhijeet
Member


Reged: 11/05/08
Posts: 88
Re: Donate a user defined function to this topic [Re: chinna_you]
      #578680 - 07/08/09 04:29 AM

This simple code will compare the string line by line within the File by using MatchStr()

---------------------------------------------------------

HFILE hfile = SYS_FileOpen ("\\machine1\SharedFiles\ApplicationLog.log")
STRING sLine

While (FileReadLine(hFile, sLine))
if(MatchStr("*fatal errors*", sLine))
Print("String Matched")
else
Print ("No Match Found")
FileClose(hFile)


Post Extras: Print Post   Remind Me!   Notify Moderator  
RakeshSharma
Member


Reged: 04/14/07
Posts: 73
Loc: Gurgaon, India
Re: Donate a user defined function to this topic [Re: chinna_you]
      #590398 - 09/10/09 09:53 PM

// Fuction to pick the date from Date control in VB form.

[+] POINT LocateCalander(WINDOW wDate)
[ ] POINT p
[ ] INTEGER iMaxYPosition
[ ] INTEGER iXIncrement = 20, iYIncrement = 30
[ ] INTEGER iXStartPos = 15, iYStartPos = 15
[-] with WinForm.Date1
[ ] iMaxYPosition = .GetRect().yPos-.GetRect().ySize
[ ] RECT rect
[ ] rect = wDate.GetRect()
[ ] p.x = iXStartPos
[ ] p.y = iYStartPos
[-] while(!Calander.Exists())
[+] if p.x >= rect.xPos
[ ] p.x = iXStartPos
[ ] p.y = p.y+iYIncrement
[ ] continue
[+] if p.y > iMaxYPosition
[ ] break
[ ] wDate.Click(1, p.x, p.y)
[ ] p.x = p.x+iXIncrement
[ ] return p

--------------------
Regds,
Rakesh
If fate means you to lose, give it a good fight anyhow


Post Extras: Print Post   Remind Me!   Notify Moderator  
AmitX
Member


Reged: 09/16/08
Posts: 43
Re: Donate a user defined function to this topic [Re: chinna_you]
      #619686 - 03/25/10 10:52 PM

Picking value from registry and available throughout the whole testcase

[ ]
[ ] use "msw32.inc"
[ ]
[ ] int sKey=HKEY_LOCAL_MACHINE
[ ] String sKeyPath="SOFTWARE\Employee\"
[ ]
[ ] const eName="eName"
[ ] const eAge="eAge"
[ ] const eDept="eDept"
[ ] const eEcn="eEcn"
[ ] const eAdd="eAddress"
[ ] const eWait="waittime"
[ ]
[ ] //record of employee
[+] type Employee is record
[ ] int eEcn
[ ] String eName
[ ] int eAge
[ ] String eAddress
[ ] String eDept
[ ] int wait
[ ]
[ ] Employee emp
[ ]
[ ] //function which is picking value from registry
[+] void GetUserOption(inout Employee emp)
[ ] print("Entering in GetUserOption function ")
[+] do
[ ] emp.eName=Sys_GetRegistryValue(sKey,sKeyPath,eName)
[-] except
[ ] ExceptLog()
[-] do
[ ] emp.eAge=Val(Sys_GetRegistryValue(sKey,sKeyPath,eAge))
[+] except
[ ] ExceptLog()
[+] do
[ ] emp.eDept=Sys_GetRegistryValue(sKey,sKeyPath,eDept)
[+] except
[ ] ExceptLog()
[+] do
[ ] emp.eEcn=Val(Sys_GetRegistryValue(sKey,sKeyPath,eEcn))
[+] except
[ ] ExceptLog()
[+] do
[ ] emp.eAddress=Sys_GetRegistryValue(sKey,sKeyPath,eAdd)
[+] except
[ ] ExceptLog()
[-] do
[ ] emp.wait=Val(Sys_GetRegistryValue(sKey,sKeyPath,eWait))
[+] except
[ ] ExceptLog()
[ ]
[ ] //override default recovery system
[+] ScriptEnter()
[ ] GetUserOption(emp)
[ ]
[ ]
[ ] //testcase: which read value from registry
[+] testcase ReadFromRegistry() appstate none
[ ] print("Employee Name:->" +emp.eName)
[ ] print("Employee Age:->" +Str(emp.eAge))
[ ] print("Employee Address:->"+emp.eAddress)
[ ] print("Employee code:->" +Str(emp.eEcn))
[ ] print("Employee Dept:->"+emp.eDept)
[ ] print("Wait Time:->"+Str(emp.wait))
[ ]

--------------------
Amit Nigam

SQA,Oracle


Post Extras: Print Post   Remind Me!   Notify Moderator  
beniamin
Member


Reged: 11/27/08
Posts: 27
Re: Donate a user defined function to this topic [Re: AmitX]
      #619726 - 03/26/10 04:39 AM

Hi,

I have been working on the issue to have all result related files automatically uploaded to SCTM when executing a SilkTest test case.
The problem was that SCTM execution server (respectively the ST runtime) generetes for each test case an own result folder. So when you try to do for example screen shots, logs or anything related to the specific test case the files won't be uploaded automatically to SCTM.

here comes the solution from Borland:

Code:
 [-] STRING CalculateResultDirPath()
[ ] STRING dirPath = "{SYS_GETENV("TMP")}\SCC_ExecServer_19124_19125\PerfProjects"
[-] if (SYS_DirExists(dirPath))
[ ] LIST OF FILEINFO fileInfos
[ ] datetime lastModified = "1970-01-01 00:00"
[ ] INTEGER newestResultDirIdx = 1
[ ] fileInfos = SYS_GetDirContents(dirPath)
[ ]
[ ] FILEINFO fileInfo
[ ] INTEGER i = 1
[-] for each fileInfo in fileInfos
[-] if (fileInfo.bIsDir && lastModified < fileInfo.dtLastModifyTime)
[ ] lastModified = fileInfo.dtLastModifyTime
[ ] newestResultDirIdx = i
[ ] i++
[ ] return "{dirPath}\{fileInfos[newestResultDirIdx].sName}"
[-] else
[ ] dirPath = "{SYS_GETENV("TEMP")}\Bitmap"
[-] if !SYS_DirExists(dirPath)
[ ] SYS_MakeDir(dirPath)
[ ] return dirPath



Have fun...


Post Extras: Print Post   Remind Me!   Notify Moderator  
LangtonBen
Newbie


Reged: 03/31/09
Posts: 7
Re: Donate a user defined function to this topic [Re: chinna_you]
      #628556 - 05/28/10 11:44 AM

Here's a function that finds a window/control within a window, recursively. I use it with a data-driven framework, so that I can operate on controls nested within containers, without having to specify the full path like window.container1.container2.control.

[ ] // Returns a variable of type WINDOW for sControl within wWindow
[ ] // sControl may be an indirect descendant of the window (ex. grandchild)
[ ] // Helper function for a number of other functions
[-] WINDOW GetChildWindow(WINDOW wWindow, STRING sControl)
[-] // 2010-04-21 - Ben Langton
[ ] // Example:
[ ] // dlgDialog
[ ] // DataWin dwDataWin
[ ] // DWEditField txtField
[ ]
[ ] // GetChildWindow(dlgDialog, txtField)
[ ] // Returns the WINDOW dlgDialog.DWEditField.txtField
[ ]
[ ] // Debug code
[ ] // Print("GetChildWindow({wWindow}, {sControl})")
[ ]
[ ] // Reference to the control that will eventually be returned
[ ] WINDOW wControl
[ ]
[ ] // If sControl has a "." in it, try to resolve the reference - only one level deep, currently
[ ] // Generally, it's safest not to call this function with sControl having a "." in it.
[ ] // Because this may be a bit sketchy...
[-] if(StrPos(".", sControl) > 0)
[ ] wWindow = GetChildWindow(wWindow, GetField(sControl, ".", 1))
[ ] sControl = SubStr(sControl, StrPos(".", sControl) + 1)
[ ] wWindow = GetChildWindow(wWindow, sControl)
[ ]
[ ] // If the control has been found, then return it.
[-] if(wWindow.sName == sControl)
[ ] return wWindow
[ ]
[ ] // Loop through the children of the window until the specified control is found
[ ] WINDOW wWinChild
[-] for each wWinChild in wWindow.lwChildren
[ ] // Debug Code
[ ] // Print("Child: {wWindow}.{wWinChild.sName}")
[ ]
[-] if(wWinChild.sName == sControl)
[ ] // Debug Code
[ ] Print("GetChildWindow found child '{sControl}' in '{wWinChild}'")
[ ]
[ ] return wWinChild
[ ]
[ ] // Only get here if the specified control is not a child of the window (ex. it could be a grandchild)
[ ] // Call the function recursively, passing in the child.
[ ] wControl = GetChildWindow(wWinChild, sControl)
[-] if(IsNull(wControl) == False)
[ ] return wControl
[ ]
[ ] return NULL


Post Extras: Print Post   Remind Me!   Notify Moderator  
bellis89
Newbie


Reged: 06/23/11
Posts: 7
Re: Donate a user defined function to this topic [Re: chinna_you]
      #704121 - 04/12/12 01:48 PM

I had to write IDs of items created to a file and recall them.


Write to file

[-] HFILE ProjectID
[ ] // Open file, append variable and close file
[ ] ProjectID = FileOpen ("<insert path and name of file>", FM_WRITE)
[ ] FileWriteLine (ProjectID, "{sProjectID}")
[ ] FileClose (ProjectID)


To read from file

[-] string GetProjectID()
[ ] HFILE ProjectIDRead
[ ] STRING sProjectID
[ ] ProjectIDRead = FileOpen ("<insert path and name of file>", FM_READ)
[ ] while (FileReadLine (ProjectIDRead, sProjectID))
[ ] FileClose (ProjectIDRead)
[ ] return sProjectID


Locator looks like this

[-] DomElement ProjectID
[ ] locator "//A[@id='{GetProjectID()}']/../../..//IMG"


Post Extras: Print Post   Remind Me!   Notify Moderator  
Pages: 1 | 2 | 3 | >> (show all)



Extra information
0 registered and 11 anonymous users are browsing this forum.

Moderator:  AJ, jamesso, DJGray, David Reed 

Print Topic

Forum Permissions
      You cannot start new topics
      You cannot reply to topics
      HTML is disabled
      UBBCode is enabled

Rating: ****
Topic views: 52669

Rate this topic

Jump to

Contact Us | Privacy statement SQAForums

Powered by UBB.threads™ 6.5.5