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  
Pages: 1 | 2 | 3 | >> (show all)



Extra information
0 registered and 12 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: 52666

Rate this topic

Jump to

Contact Us | Privacy statement SQAForums

Powered by UBB.threads™ 6.5.5