|
Overview
This article provides an introduction to the key functions available for scripting within the Login Enterprise Virtual Appliance. Our scripting framework offers a comprehensive set of tools to enhance automation and control over Windows applications.
- Basic Functions: Essential commands for managing application execution and performance, including launching and closing applications, measuring action durations, and logging key events.
- Window Functions: Tools for interacting with and controlling windows and their elements, allowing precise manipulation and error handling in your automation scripts.
- Mouse and Keyboard Functions: Functions that simulate user input through typing and mouse actions, enabling you to script user interactions and test application workflows effectively.
- File and Registry Functions: Capabilities for managing file operations and interacting with the Windows registry, ensuring smooth automation of file and registry tasks.
- Browser Functions: Functions designed to control web browsers, navigate URLs, and interact with web elements, streamlining browser automation for web interactions.
- Native Automation Scripting: Advanced capabilities for deeper control over Windows applications using native OS elements, allowing for precise targeting and robust UI automation.
- Control Flow Functions: Conditional logic and iteration tools that enable dynamic scripting, error handling, and adaptable automation workflows.
Login Enterprise also comes with the Script Editor, a tool designed to assist administrators in creating custom application workflows. These workflows can be seamlessly incorporated into various testing scenarios, including Application, Load, and Continuous Tests. By leveraging the Script Editor, administrators can streamline test creation and execution, ensuring comprehensive and efficient testing processes tailored to specific application requirements.
- For more details on the Script Editor, its benefits, use cases, and more, see the Script Editor.
- The Script Editor comes with v1 of the Script Recorder, capable of recording WinApps. To learn more about the Script Recorder, see the Script Recorder.
Basic functions
Basic functions offer essential tools for managing application execution and performance. Commands such as START and STOP are used to launch and close applications, while StartTimer and StopTimer help measure the duration of actions within your scripts. You can log key events, take screenshots for validation, and capture environment variables. These functions also include error handling features, providing greater control and visibility over script execution, which ensures smooth automation of your testing processes.
Start
START executes the associated application and creates the mainWindow variable. The START command will auto-detect the application's title, class, and process name. All parameters are optional.
Syntax
START(string mainWindowTitle = null, string mainWindowClass = null, string processName = null, int timeout = 180, bool continueOnError = false);
Parameters | Type | Default Value | Description |
mainWindowTitle | string | window title. Example: "Untitled - Notepad" | |
mainWindowClass | string | window class. Example: "Win32 Window:Notepad" | |
processName | string | window process name. Example: "notepad" | |
timeout | int | 180 | timeout in seconds for the window to appear |
continueOnError | bool | false | continue with the script on error |
Code Example
START(mainWindowTitle:"Untitled - Notepad", mainWindowClass:"Win32 Window:Notepad", processName:"notepad", timeout:10);
Stop
The STOP command terminates the associated application. The timeout parameter specifies the maximum amount of seconds an application can take to gracefully stop. After the timeout is reached, the application is closed forcefully.
Syntax
STOP(int timeout = 5);
Parameter | Type | Default Value | Description |
timeout | int | 5 | timeout in seconds to close an application |
Code Example
STOP(timeout:5);
StartTimer
The StartTimer function allows you to create a custom timer to measure the time one or more actions take within a script. The timers are reported back to the Login Enterprise server as measurements and can be used to trigger a notification if the measurement is over the configured threshold. Measurements are displayed in the Login Enterprise dashboard and charts. StartTimer must be stopped with either CancelTimer or StopTimer.
Syntax
StartTimer(string name);
Parameter | Type | Default Value | Description |
name | string | defines the name of the timer. max of 32 characters. |
Note: Timer name must only contain alphanumeric characters and underscore
Code Example
StartTimer(name:"Create_New_File");
StopTimer(name:"Create_New_File");
StopTimer
StopTimer is used to stop a timer that's started by StartTimer. The StopTimer name should be the same as the StartTimer.
Syntax
StopTimer(string name);
Parameter | Type | Default Value | Description |
name | string | defines the name of the timer. max of 32 characters. |
Note: Timer name must only contain alphanumeric characters and underscore
Code Example
StartTimer(name:"Save_File_To_Network");
StopTimer(name:"Save_File_To_Network");
CancelTimer
The CancelTimer command is used to cancel a timer. The CancelTimer name should be the same as the StartTimer.
Syntax
CancelTimer(string name);
Parameter | Type | Default Value | Description |
name | string | defines the name of the timer. max of 32 characters. |
Note: Timer name must only contain alphanumeric characters and underscore
Code Example
StartTimer(name:"Create_New_File");
CancelTimer(name:"Create_New_File");
SetTimer
Create your own custom timers with the SetTimer function. In many cases you could call an external value of a system resource like CPU % utilization and have it be visible in the Login Enterprise reporting.
SetTimer does not require a start and stop function as it collects an integer at the time it is executed.
Syntax
SetTimer("name", value);
Parameter | Type | Default Value | Description |
name | string | defines the name of the timer. max of 32 characters. | |
value | integer | value collected when timer is called |
Note: Timer name must only contain alphanumeric characters and underscore
Code Example
int myCounter = {some code that gets a Windows performance counter in milliseconds};
SetTimer(“MyTimer”,myCounter);
Wait
The Wait function will wait for an X amount of time in seconds before continuing with the script.
Syntax
Wait(double seconds);
Parameter | Type | Default Value |
seconds | double | |
showOnScreen | boolean | true |
onScreenText | string |
Code Example
Wait(seconds:10, showOnScreen:true, onScreenText:"Waiting 10 seconds");
Log
The log function will log to console if you are using the scriptrunner. When using it as part of the Login Enterprise appliance, it logs to %temp%\LoginPI\Logs.
Syntax
Log(string message);
Log(object component);
Parameters | Type | Default Value |
message | string | |
component | object |
Code Example
Log(message:"Log Message");
Log(component:MainWindow);
Abort
Abort is used to gracefully exit the script and throw an error message. The error will be shown as an 'Application failure' on the Login Enterprise dashboard, under events.
Syntax
ABORT(string error);
Parameter | Type | Default Value |
error | string |
Code Example
ABORT(error:"An error occurred");
ShellExecute
Run a script or application in the Windows Shell
Syntax
ShellExecute(string commandLine, string workingFolder = "", bool waitForProcessEnd = true, int timeout = 180, bool forceKillOnExit = true);
Parameter | Type | Default Value | Description |
commandLine | string | ||
workingFolder | string | ||
waitForProcessEnd | bool | true | wait for the process to finish before continuing. |
timeout | int | 180 | defines how long to wait for the process to end before it's killed. |
forceKillOnExit | bool | true | forces the application / process to close or stay open after the command has ended. Default is true. |
Code Example
ShellExecute("mspaint", waitForProcessEnd: false, timeout: 15, forceKillOnExit: false);
Create Event
The CreateEvent function will generate a custom event on the Enterprise appliance which is shown in the results page of a Continuous, Load, and Application test.
Syntax
CreateEvent(title:"", description:"");
Parameters | Type | Default Value |
Title | string | |
Description | string |
Code Example
CreateEvent(title:"Windows Update Available", description:"Update is available on hostname x");
Get Environment
GetEnvironmentVariable is used as the name suggest to retrieve an environment variable. The GetEnvironmentVariable can be stored in a variable to use multiple times in your script. Note that if a continueOnError is not set and if you do not have permissions to retrieve the variable, the script will stop.
Syntax
GetEnvironmentVariable(variableName:"", continueOnError:false);
Parameters | Type | Default Value |
variableName | string | |
continueOnError | bool | false |
Code Example
var TempEnv = GetEnvironmentVariable("temp", continueOnError:true);
Log ($"The environment path = {TempEnv}");
Type ($"{TempEnv}");
Take Screenshot
The take screenshot command is used to create custom screenshots that are sent to the Login Enterprise appliance. This functionality can be used to verify the visual output of an application. This will also work for your Application Testing.
The name field cannot handle spaces, these need to be underscored.
Syntax
TakeScreenshot(name:"", description:"");
Parameters | Type | Default Value |
name | string | |
description | string | null |
Code Example
TakeScreenshot(name:"Notepad",description: "Check if notepad has loaded the correct file");
Window functions
Window functions provide capabilities for interacting with and controlling windows and their elements in a Windows environment. Use FindWindow to detect windows by title, class, or process name. The FindControl and FindControlWithXPath functions enable interaction with specific controls, such as buttons or text fields. You can manipulate windows and controls using Click, Maximize, and GetBounds, allowing for precise actions and automation. Additionally, DumpHierarchy is available for troubleshooting by exporting a control tree to a file. These functions offer granular control over window elements and include conditional error handling.
FindWindow
FindWindow can be used to detect a new window or a window that is already opened. Each window has a set of information: class, title, and process name, that can be searched on. The ApplicationXRay tool can be used to detect the title, class, and process name of a window or control to allow you to find it in code later.
Syntax
FindWindow(string title = null, string className = null, string processName = null, int timeout = 30, bool continueOnError = false);
Parameter | Type | Default Value | Description |
title | string | find window matching title | |
className | string | find window matching classname | |
processName | string | find window matching process name | |
timeout | int | 30 |
timeout in seconds to find window |
continueOnError | bool | false | continue with script if an error is encountered |
Code Example
FindWindow(title:"*Untitled*", timeout: 5);
FindWindows
Find all windows by title, class, and/or process. If you specify multiple parameters, only the windows matching all criteria will be returned. The parameters do accept wildcards (*). This method will return whenever even if zero windows are found. If no window is found within the given timeout, it will return an empty array.
Syntax
var windowList = FindWindows(title:"", classname:"", processname:"", timeout = 30);
foreach (var myWindow in windowList) {
....
}
Parameter | Type | Default Value | Description |
title | string | title of window | |
className | string | window class | |
processName | string | name of windows process | |
timeout | int | 30 | timeout value |
Code Example
FindWindow(title:"*Untitled*", timeout: 5);
Control Actions
When the engine finds the window or object, it can perform multiple actions on the window/object. Using the above example, the following window control actions are available:
Name | Description |
openDialogue.Click(); | |
openDialogue.Close(); | |
openDialogue.DoubleClick(); | |
openDialogue.FindControl(); | |
openDialogue.FindControlWithXPath(); | |
openDialogue.Focus(); | |
openDialogue.GetAllChildControls(); | Gets all direct child controls for the window (can also be used on a control) |
openDialogue.GetBounds(); |
Retrieves the window or control boundary coordinates in relation to the screen resolution, returning a WindowsCoordinates structure that includes X and Y coordinates along with additional properties. Returns a WindowsCoordinates structure containing properties and methods for manipulating and interacting with the retrieved coordinates. GetBounds() contains the following properties:
Available methods on coordinate pair properties (Center, LeftBottom, LeftTop, RightBottom, RightTop):
Chaining example: The methods can be chained together for more complex actions. For instance, the following code snippet retrieves the center of control, moves slightly down and to the left, and then performs a right-click: javascriptCopy codevar myThing = MainWindow.FindControl(…); Additional notes: The GetBounds() method not only retrieves the boundary coordinates but also allows for dynamic interaction through the WindowsCoordinates structure. |
openDialogue.GetClass(); | Gets the class name for the window or control |
openDialogue.GetProcess(); | Gets the processname for the window or control |
openDialogue.GetTitle(); | Gets the title for the window or control |
openDialogue.Maximize(); | |
openDialogue.Minimize(); | |
openDialogue.MoveMouseToCenter(); | Moves the mouse to the center of the window |
openDialogue.Restore(); | |
openDialogue.RightClick(); | |
openDialogue.Type(""); |
Type directly to the window and keeps the focus |
openDialogue.GetText(); |
Retrieves the value from the object |
openDialogue.SwitchTopMostWindow(); |
Allows a window to stay on top rather than behind a newly opened window. It provides a better defense against popups overlapping your active window while running a workload. |
NativeWindowHandle |
For details, see the NativeWindowHandle |
NativeAutomationElement |
For details, see the NativeAutomationElement |
FindControl
Each window has a set of controls (buttons, input fields, text fields, etc...). Using FindControl allows you to find and subsequently interact with these controls.
Syntax
FindControl(string className = null, string title = null, int timeout = 5, bool searchRecursively = true, bool continueOnError = false);
Parameter | Type | Default Value | Description |
className | string | defines the class name of the control to find | |
title | string | defines the title of the control to find | |
timeout | int | 5 | timeout period |
searchRecursively | bool | true | defines if only the direct childs or all indirect children should be searched |
continueOnError | bool | false | continue with the script if control is not found |
Code Example
MainWindow.FindControl(className : "Button:Button", title : "&Open").Click();
FindControlWithXPath
Each window has a set of controls (buttons, input fields, text fields, etc...). Using FindControlWithXPath allows you to find and subsequently interact with these controls.
Syntax
FindControlWithXPath(string xPath, int timeout = 5, bool continueOnError = false);
Parameter | Type | Default Value | Description |
xPath | string | (x)Path to the control | |
timeout | int | 5 | timeout period |
continueOnError | bool | false | continue with the script if control is not found |
Code Example
MainWindow.FindControlWithXPath(xPath : "Button:Button").Click();
DumpHierarchy
Every window has a control tree with all classes and names. For troubleshooting purposes, we have a DumpHierarchy method. DumpHierarchy dumps the control tree to a text file.
Syntax
DumpHierarchy(string filePath, bool refreshBeforeDump = false);
Parameter | Type | Default Value | Description |
filePath | string | defines where to store the dump | |
refreshBeforeDump | bool | false | defines if we should refresh the control tree before the dump |
Code Example
var Open = FindWindow(title:"Open");
Open.DumpHierarchy(filePath:"C:\\dump.txt");
Mouse and Keyboard functions
Mouse and keyboard functions automate interactions with Windows applications by simulating user input through typing and mouse actions. The Type command lets you enter text or press keys at a specified speed, supporting key combinations and encrypted application credentials. Mouse functions like Click, RightClick, and DoubleClick provide precise control over application elements based on X-Y coordinates. You can also use MouseMove and MouseMoveBy to reposition the cursor, while KeyDown and KeyUp simulate holding or releasing keys. These functions enable you to script user actions, test application workflows, and ensure that inputs and interactions behave as expected in real-world conditions.
Type
The Type command is used to type text or press keys.
Syntax
Type(string text, int cpm = 300, hideInLogging:true)
Parameter | Type | Default Value | Description |
text | string | text to type or keys to press | |
cpm | int | 300 | characters per minute |
hideInLogging | Boolean | true | hides entry from being logged |
Variable options:
- ApplicationPassword - using this variable you can enter an encrypted password for a specific application.
- ApplicationUser - using this variable you can enter an encrypted user for a specific application.
For information on scripting application credentials, see Scripting secure application credentials.
To learn about the encryption types and certificates, see the Encryption technology.
Code Example
// use type to type text
Type("Insert Text Here");
// use type to press the enter key
Type("{ENTER}");
// use type to press the enter key twice
Type("{ENTER}".Repeat(2));
// use type to press ctrl + O
Type("{CTRL+O}");
// use type to enter a path. backslash is an escape character.
Type("C:\\Folder\\Folder1\\something.txt");
// use @ sign to type path
Type(@"C:\Folder\Folder1\something.txt");
// type quotes
// use backslash to escape quote e.g. \"
Type("\"test\""); // this will type "test"
// type quotes
// use @ in front of string and use double quotes
Type(@"""test"""); // this will type "test"
// typing to a window variable will keep the focus on that window
MainWindow.Type("Insert text here");
KeyDown(KeyCode.SHIFT); // Holds the SHIFT key
Type("insert non-capital text here"); // This text will be typed in uppercase
KeyUp(KeyCode.SHIFT); // Releases the SHIFT key
Type("insert non-capital text here"); // This text will be typed in lowercase
Click
The Click command is used to mouse-click on an X-Y coordinate.
Syntax
Click(double x, double y, bool continueOnError = false);
Parameter | Type | Default Value | Description |
x | double | x is the horizontal coordinate | |
y | double | y is the vertical coordinate | |
continueOnError | bool | false | continue with the script on error |
Code Example
Click(x:10, y:10);
RightClick
The RightClick command is used right click on an X Y coordinate.
Syntax
RightClick(double x, double y, bool continueOnError = false);
Parameter | Type | Default Value | Description |
x | double | x is the horizontal coordinate | |
y | double | y is the vertical coordinate | |
continueOnError | bool | false | continue with the script on error |
Code Example
RightClick(x:10, y:10);
DoubleClick
The DoubleClick command is used double click on an X Y coordinate.
Syntax
DoubleClick(double x, double y, bool continueOnError = false);
Parameter | Type | Default Value | Description |
x | double | x is the horizontal coordinate | |
y | double | y is the vertical coordinate | |
continueOnError | bool | false | continue with the script on error |
Code Example
DoubleClick(x:10, y:10);
MouseMove
The MouseMove command is used to move the mouse/cursor to a set of X Y coordinate.
Syntax
MouseMove(double x, double y, bool continueOnError = false);
Parameter | Type | Default Value | Description |
x | double | x is the horizontal coordinate | |
y | double | y is the vertical coordinate | |
continueOnError | bool | false | continue with the script on error |
Code Example
MouseMove(x:10, y:10);
MouseMoveBy
The MouseMoveBy command is used to move the mouse/cursor by a set of pixels relative to the current position.
Syntax
MouseMoveBy(double dx, double dy, bool continueOnError = false);
Parameter | Type | Default Value | Description |
dx | double | dx is the horizontal coordinate | |
dy | double | dy is the vertical coordinate | |
continueOnError | bool | false | continue with the script on error |
Code Example
MouseMoveBy(dx:10, dy:10);
MouseDown
The MouseDown command presses the left mouse button without letting go
Code Example
MouseDown();
MouseUp
The MouseUp command lets go of the left mouse button
Code Example
MouseUp();
KeyDown
The KeyDown command holds down a key
Parameter | Description |
KeyCode | See available keycode list |
Code Example
KeyDown(KeyCode.SHIFT);
KeyUp(KeyCode.SHIFT);
KeyUp
The KeyUp command lets go of a key
Parameter | Description |
KeyCode | See available keycode list |
Code Example
KeyDown(KeyCode.CTRL);
KeyUp(KeyCode.CTRL);
KeyCodes
Available KeyCodes
/// Control-break processing
CANCEL = 0x03,
BREAK = CANCEL,
/// BACKSPACE key
BACK = 0x08,
BACKSPACE = BACK,
/// TAB key
TAB = 0x09,
/// CLEAR key
CLEAR = 0x0C,
/// ENTER key
RETURN = 0x0D,
ENTER = RETURN,
/// SHIFT key
SHIFT = 0x10,
/// CTRL key
CONTROL = 0x11,
CTRL = CONTROL,
/// ALT key
ALT = 0x12,
/// PAUSE key
PAUSE = 0x13,
/// CAPS LOCK key
CAPITAL = 0x14,
CAPSLOCK = CAPITAL,
/// ESC key
ESCAPE = 0x1B,
ESC = ESCAPE,
/// SPACEBAR
SPACE = 0x20,
/// PAGE UP key
PRIOR = 0x21,
PAGEUP = PRIOR,
/// PAGE DOWN key
NEXT = 0x22,
PAGEDOWN = NEXT,
/// END key
END = 0x23,
/// HOME key
HOME = 0x24,
/// LEFT ARROW key
LEFT = 0x25,
/// UP ARROW key
UP = 0x26,
/// RIGHT ARROW key
RIGHT = 0x27,
/// DOWN ARROW key
DOWN = 0x28,
/// PRINT SCREEN key
SNAPSHOT = 0x2C,
PRINTSCREEN = SNAPSHOT,
/// INS key
INSERT = 0x2D,
INS = INSERT,
/// DEL key
DELETE = 0x2E,
DEL = DELETE,
/// 0 key
KEY_0 = 0x30,
/// 1 key
KEY_1 = 0x31,
/// 2 key
KEY_2 = 0x32,
/// 3 key
KEY_3 = 0x33,
/// 4 key
KEY_4 = 0x34,
/// 5 key
KEY_5 = 0x35,
/// 6 key
KEY_6 = 0x36,
/// 7 key
KEY_7 = 0x37,
/// 8 key
KEY_8 = 0x38,
/// 9 key
KEY_9 = 0x39,
/// A key
KEY_A = 0x41,
/// B key
KEY_B = 0x42,
/// C key
KEY_C = 0x43,
/// D key
KEY_D = 0x44,
/// E key
KEY_E = 0x45,
/// F key
KEY_F = 0x46,
/// G key
KEY_G = 0x47,
/// H key
KEY_H = 0x48,
/// I key
KEY_I = 0x49,
/// J key
KEY_J = 0x4A,
/// K key
KEY_K = 0x4B,
/// L key
KEY_L = 0x4C,
/// M key
KEY_M = 0x4D,
/// N key
KEY_N = 0x4E,
/// O key
KEY_O = 0x4F,
/// P key
KEY_P = 0x50,
/// Q key
KEY_Q = 0x51,
/// R key
KEY_R = 0x52,
/// S key
KEY_S = 0x53,
/// T key
KEY_T = 0x54,
/// U key
KEY_U = 0x55,
/// V key
KEY_V = 0x56,
/// W key
KEY_W = 0x57,
/// X key
KEY_X = 0x58,
/// Y key
KEY_Y = 0x59,
/// Z key
KEY_Z = 0x5A,
/// Left Windows key (Microsoft Natural keyboard)
LWIN = 0x5B,
/// Right Windows key (Natural keyboard)
RWIN = 0x5C,
/// Applications key (Natural keyboard)
APPS = 0x5D,
MENU = APPS,
/// Numeric keypad 0 key
NUMPAD0 = 0x60,
/// Numeric keypad 1 key
NUMPAD1 = 0x61,
/// Numeric keypad 2 key
NUMPAD2 = 0x62,
/// Numeric keypad 3 key
NUMPAD3 = 0x63,
/// Numeric keypad 4 key
NUMPAD4 = 0x64,
/// Numeric keypad 5 key
NUMPAD5 = 0x65,
/// Numeric keypad 6 key
NUMPAD6 = 0x66,
/// Numeric keypad 7 key
NUMPAD7 = 0x67,
/// Numeric keypad 8 key
NUMPAD8 = 0x68,
/// Numeric keypad 9 key
NUMPAD9 = 0x69,
/// Multiply key
MULTIPLY = 0x6A,
NUMPAD_MULTIPLY = MULTIPLY,
/// Add key
ADD = 0x6B,
PLUS = ADD,
NUMPAD_ADD = ADD,
/// Subtract key
SUBTRACT = 0x6D,
MINUS = SUBTRACT,
NUMPAD_SUBTRACT = SUBTRACT,
/// Decimal key
DECIMAL = 0x6E,
NUMPAD_DECIMAL = DECIMAL,
/// Divide key
DIVIDE = 0x6F,
NUMPAD_DIVIDE = DIVIDE,
/// F1 key
F1 = 0x70,
/// F2 key
F2 = 0x71,
/// F3 key
F3 = 0x72,
/// F4 key
F4 = 0x73,
/// F5 key
F5 = 0x74,
/// F6 key
F6 = 0x75,
/// F7 key
F7 = 0x76,
/// F8 key
F8 = 0x77,
/// F9 key
F9 = 0x78,
/// F10 key
F10 = 0x79,
/// F11 key
F11 = 0x7A,
/// F12 key
F12 = 0x7B,
/// NUM LOCK key
NUMLOCK = 0x90,
/// SCROLL LOCK key
SCROLL = 0x91,
SCROLL_LOCK = SCROLL,
/// Left SHIFT key
LSHIFT = 0xA0,
/// Right SHIFT key
RSHIFT = 0xA1,
/// Left CONTROL key
LCONTROL = 0xA2,
LCTRL = LCONTROL,
/// Right CONTROL key
RCONTROL = 0xA3,
RCTRL = RCONTROL,
/// Left MENU key
LMENU = 0xA4,
LALT = LMENU,
/// Right MENU key
RMENU = 0xA5,
RALT = RMENU,
/// Windows 2000/XP: Volume Mute key
VOLUME_MUTE = 0xAD,
/// Windows 2000/XP: Volume Down key
VOLUME_DOWN = 0xAE,
/// Windows 2000/XP: Volume Up key
VOLUME_UP = 0xAF,
File and Registry functions
File and registry functions provide the capability to manage file operations and interact with the Windows registry in your automation scripts. Use CopyFile and CopyFolder to move files or directories, while FileExists and DirectoryExists verify whether the items were successfully copied. Commands such as RemoveFile and RemoveFolder facilitate cleanup of files and folders as needed. For handling compressed data, UnzipFile extracts contents from ZIP archives. Registry interactions are managed through RegImport, which imports registry settings from a specified file. These functions ensure efficient file management and registry operations.
CopyFile
The CopyFile command will copy a file from source to destination, overwriting the destination path.
Syntax
CopyFile(string sourcepath, string destinationPath, bool continueOnError, bool overwrite);
Parameter | Type | Default Value | Description |
sourcepath | string | copy file source path | |
destinationPath | string |
copy file destination path |
|
continueOnError | boolean | false |
Continue if error occurs |
overwrite | boolean | true |
overwrite target file if it exists |
Code Example
CopyFile(sourcePath:"C:\\somefile.txt",destinationPath:"D:\\somefile.txt",continueOnError:false,overwrite:true)
CopyFile - download existing example files
With update 4.1 it's now possible to download known files from the appliance. This is part of the existing CopyFile command. These files can be found on the appliance under "/loginVSI/content/scriptcontent/" when using WINSCP to connect to the appliance.
Syntax
CopyFile(KnownFiles.FileType, string destinationPath, bool continueOnError, bool overwrite);
Parameter | Type | Default Value | Description |
KnownFiles. | filetype |
KnownFiles.PdfFile
|
|
destinationPath | string |
copy file destination path |
|
continueOnError | boolean | false |
Continue if error occurs |
overwrite | boolean | true |
overwrite target file if it exists |
Code Example
CopyFile(KnownFiles.PdfFile, "C:\\Temp\\loginvsi.pdf",continueOnError:false,overwrite:true);
CopyFolder
The CopyFolder command will copy a folder from source to destination, overwriting the destination path.
Syntax
CopyFolder(string sourcepath, string destinationPath);
Parameter | Type | Default Value | Description |
sourcepath | string | copy folder source path | |
destinathPath | string | copy folder destination path |
Code Example
CopyFolder(@"c:\testfolder", @"c:\temp\testfolder");
CopyFolder(string sourcepath, string destinationPath);
FileExists
Check if a file exists, can be used as a verification to check if the file was successfully copied
Syntax
FileExists(string path);
Parameter | Type | Default Value | Description |
path | string | path of the file to verify |
Code Example
FileExists("C:\\Temp\\loginvsi.pdf");
RemoveFile
The RemoveFile command will remove/delete the specified file.
Syntax
RemoveFile(string path);
Parameter | Type | Default Value | Description |
path | string | path of the file to delete |
Code Example
# literal string path
RemoveFile(path: "c:\\testfolder\\some file.txt");
# verbatim string path
RemoveFile(@"c:\testfolder\some file.txt");
RemoveFolder
The RemoveFolder command will remove/delete the specified folder.
Syntax
RemoveFolder(string path);
Parameter | Type | Default Value | Description |
path | string | path of the folder to remove |
Code Example
# literal string path
RemoveFolder(path: "c:\\temp\\testfolder");
# verbatim string path
RemoveFolder(@"c:\temp\testfolder");
DirectoryExists
The DirectoryExists function checks if a specified folder exists. Can be used after you created a folder or if you wish to verify if the folder exists before executing an action
Syntax
DirectoryExists(string path);
Parameter | Type | Default Value | Description |
pathOfDirectory | string | path of the directory to verify |
Code Example
DirectoryExists("C:\\Temp");
UnzipFile
The DirectoryExists function checks if a specified folder exists. Can be used after you created a folder or if you wish to verify if the folder exists before executing an action
Syntax
UnzipFile(string SourcePath, destinationFolder, continueOnError, overWrite);
Parameter | Type | Default Value | Description |
sourcePath | string | path of the .zip file | |
destinationFolder | string | path of the folder to unzip the contents into | |
continueOnError | boolean | false | continue if error ocures |
overWrite | boolean | true | overwrite if file(s) exist |
UnzipFile(sourcePath:"C:\\Temp\\loginvsi.zip", destinationFolder:"C:\\temp\\loginvsiwebsite",continueOnError:false,overWrite:false);
RegImport
The RegImport command will import a registry file to the system registry.
Syntax
RegImport(string registryFile);
Parameter | Type | Default Value | Description |
registryFile | string | path of the registry file to import |
Code Example
# literal string path
RegImport(registryFile: "C:\\temp\\regfile.reg");
# verbatim string path
RegImport(@"C:\temp\regfile.reg");
Browser functions
Browser functions provide the capability to control web browsers in your application scripts. Use StopBrowser to close a previously opened browser. The Navigate function directs the browser to a specified URL and tracks the time it takes to load the page, which is useful for performance monitoring. FindWebComponentBySelector and FindAllWebComponentsBySelector allow you to locate and interact with web elements using CSS selectors, enabling actions such as clicking or typing directly into the identified components. These functions streamline browser automation, allowing you to script web interactions and measure performance within your application workflows.
StartBrowser
The StartBrowser command allows you to start a browser within an application script. Right now we only support Chrome80 and Edge42/44.
Syntax
StartBrowser(useInPrivateBrowsing, expectedURL, timeout, continueOnError);
Parameter | Type | Default Value | Description |
useInPrivateBrowsing | boolean | false | Define if browser starts in private mode |
expectedURL | string | defines the URL that you want to wait for | |
timeout | int | 60 | waits for # seconds before timing out if not found |
continueOnError | boolean | false | continues process if error occurs |
Code Example
StartBrowser(useInPrivateBrowsing:false,expectedUrl:"https://www.loginvsi.com",timeout:30,continueOnError:true);
StopBrowser
The StopBrowser command allows you to stop a browser within an application script.
Syntax / Code Example
StopBrowser();
Navigate
The navigate command will tell the open browser to browse to a specific URL. It automatically times the time it takes to browse the page.
Syntax
Navigate(string url, string timerName);
Parameter | Type | Default Value | Description |
Url | string | url to browse too | |
timerName | string | name of the timer |
Navigate(url: "https://loginvsi.com", timerName: "Website_LoginVSI");
FindWebComponentBySelector
The FindWebComponentBySelector finds a web element based on the given CSS selector. You can attach existing control actions. For more details, see Control Actions. You can also move your mouse to the component or search your component by text.
Note: Make the search field as small as possible to eliminate long searches.
Syntax
FindWebComponentBySelector(string selector, int timeout, bool continueOnError);
Parameter | Type | Default Value | Description |
selector | string | CSS Selector on page | |
timeout | int | 30 | timeout in seconds |
continueOnError | boolean | false | continue if error occurs |
Code Example
FindWebComponentBySelector(selector:"",timeout:30,continueOnError:false);
// It's also possible to type to the web element via
FindWebComponentBySelector(selector:"",timeout:30,continueOnError:false).Type("Example text");
// You can also send a Click to the found web element
FindWebComponentBySelector(selector:"",timeout:30,continueOnError:false).Click();
Browser.FindWebComponentBySelector("button[id='logonbutton']",timeout:30,continueOnError:false).Click();
FindAllWebComponentsBySelector
Sometimes the CSS selector appears multiple times within the webpage, which makes it hard to find the one you are looking for. To list the selectors you can use this command. The result can be used by FindWebComponentBySelector.
You can also move your mouse to the component. For more information, see Control Actions.
Syntax
FindAllWebComponentsBySelector(string selector, int timeout);
Parameter | Type | Default Value | Description |
selector | string | selector object name | |
timeOut | string | 30 | timeout value |
Code Example
var components = FindAllWebComponentsBySelector(selector:"A", timeout:30);
Native automation scripting
Native automation scripting enhances the capabilities of scripting within the Virtual Appliance by providing deeper control over Windows applications through native OS elements. The NativeWindowHandle and FromNativeWindowHandle functions enable you to identify and work directly with windows using their native OS handles, allowing for precise targeting. SwitchTopMostWindow ensures that the desired window remains on top, preventing pop-ups from interrupting automated tasks. NativeAutomationElement offers direct access to UIAutomation features, providing robust control over UI elements when default methods, such as typing, are insufficient. These functions significantly enhance your ability to script and automate complex interactions with Windows applications.
Please note that using these functions requires you to include the following line at the top of your script:
using Interop.UIAutomationClient;
NativeWindowHandle
Returns the unique identifier of the window as it is known to the Windows OS. This solves the issue where we cannot uniquely identify any given window.
Syntax
IntPtr NativeWindowHandle;
Code Example
FindWindow(title:"*Untitled*", timeout: 5).NativeWindowHandle;
FromNativeWindowHandle
Constructs a scripting window object from a native window handle. This allows us to work with a window that was found by its handle using native technologies like win32 calls.
Syntax
IWindow FromNativeWindowHandle(IntPtr handle);
Code Example
var myNativeWindow = Process.GetProcessesByName("notepad")[0].MainWindowHandle;
var myLEWindow = FromNativeWindowHandle(myNativeWindow);
NativeAutomationElement
This provides access to the underlying automation (UIAutomation) library the Login Enterprise Engine uses. It allows us to use low-level automation actions like manipulating checkboxes directly or setting the value of a text edit control in a more resilient way if typing doesn't work properly.
In-depth information about the UIAutomationClient functions is beyond the scope of this article. For a code example, see the file attached under Additional resources.
Syntax
IUIAutomationElement NativeAutomationElement;
Code Example
MainWindow.FindControl(classname:"*Document*").NativeAutomationElement;
Control Flow functions
Control flow functions provide options for implementing conditional logic and iteration in your scripts. The If Else statement allows you to execute code based on whether a condition is true or false. The Try Catch construct enables error handling, ensuring scripts continue running smoothly even if an element is not found. Loops like While and ForEach let you repeat actions until a condition is met or iterate over a collection of values. These control flow functions are essential for building dynamic and resilient scripts, helping you automate workflows that adapt to changing conditions and handle errors gracefully.
Note: These functions represent standard programming concepts that are common across many languages, including C#. While they may be familiar to experienced programmers, we recognize that many of our users may not have a programming background. This section aims to clarify these concepts for those who may be new to scripting, particularly as our workload scripting in C# supports these features, facilitating more advanced and conditional scenarios.
If Else versus Try Catch
Function name: If Else statement
Description: The If...Else statement allows you to create conditional logic in your scripts. If the condition is true, the code within the If block executes. If the condition is false, the code within the Else block executes. Note that the Else statement is not mandatory.
Example:
var Condition = MainWindow.FindControl(title:"Condition");
if (Condition != null)
{
Type("Condition is true");
}
else
{
Type("Condition is not true");
}
Challenges:
Finding a control may throw an exception if the control is not found. If "Continue on Error" is not enabled, this will terminate the workflow.
Solution
Reword the script using a Try...Catch statement. This approach can eliminate inconsistent pop-ups and allow the script to continue running even if a control is not found.
Example:
Try{
var Condition = MainWindow.FindControl(title:"Condition");
Condition.Click();
}
catch{
Log("Was unable to find conditional window");
};
While
Function name: While
Description: The While statement executes a block of code in a loop as long as the specified condition evaluates to true. The condition is evaluated before each iteration of the loop.
Example:
In the following example, we specify an integer variable that equals zero. While the number is less than 10, we log the number to the console and add +1 to it until it evaluates false.
int number = 0;
while(number < 10)
{
Log(number);
number++;
}
ForEach
Function name: foreach
Description: The ForEach statement iterates through each item in an array of values.
Example:
In the following example, we iterate through 3 sample values.
string[] example = {"example 1","example 2","example 3"};
foreach (string value in example)
{
Log(value);
}
Additional Uses
When working with a browser application, collecting all web selectors can be beneficial. You can then use a ForEach loop to find a specific condition or to identify a particular selector from an array of many.