CapeSoft.Com
Clarion Accessories
OddJob
Documentation
Class Reference Documentation
CapeSoft Logo

CapeSoft OddJob Class Reference
Documentation

Download Latest Version
Installed Version Latest Version

Introduction

OddJob provides the following classes:

JobObject

The main OddJob class, this provides the core functionality off OddJob, such as:

PipeServer and PipeClient

The PipeServer and PipeClient classes wrap up the Windows named pipe API. While we recommend NetTalk for inter process communication (IPC), and the OddJob examples use NetTalk as the primary method of IPC, OddJob provides the pipe classes for integration with applications that use named pipes, or application that you may have no control over, and no access to the source etc.

Api Base Methods and Properties

The following methods and properties are available in all the OddJob classes, including JobObject, PipeServer and PipeClient.

General Method Reference

Debug Conditionally output to the Windows debug output depending on whether the .debug property is set to true or not.
Trace Unconditionally output a string to the Windows debug output.
ErrorTrap Callback method used to trap errors.
FormatMessage Converts an API error code into the associated error message.
ToCString Creates a new cstring from the passed string.
FreeCstring Safely frees a cstring reference variable.
Ulong64ToReal Converts an unsigned 64 bit integer to a Real
GetReg Returns the value of the specified registry key.
PutReg Sets the value of the specified registry key.
General Property Reference
displayErrors Sets whether or not the class displays errors using the Message function.
logErrors Sets whether or not errors are sent to the Windows Debug Output
errorCode The last error code
errorMessage The last error message
debug Determines whether or not debug output is produced
debugPrefix The prefix used for debug output

Base Methods

Debug

Debug Procedure(string msg)

Description

Conditionally send a string to the Windows debug output. The string will only be sent to the output if the .debug property of the class is set to True (1). The output string will automatically be prefixed with string specified by the .debugPrefix property of the class. This allows easy filtering of debug output.

Notes:

The Windows Debug Output can be viewed using the free DebugView tool provided by Microsoft ( http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx)

Providing an option to set the .debug property at runtime is recommended, as this allows creation of debug output, but also allows it to be disabled. The Windows debug output is shared between all applications on the system, so applications should not write to it as if it were a private debug output.

Parameters
Parameter Description
msg A string containing the information to be sent to the debug output. The string will be prefixed with the contents of the .debugPrefix property. By default this is set to a string indicating which class output the error.

Return Value

None

Example
Example
st     JobObject
 
code
    st.debug = glo:EnableDebug   
! Example of a global setting to enable or disable debug output
    st.Debug('
Debug output enabled')   ! Will only be displayed if debug output is enabled.

Trace

Trace Procedure (string msg)

Description

Identical to the Debug method, except that the output is not conditional (the string is always sent to the debug output, regardless of whether or not the .debug property of the class is set to True (1) or not).

See Debug for more information.

ErrorTrap

ErrorTrap Procedure (string msg, long err)
ErrorTrap Procedure ()

Description

Callback method provided for trapping and handling of error. The ErrorTrap method is called when an error occurs in one of the methods of the class, and provides additional information pertaining to the error. For API errors the ErrorTrap method can be called without parameters, which causes it to retrieve the API error code, and call FormatMessage() to retrieve the Windows error message associated with the error code.

If the .debug property of the class is set to True (1), then error messages are sent to the Windows debug output. See Debug for more information of viewing the output. If the .displayErrors property is set to True (1), then error messages are displayed using the Message() function.

Parameters
Parameter Description
msg The error message.
err The error code. If this is a Windows API error code, then the FormatMessage API is called to convert this to the associated error message.
Return Value

None

FormatMessage

FormatMessage Procedure (long errorCode), string

Description

Returns the associated error message when passed a Windows API error code. This is called by the ErrorTrap method to convert API error code to their associated messages.

Parameters
Parameter Description
errorCode The Windows API error code.
Return Value

none

ToCString

ToCString Procedure (*string s)

Description

Creates a new cstring that contains the contents of the passed string. The new cstring is returned as a reference.

NOTE:

The Cstring is created using the NEW keyword. It is the responsibility of the programmer to DISPOSE this cstring. The FreeCstring() method can also be used to safely dispose the string reference.

Parameters
Parameter Description
s The contents of this string will be stored in the returned cstring. The returned cstring is the same length as the contents of this string (the clipped length), plus one byte for the null terminator.
Return Values

Returns a reference to the newly created cstring.

Example
Example
cs     &cstring
s      string(255)
st     ApiBase
 
code
    s = '
Some String Value'
    cs &= st.ToCstring(s)

   
! use cstring here

    st.FreeCstring(cs)  ! Safely free the cstring reference
See Also

StringTheory, ToCString

FreeCString

FreeCString Procedure (*cstring c)

Description

Safely frees the passed cstring reference, if it is not already null.

Parameters
Parameter Description
c A cstring reference variable.
Return Value

None

Ulong64ToReal

Ulong64ToReal Procedure (*joLARGE_INTEGER pli)

Description

Converts the passed 64 bit integer to a Real value for use and display in Clarion applications. The joLARGE_INTEGER type is typed group provided to handle 64bit integers returned by API functions.

Parameters
Parameter Description
lpi A joLARGE_INTEGER group that contains a 64bit integer value to be converted.
Return Value

Returns a Real that contains the value of the passed 64bit integer.

GetReg

GetReg Procedure (long hKey, string sSubKeyPath, string sValue), ?

Description

Retrieves the specified registry key value and returns the stored value it exists, or False (0) if it does not. If the key does not exist, the ErrorTrap method is called.

Parameters
Parameter Description
hKey The root registry hive to retrieve the key value from. Can be one of the following values:

jo:HKEY_CLASSES_ROOT
jo:HKEY_CURRENT_USER
jo:HKEY_LOCAL_MACHINE
jo:HKEY_USERS
jo:HKEY_PERFORMANCE_DATA
jo:HKEY_PERFORMANCE_TEXT
jo:HKEY_PERFORMANCE_NLSTEXT
jo:HKEY_CURRENT_CONFIG
jo:HKEY_DYN_DATA
sSubKeyPath The path of the key to retrieve the value for.
sValue The name of the value to retrieve.
Return Value

Returns the value stored in the specified key. The return type is based on type of the value stored, and is either an integer (ulong)  for numeric values, or a string for strings and binary data.

PutReg

PutReg Procedure (long hKey, string sSubKeyPath, string sValueName, string sValue, long lType=1), long

Description

Sets the specified registry key to the passed value.

Parameters
Parameter Description
hKey The root registry hive. Can be one of the following values:

jo:HKEY_CLASSES_ROOT
jo:HKEY_CURRENT_USER
jo:HKEY_LOCAL_MACHINE
jo:HKEY_USERS
jo:HKEY_PERFORMANCE_DATA
jo:HKEY_PERFORMANCE_TEXT
jo:HKEY_PERFORMANCE_NLSTEXT
jo:HKEY_CURRENT_CONFIG
jo:HKEY_DYN_DATA
sSubKeyPath The path of the key to set the value for.
sValueName The name of the value to set.
sValue The actual value to set the entry to
lType The value type to set. Can be one of the following:
Equate Value Definition
jo:REG_NONE 0 No value type
jo:REG_SZ 1 Unicode nul terminated string
jo:REG_EXPAND_SZ 2 Unicode nul terminated string (with environment variable references)
jo:REG_BINARY 3 Free form binary
jo:REG_DWORD 4  32-bit number
jo:REG_DWORD_LITTLE_ENDIAN 4 32-bit number (same as REG_DWORD)
jo:REG_DWORD_BIG_ENDIAN 5 32-bit number
jo:REG_LINK 6 Symbolic Link (unicode)
jo:REG_MULTI_SZ 7 Multiple Unicode strings
jo:REG_RESOURCE_LIST 8 Resource list in the resource map
jo:REG_FULL_RESOURCE_DESCRIPTOR 9
jo:REG_RESOURCE_REQUIREMENTS_LIST 10
jo:REG_QWORD 11  64-bit number
jo:REG_QWORD_LITTLE_ENDIAN 11  64-bit number (same as REG_QWORD)
Return Value

Returns True (1) if successful, and False (0) for failure. The ErrorTrap method will be called with additional error information in the event of the method failing.

ApiBase Properties

displayErrors long Display errors to the user. Setting this to a non-zero value will cause the ErrorTrap() method to display any errors using the Message() function.
logErrors long Log errors to the system debug log. If this is non-zero, then errors are logged to the Windows debug log. See Debug for more information.
errorCode long The last error code.
errorMsg string(512) The last error message.
debug long Set to true to enable debug logging. If this is enabled, then calls to Debug() will output the passed string to the Windows debug output.
debugPrefix cstring(12) A prefix for debug output. This is set by each of the classes to a unique value to make reading and filtering the debug output easier.

JobObject

Using the JobObject class

JobObject Method Reference

AddProcess Add an existing (running) process to the Job.
CloseAll Close all processes associated with the current job.
CreateJob Create a new Job. Called automatically by the Init method.
EndProcess Terminate a running process.
ExecuteFile Run a file using the default application associated with it, or start a program
GetCurrentUserToken Gets the current User's token (which stores the users security attributes).
GetInformation Get information about the Job.
GetProcessJobs Fills the passed queue with all processes related to the current Job.
GetSessions Get a list of sessions on the current machine (log in users and system sessions).
Init Initialize the object, load the DLLs required, and optionally create a new Job Object.
Kill Terminate the Job, release all handles and free all memory allocated.
KillProcess Kill one or more processes with the specified name.
LoadLibs Load the libraries (DLLs) required for the functionality provided.
LocateProcedure Locate a procedure in a dynamically loaded library.
LogonUser Retrieves a the token representing the specified user.
RunAsUser Run a process as the currently logged in user.
SetInformation Set information (such as limits) for the current Job.
CreateProcess Start a process (processes are started as a part of the current Job by default).
StoreProcessInfo Store information related to a specific process. Called internally to update the Processes queue.
AddEnv Add an environment variable to the stored Environment block.
ClearEnvironment Clear the stored environment block
ListProcesses List all processes running on the system and stores them in a queue (much like the Windows task manager does).
HandleFromPID Returns the Process Handle when passed the Process ID (PID)
GetProcessPath Returns the full path to the executable for a process
DeviceNameForDrive Returns the full device name when passed the drive identifier (for example 'C:'  or 'D:')
GetDrives Populates a queue with a list of all drives and their full NT Device Names.

JobObject Property Reference

init Set to 1 when the Init method is called successfully. If init is 0 all other functions will return immediately.
hJob Handle to the current API JobObject
hProcess Pseudo Handle to the process that create the job (and hence is the first process in the job by default)
name Name for the job
env String that stores the environment for passing to a new process. Contains null separate environment setting and is terminated by a pair of nulls
envLen The current environment length
securityAttributes The Security Attributes for the started Job
basicAccounting Basic account information for the job (memory usage, processes etc.)
basicIoAndAccounting Accounting information and IO (disk read/writes etc.)
basicLimits Job limits, including process and time limits, memory limitations, processor affinity, priority etc.
basicProcessIdList List of processes in the job
basicUIRestrictions Restricts creation of desktops, changing display settings, shutting down windows, clipboard access etc.
extendedLimits Memory limits (per process and job, peek memory usage etc.)
securityLimits Security limits (prevent admin token access etc.)
completionPort Associate a completion port with a job
endTimeInfo The action that the system will perform when the end-of-job time limit has been exceeded
Processes A queue of processes started in the current Job

Using the JobObject Class

This document covers the usage of the JobObject class and is incomplete in this release. Please refer to the example shipped with JobObject.

JobObject Method Reference

AddProcess

AddProcess Procedure (unsigned hProcess), long

Description

Add a current running process to the current job.

Parameters
Parameter Description
unsigned hProcess A handle to the process to add to the current job. The process must not already be assigned to a job.
Returns

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. The ErrorTrap() method is called with error information.

See Also

EndProcess

BindToCPU

BindToCPUProcedure (long pMask=1), long

Description

Add a current running process to the current job.

Parameters
Parameter Description
pMask  A bit mask of the CPU's to bind the program to. Typically if this is used it binds the program to a single CPU, however a program can be bound to a subset of CPU's if you wish.
If this value is 0 then the program will be bound to a single CPU, at random, from the CPU's available.
If the computer only has a single CPU then this method has no effect.
Returns

0 - error, failed to set the affinity
1 - success; affinity set.
2 - single CPU machine, nothing needs to be set
 

CloseAll

CloseAll Function (), long, proc

Description

Terminates all processes currently associated with the job.

Parameters

None

Returns

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. The ErrorTrap() method is called with error information.

Notes

It is not possible for any of the processes associated with the job to postpone or handle the termination. It is as if EndProcess were called for each process associated with the job.

CreateJob

CreateJob Function (string jobName), long

Description

Creates a new Job object, or opens an existing one, if a Job with the same name has already been created. JobObject calls this automatically when the Init method is called.

Parameters
Parameter Description
string JobName The name of the job to create, or the name of an existing job to open.
Returns

True for success, false for failure. In the event of an error calling the ErrorTrap() method is called with error information.

Remarks

When a job is created, its accounting information is initialized to zero, all limits are inactive, and there are no associated processes. To assign a process to a job object, use the AddProcess method. To set limits for a job, use the SetInformation method. To query accounting information, use the GetInformation method.

All processes associated with a job must run in the same session. A job is associated with the session of the first process to be assigned to the job. Any new processes created by a process within the job will automatically be a part of the job. In the case of JobObject, if this is called by the Init method, then the default is to add the current process as the first process that is a member of the job. See Init for details.

EndProcess

EndProcess Procedure (long procNum), long

Description

Terminates the specific process that is associated with the job.

Parameters
Parameter Description
long procNum The position in the Processes queue of the process to terminate.
Returns

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. The ErrorTrap() method is called with error information.

Remarks

To terminate a process that is not associate with a job call the joTerminateProcess function directly. This requires a handle to the process that can be retrieve by calling joOpenProcess with the process ID of the process to acquire a handle for. The ListProcesses method can be used to list all running processes and retrieve the process IDs

ExecuteFile

ExecuteFile Procedure (string fileName), long

Description

Opens the passed file, which can be a document or an application, or a directory. This is effectively the same as doubling clicking on a File or Folder in Windows Explorer.

Parameters
Parameter Description
string fileName The name of the file to open.
Returns

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. The ErrorTrap() method is called with error information.

Remarks

This is a simple method used to open a file independently using ShellExecute.

GetCurrentUserToken

GetCurrentUserToken Function () unsigned

Description

Retrieve a handle to the token that identifies the current user. This is used primarily to start processes as the currently logged in user.

Parameters

None

Returns

If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. The ErrorTrap() method is called with error information.

GetInformation

GetInformation Function (long infoClass), long

Description

Get information about the Job. The retrieved information is stored in the object properties

Parameters
Parameter Description
long infoClass The information class for the limits to be queried. This parameter can be one of the following values:
Value Meaning
JobObjectBasicAccountingInformation
1
Retrieves basic accounting information and stores it in the basicAccounting property of the class.
JobObjectBasicAndIoAccountingInformation
8
Retrieves basic accounting information and IO information and stores it in the basicIoAndAccounting property of the class.
JobObjectBasicLimitInformation
2
Retrieves basic limits and stores them in the basicLimits property.
JobObjectBasicProcessIdList
3
Retrieves a list of process IDs associated with the Job (running and terminated) and stores them in the basicProcessIdList property.
JobObjectBasicUIRestrictions
4
Retrieves basic UI restriction information and stores it in the basicUIRestrictions property of the class.
JobObjectExtendedLimitInformation
9
Retrieves extended limit information and stores it in the extendedLimits property of the class.
JobObjectSecurityLimitInformation
5
Retrieves security limits information and stores it in the securityLimits property of the class.
Returns

If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. The ErrorTrap() method is called with error information.

Remarks

You can use GetInformation to obtain the current limits, modify them, then use the SetInformation function to set new limits.

GetSessions

GetSessions Procedure (<*joSessionInfo Sessions>), ulong, virtual

Description

Returns a list of session (all logged in users on the system, including system sessions).

Parameters
Parameter Description
*joSessionInfo Sessions A joSessionsInfo structure which stores the list of returned sessions.
Returns

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. The ErrorTrap() method is called with error information.

Init

Init Procedure (<string jobName>, long associateProcess = 0), long, proc

Description

Initializes the object and optionally creates a new Job. If a new Job is created then by default the current process is assigned as the first process in the Job. This method must be called before the object can be used, regardless of whether or not any of the Job related functionality is required, as it handles the loading of required libraries and initialization of the object.

Parameters
Parameter Description
<string jobName> If this is passed then a Job is created, otherwise the object is initialized, but no job is created. By default the current process is not assigned to the newly created job, unless the associateProcess parameter is set to 1 (true).
long associateProcess= 0
If this is set to a non zero value, the process that creates the job is also the first process assigned to the Job. This is limited by the security permissions for the current user.

Important: If the current process becomes the first process in the Job, and will be affected by any calls to the methods that interact with the job. For example calling CloseAll or calling the Kill method will end this process, along with all other associated with the job
Returns

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. The ErrorTrap() method is called with error information.

Remarks

The CreateJob method can be called to create a Job if jobName is not passed (and hence Init does not create a job). AddProcess can be called to add this, or any other process, to a created Job.

Kill

Kill Procedure ()

Description

Closes all processes in the Job, releases memory, frees all handles and loaded libraries and cleans up the object.

Parameters

None

Returns

None

KillProcess

KillProcess Function (string processName, bool killAll=true, bool exactMatch=true)

Description

Kill (terminate) one or more instances of a process when passed the process name. The process is force terminated, the same as if it is killed using the Windows Task manager.

By default it requires the passed process name to be an exact match (including case). Setting exactMatch to false will perform a case insensitive substring match. This is only recommended if the entire process name is provided, such as: 'myprocess.exe'. Passing a substring such as 'win' is not recommended, as this will terminate ALL processes with that substring in the name (or the first instance if killAll is set to false), which can have unintended consequences.

Parameters
Parameter Description
processName The handle to the library to load to the function from.
killAll = true Optional parameter. If set to False only the first instance found will be terminated. By default set to True and all matching processes are terminated.
exactMatch = true Optional parameter. Defaults to True which does a cases sensitive search for processes that match the exact process name passed. If set to False this will perform a case insensitive substring match and all processes whose names contain the passed processName string will be matched. For example passing processName as 'win' with exactMatch set to False would match: wininit.exe, winlogon.exe, winmerge.exe, searchwin.exe etc. For this reason setting exactmatch to False is not recommended unless the passed processName is a substring is specified that has a very low likelihood of terminating processes that are not intended to be terminated.
Returns

None

Examples

See the KillProcess example in the examples directory.
Example
jo              Class(JobObject)
                end
processName     string(260)
killAll         bool(true)
exactMatch      bool(true)
  code
  ! Command line is as follows:
  !    killprocess.exe ProcessName.exe exact=0 all=0
  ! Both the "exact" and "all" are optional.
  ! exact=0: Use a case insensitive substring search to find process
  ! all=0: Only kill the first instance
 
  processName = Command('1')
 
  if processName
    if Command('exact') = '0'
        exactMatch = false
    end
    if Command('all') = '0'
        killAll = false
    end
 
    jo.KillProcess(clip(processName), killAll, exactMatch)
  end

  return

LoadLibs

LoadLibs Function (), long

Description

Internal function called by Init to load all required libraries (DLLs).

Parameters

None

Returns

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. The ErrorTrap() method is called with error information.

LocateProcedure

LocateProcedure Function (long hLib, string procName), long

Description


Internal method used to locate a procedure in a dynamically loaded library (DLL). Called by the Init method.

Parameters
Parameter Description
hLib The handle to the library to load to the function from.
procName The name of the function to locate.
Returns

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. The ErrorTrap() method is called with error information.

LogonUser

LogonUser Function (string userName, <string domain>, string password, *HANDLE phToken, ulong logonType=4, ulong logonProvider=0)

Description

Login the user.

Parameters
Parameter Description
userName The name of the user. This is the name of the user account to log on to. If you use the user principal name (UPN) format, user@DNS_domain_name, the domain parameter must be omitted.
domain Specifies the name of the domain or server whose account database contains the username account. If this parameter is omitted, the user name must be specified in UPN format. If this parameter is ".", the function validates the account by using only the local account database.
password Specifies the plaintext password for the user account specified by username.
phToken A pointer to a handle which will be set to the token handle is successful. You can use the returned handle in calls to the ImpersonateLoggedOnUser function.

In most cases, the returned handle is a primary token that you can use in calls to the RunAsUser function. However, if you specify the jo:LOGON32_LOGON_NETWORK flag, LogonUser returns an impersonation token that you cannot use in RunAsUser unless you user the DuplicateTokenEx API to convert it to a primary token.

When you no longer need this handle, close it by calling the CloseHandle method.
logonType The type of logon to perform, defaults to jo:LOGON32_LOGON_BATCH (4). May be one of the following:
Value Meaning
jo:LOGON32_LOGON_BATCH This logon type is intended for batch servers, where processes may be executing on behalf of a user without their direct intervention. This type is also for higher performance servers that process many plaintext authentication attempts at a time, such as mail or Web servers. The LogonUser function does not cache credentials for this logon type.
jo:LOGON32_LOGON_INTERACTIVE This logon type is intended for users who will be interactively using the computer, such as a user being logged on by a terminal server, remote shell, or similar process. This logon type has the additional expense of caching logon information for disconnected operations; therefore, it is inappropriate for some client/server applications, such as a mail server.
jo:LOGON32_LOGON_NETWORK This logon type is intended for high performance servers to authenticate plaintext passwords. The LogonUser function does not cache credentials for this logon type.
jo:LOGON32_LOGON_NETWORK_CLEARTEXT This logon type preserves the name and password in the authentication package, which allows the server to make connections to other network servers while impersonating the client. A server can accept plaintext credentials from a client, call LogonUser, verify that the user can access the system across the network, and still communicate with other servers.

Windows NT:  This value is not supported.
jo:LOGON32_LOGON_NEW_CREDENTIALS This logon type allows the caller to clone its current token and specify new credentials for outbound connections. The new logon session has the same local identifier but uses different credentials for other network connections.

This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider.

Windows NT:  This value is not supported.
jo:LOGON32_LOGON_SERVICE Indicates a service-type logon. The account provided must have the service privilege enabled.
jo:LOGON32_LOGON_UNLOCK This logon type is for GINA DLLs that log on users who will be interactively using the computer. This logon type can generate a unique audit record that shows when the workstation was unlocked.
longonProvider The logon provider, defaults to jo:LOGON32_PROVIDER_DEFAULT (0). May be one of the following values:
Value Meaning
LOGON32_PROVIDER_DEFAULT Use the standard logon provider for the system. The default security provider is negotiate, unless you pass NULL for the domain name and the user name is not in UPN format. In this case, the default provider is NTLM.

Windows 2000/NT: The default security provider is NTLM.
LOGON32_PROVIDER_WINNT50 Use the negotiate logon provider.

Windows NT: This value is not supported.
LOGON32_PROVIDER_WINNT40 Use the NTLM logon provider.
LOGON32_PROVIDER_WINNT35 Use the Windows NT 3.5 logon provider.
Returns

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. The ErrorTrap() method is called with error information.

Remarks



Examples
Example
 

RunAsUser

RunAsUser Function (string processPath, string arguments, bool breakAwayFromJob = True, bool dontStore=True, <HANDLE phToken>)

Description

Start a process as the currently logged in user. This can be used from an elevated process or a service to start a process as the currently logged in user.

Parameters
Parameter Description
processPath The name and path of the executable to run.
arguments Command line arguments to pass (can be an empty string).
breakAwayFromJob [optional] If a Job has been created, then this starts the process outside of the current Job
dontStore [optional] If set the process details won't be stored in the processes queue.
phToken [optional] Handle to a specific access token. If this is not specified, then the current user's token is used. Call LogonUser to get a specific user's token by authenticating using the user's name and password. Call GetSessions and GetToken under terminal server to get a token associated with a specific sessions (requires the relevant level of permission).
Returns

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. The ErrorTrap() method is called with error information.

Remarks

This method allows a new process to be started as the logged in user, and bypasses any UAC prompts. Used to start a process as the user from a service. Requires sufficient permission to get the relevant token (unless the token is passed), and hence will typically only work from a service running in the LocalSystem account.

Examples
Example
job.RunAsUser('someapp.exe', '')

SetInformation

SetInformation Function (long infoClass), long

Description

Sets limits for a job object based on the properties of the class. The infoClass parameter specifies which settings are to be updated.

Parameters
Parameter Description
long infoClass The class of information to be updated. Determines which properties of the class should be used to update the settings for the Job. Can be one of the following:
jo:JobObjectAssociateCompletionPortInformation
7
Uses the self.completionPort property.
jo:JobObjectBasicLimitInformation
2
Uses the self.basicLimits property.
jo:JobObjectBasicUIRestrictions
4
Uses the self.basicUIRestrictions property.
jo:JobObjectEndOfJobTimeInformation
6
Uses the self.endTimeInfo property.
jo:JobObjectExtendedLimitInformation
9
Uses the self.extendedLimits property.
Returns

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. The ErrorTrap() method is called with error information.

Remarks

You can use the SetInformation method to set several limits in a single call. If you want to establish the limits one at a time or change a subset of the limits, call the GetInformation method to obtain the current limits, modify these limits, and then call SetInformation.

You must set security limitations individually for each process associated with a job object, rather than setting them for the job object itself..

StoreProcessInfo

StoreProcessInfo Procedure (string app, string cmd, string env, string dir, *joPROCESS_INFORMATION pi, *joSTARTUPINFO si, HANDLE hRead = 0, HANDLE hWrite = 0), virtual

Description

Stores the information for a process in the Processes queue. This is called by the CreateProcess methods automatically as needed to populate the queue with started processes.

Parameters
Parameter Description
string app The name of the application that was started (and optionally the path). Can be empty if cmd contains the application name
string cmd The command line used, can be empty, or may contain the command line parameters, or may contain the full path, application name and any parameters passed (in which case app would be empty)
string env The environment block for the process.
string dir Starting directory
*joPROCESS_INFORMATION pi The API process information used in the process creation
*joSTARTUPINFO si The startup information returned by the process creation API
HANDLE hRead = 0 Optional handle to the standard output of the process for reading data from the process. Passed to WriteData.
HANDLE hWrite = 0 Optional handle to the standard input of the process for writing data to the process. Passed to ReadData.
Returns

None

Process Creation

The following methods allow for process creation and handling independent on whether or not a job is being used. The Init method of the JobObject class must still be called in order to use these method, however the JobName parameter does not need to be passed. This results in the required libraries being loaded, but no job is created (a job can be created at any time by calling CreateJob).

CreateProcess

CreateProcess Procedure (string pAppName, ushort pMode, byte pUseCMD=0, <string pPath>, <string pMessage>, <string pTitle>, |
<*long pExitCommand>, <*StringTheory strData>, long noRead = 0, long noStore = 0), long, proc

Description

Create a new process and optionally capture the Std output from that process. This method can be called without creating a Job. If a Job has been created then the new process is associated with the Job by default.

Also see below for two additional CreateProcess functions which provide simpler and alternative calls for CreateProcess.

Note: the process will use the self.env property of the class as the environment. If AddEnv has been called to create a custom environment block, the ClearEnvironment should be called to clear it in order to use the default environment for the process.

Parameters
Parameter Description
string pAppName The name and path of the application to run, can include command line parameters and options
ushort pMode Allows the initial window mode to be specified. Can be one of:
jo:SW_FORCEMINIMIZE

Windows 2000/XP: Minimizes a window, even if the thread that owns the window is not responding. This flag should only be used when minimizing windows from a different thread.
jo:SW_HIDE
Hides the window and activates another window.

jo:SW_MAXIMIZE
Maximizes the specified window.

jo:SW_MINIMIZE
Minimizes the specified window and activates the next top-level window in the Z order.

jo:SW_RESTORE
Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when restoring a minimized window.

jo:SW_SHOW
Activates the window and displays it in its current size and position.

jo:SW_SHOWDEFAULT
Sets the show state based on the SW_ value specified in the STARTUPINFO structure passed to the CreateProcess function by the program that started the application.

jo:SW_SHOWMAXIMIZED
Activates the window and displays it as a maximized window.

jo:SW_SHOWMINIMIZED
Activates the window and displays it as a minimized window.

jo:SW_SHOWMINNOACTIVE
Displays the window as a minimized window. This value is similar to SW_SHOWMINIMIZED, except the window is not activated.

jo:SW_SHOWNA
Displays the window in its current size and position. This value is similar to SW_SHOW, except the window is not activated.

jo:SW_SHOWNOACTIVATE
Displays a window in its most recent size and position. This value is similar to SW_SHOWNORMAL, except the window is not activated.

jo:SW_SHOWNORMAL
Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when displaying the window for the first time.
byte pUseCMD=0 Uses the cmd.exe to execute the passed file (for example if it is a batch file).
<string pPath> Optional specify the initial Path for the application (the directory that it should start in).
<string pMessage> Optional parameter allows a message window to be displayed while data is being read from the StdOut of the process. If pMessage and pTitle are omitted then no window will be displayed when reading data from the application.
<string pTitle> Optional parameter allows the title of the message window to be displayed while data is being read from the StdOut of the process. If pMessage and pTitle are omitted then no window will be displayed when reading data from the application.
<*long pExitCommand> Optional parameter. Stores the Exit value of the process.
<*StringTheory strData> An optional StringTheory object used for input and output. If this is passed with data then that data is written to the StdIn of the process. If a StringTheory object is passed with no data then nothing is written to the processes StdIn, however the process output will still be returned in the StringTheory object passed.
long noRead = 0 Optional parameter. If this is set to 1 then any data passed in the strData parameter will be written to the created process, however no output will be read from the process. This is useful when data only needs to be passed to the newly created process, which may not write anything back that needs to be read.
long noStore = 0 Optional parameter. If this is set to 1 then the process is called, and all handles are cleaned up once complete. No entry is added to the Processes queue. This is useful for process that will be called will terminate after the call. For example batch files, script processors, CGI application etc. Any process that will be called to perform a function and will exit on completion can be called with this parameter set to 1. If there is no job then no entries will be added to the queue, and this parameter has no affect (all processes are run without storing information relating to them).
Returns

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. The ErrorTrap() method is called with error information.

Remarks

This wrapper allows processes to be created, and also data passed to them using the environment block, the command line, and the standard input (StdIn) of the process. It also allows data returned to be captured. This functionality allows command line applications to be used, such as the PHP CGI interface, batch files, FTP or other client/server applications, compilers and so on, and not only allows data to be passed to them, but allows the output to be captured.

CreateProcess

CreateProcess Procedure (string pAppName, <*StringTheory pOutput>, long noRead = 0, long noStore = 0, long mode=0), long, proc, virtual

Description

A simpler wrapper for CreateProcess, where just the application name and optionally a StringTheory object is passed for data IO.

Parameters
Parameter Description
string pAppName The name of the application to run
<*StringTheory pOutput> An optional StringTheory object used for input and output. If this is passed with data then that data is written to the StdIn of the process. If a StringTheory object is passed with no data then nothing is written to the processes StdIn, however the process output will still be returned in the StringTheory object passed.
long noRead = 0 Optional parameter. If this is set to 1 then any data passed in the strData parameter will be written to the created process, however no output will be read from the process. This is useful when data only needs to be passed to the newly created process, which may not write anything back that needs to be read.
long noStore = 0 Optional parameter. If this is set to 1 then the process is called, and all handles are cleaned up once complete. No entry is added to the Processes queue. This is useful for process that will be called will terminate after the call. For example batch files, script processors, CGI application etc. Any process that will be called to perform a function and will exit on completion can be called with this parameter set to 1. If there is no job then no entries will be added to the queue, and this parameter has no affect (all processes are run without storing information relating to them).
long mode = 0 Allows the initial window mode to be specified. Defaults to SW_SHOW if not set. Can be one of:

jo:SW_FORCEMINIMIZE

Windows 2000/XP: Minimizes a window, even if the thread that owns the window is not responding. This flag should only be used when minimizing windows from a different thread.

jo:SW_HIDE
Hides the window and activates another window.

jo:SW_MAXIMIZE
Maximizes the specified window.

jo:SW_MINIMIZE
Minimizes the specified window and activates the next top-level window in the Z order.

jo:SW_RESTORE
Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when restoring a minimized window.

jo:SW_SHOW
Activates the window and displays it in its current size and position.

jo:SW_SHOWDEFAULT
Sets the show state based on the SW_ value specified in the STARTUPINFO structure passed to the CreateProcess function by the program that started the application.

jo:SW_SHOWMAXIMIZED
Activates the window and displays it as a maximized window.

jo:SW_SHOWMINIMIZED
Activates the window and displays it as a minimized window.

jo:SW_SHOWMINNOACTIVE
Displays the window as a minimized window. This value is similar to SW_SHOWMINIMIZED, except the window is not activated.

jo:SW_SHOWNA
Displays the window in its current size and position. This value is similar to SW_SHOW, except the window is not activated.

jo:SW_SHOWNOACTIVATE
Displays a window in its most recent size and position. This value is similar to SW_SHOWNORMAL, except the window is not activated.

jo:SW_SHOWNORMAL
Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when displaying the window for the first time.
Returns

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. The ErrorTrap() method is called with error information.

CreateProcess

CreateProcess Function (string applicationName, string commandLine, string currentDirectory, string environment, long mode=0), long

Description

Starts the process specified by the application name and command line. All of the parameters are optional, and those that are not needed can be passed as empty strings. If the commandLine parameter contains the name of the application to start, then the applicationName can be passed as an empty string. The environment string passed must be a valid environment block, which can be created using the provided environment methods.

Parameters
Parameter Description
string applicationName The name of the module to be executed. This module can be a Windows-based application. It can be some other type of module (for example, MS-DOS or OS/2) if the appropriate subsystem is available on the local computer.

The string can specify the full path and file name of the module to execute or it can specify a partial name. In the case of a partial name, the function uses the current drive and current directory to complete the specification. The function will not use the search path. If the file name does not contain an extension, .exe is assumed. Therefore, if the file name extension is .com, this parameter must include the .com extension.

The applicationName parameter can be empty. In that case, the module name must be the first white space-delimited token in the commandLine string. If you are using a long file name that contains a space, use quoted strings to indicate where the file name ends and the arguments begin; otherwise, the file name is ambiguous. For example, consider the string "c:\program files\sub dir\program name". This string can be interpreted in a number of ways. The system tries to interpret the possibilities in the following order:
c:\program.exe files\sub dir\program name
c:\program files\sub.exe dir\program name
c:\program files\sub dir\program.exe name
c:\program files\sub dir\program name.exe
If the executable module is a 16-bit application, applicationName should be empty, and the commandLine should specify the executable module as well as its arguments.

To run a batch file, you must start the command interpreter; set applicationName to cmd.exe and set commandLine to the name of the batch file.
string commandLine The command line to be executed. The maximum length of this string is 32K characters. If applicationName is empty, the module name portion of commandLine is limited to File:MaxFileName (260) characters.

The commandLine parameter can be empty. In that case, the function uses the string pointed to by applicationName as the command line.

If both applicationName and commandLine are non-empty, the applicationName specifies the module to execute, and the commandLine specifies the command line.

If applicationName is empty, the first white-space – delimited token of the command line specifies the module name. If you are using a long file name that contains a space, use quoted strings to indicate where the file name ends and the arguments begin (see the explanation for the applicationName parameter). If the file name does not contain an extension, .exe is appended. Therefore, if the file name extension is .com, this parameter must include the .com extension. If the file name ends in a period (.) with no extension, or if the file name contains a path, .exe is not appended. If the file name does not contain a directory path, the system searches for the executable file in the following sequence:

The directory from which the application loaded.
  1. The current directory for the parent process.
  2. The 32-bit Windows system directory.
  3. The 16-bit Windows system directory.
  4. The Windows directory.
  5. The directories that are listed in the PATH environment variable. Note that this function does not search the per-application path specified by the App Paths registry key. To include this per-application path in the search sequence, use the ShellExecute function.
string currentDirectory The full path to the current directory for the process. The string can also specify a UNC path.

If this parameter is empty, the new process will have the same current drive and directory as the calling process. (This feature is provided primarily for shells that need to start an application and specify its initial drive and working directory.)


string environment A pointer to the environment block for the new process. If this parameter is an empty string, the new process uses the environment of the calling process.

An environment block consists of a null-terminated block of null-terminated strings. Each string is in the following form:

'name=value<0>'

Because the equal sign is used as a separator, it must not be used in the name of an environment variable.

Note that an environment block is terminated by two zero bytes: one for the last string, one more to terminate the block.
long mode = 0 Allows the initial window mode to be specified. Defaults to SW_SHOW if not set. Can be one of:

jo:SW_FORCEMINIMIZE
Windows 2000/XP: Minimizes a window, even if the thread that owns the window is not responding. This flag should only be used when minimizing windows from a different thread.

jo:SW_HIDE
Hides the window and activates another window.

jo:SW_MAXIMIZE
Maximizes the specified window.

jo:SW_MINIMIZE
Minimizes the specified window and activates the next top-level window in the Z order.

jo:SW_RESTORE
Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when restoring a minimized window.

jo:SW_SHOW
Activates the window and displays it in its current size and position.

jo:SW_SHOWDEFAULT
Sets the show state based on the SW_ value specified in the STARTUPINFO structure passed to the CreateProcess function by the program that started the application.

jo:SW_SHOWMAXIMIZED
Activates the window and displays it as a maximized window.

jo:SW_SHOWMINIMIZED
Activates the window and displays it as a minimized window.

jo:SW_SHOWMINNOACTIVE
Displays the window as a minimized window. This value is similar to SW_SHOWMINIMIZED, except the window is not activated.

jo:SW_SHOWNA
Displays the window in its current size and position. This value is similar to SW_SHOW, except the window is not activated.

jo:SW_SHOWNOACTIVATE
Displays a window in its most recent size and position. This value is similar to SW_SHOWNORMAL, except the window is not actived.

jo:SW_SHOWNORMAL
Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when displaying the window for the first time.
Returns

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. The ErrorTrap() method is called with error information.

Environment handling

The following methods provide handling of environment blocks and variables associated with processes. This allows processes to be started with their own custom set of environment variables. This is particularly useful for calling CGI applications (PHP for example), which use the environment to specify the parameters for the application.

ClearEnvironment

ClearEnvironment Procedure ()

Description

Clears the env property which stores the current environment block.

Parameters

None

Returns

None

AddEnv

AddEnv Procedure (string env, string val, long cgi=0)

Description

Adds a string to the environment block, handles null termination and so on. The environment block is created in the env property which is envLen bytes long. Note that this is not a standard string. Each value pair is null terminated, and the entire block is terminated by a pair of null terminators (one for the last value, and one for the block itself).

Parameters
Parameter Description
string env The name of the environment variable. This may NOT contain the equals sign character ('=')
string val The value for the variable
long cgi=0 If this is set then the function will automatically create this variable in CGI compatible format for use with CGI application.
Returns

None

Remarks

This method encapsulates environment block creation and allows simple strings to be passed to add an value to an environment block. All null separation and termination is handled.

System Process Handling

The following methods provide basic interaction with the processes on the system, such as allowing all processes to be enumerated (list). This is useful for monitoring whether a process is running, and managing existing processes.

DeviceNameForDrive

DeviceNameForDrive Procedure (string sDrive), string

Returns the NT Device name (such as '\Device\HarddiskVolume1') when passed the DOS style drive name (such as 'C:')

Parameters
Parameter Description
string sDrive The drive to retrieve the NT Device Name for. Typically this does not have a trailing backslash, however the method will handle the trailing backslash if it exists.
Returns

If the function succeeds, the return value is a string that contains the NT Device Name that matches the passed drive letter.

If the function fails, the return value is an empty string. The ErrorTrap() method is called with error information.

GetDrives

GetDrives Procedure ( *joDrivesQType drivesQ), bool, proc

Description

Lists all processes running on the system.

Parameters
Parameter Description
*joDrivesQType drivesQ A queue that will be populated with a list of all drives on the system (including mapped network drives, drives added using the SUBST command etc.). The queue must match the joDrivesQType type:
joDrivesQType           queue, type
drive                       string(4)
deviceName                  string(1024)
                        end
The drive property of the queue is populated with the DOS drive name such as 'C:\', while the deviceName property is populated with the NT Device name such as '\Device\HarddiskVolume1'.

As the fields are Strings they may need clipping before use.
Returns

If the function succeeds, the return value is True (1).

If the function fails, the return value is False (0). The ErrorTrap() method is called with error information.

GetProcessPath

GetProcessPath Procedure ( *joProcessQType processQ), string

Description

Returns the path to the executable for the process represented by the current entry in the passed queue. The desired entry should be retrieved before calling this method.

Parameters
Parameter Description
**joProcessQType processList A queue where the current record contains the process information to query. Must be identical to the provided joProcessQType.:
joProcessQType           queue, type
dwSize                      ulong
cntUsage                    ulong
th32ProcessID               ulong
th32DefaultHeapID           ulong                           
th32ModuleID                ulong
cntThreads                  ulong
th32ParentProcessID         ulong
pcPriClassBase              long
dwFlags                     ulong
ExeFile                     string(jo:MAX_PATH)
ProgramName                 string(100)
                        end
Returns

If the function succeeds, the return value is string that contains the path to the executable. Note that the path uses the NT Device format, to get the path uses a standard drive letter use the GetDrives method to get a queue that maps from NT Device names to DOS drive letters.

If the function fails, the return value is an empty string. The ErrorTrap() method is called with error information.

HandleFromPID

HandleFromPID Procedure ( ulong PID), unsigned

Description

Lists all processes running on the system.

Parameters
Parameter Description
*ulong PID The PID (Process Identifier) of the process to retrieve a handle for. When ListProcesses is used to retrieve a list of all processes on the system the th32ProcessID property of the queue contains the PID of the process.
Returns

If the function succeeds, the return value is a handle to the Process.

If the function fails, the return value is zero. The ErrorTrap() method is called with error information.

Remarks

One the handle is not longer required the joCloseHandle API should be used to close it.

ListProcesses

ListProcesses Procedure (*joProcessQType processList), long, proc

Descriptions

Lists all processes running on the system.

Parameters
Parameter Description
*joProcessQType processList The queue to populate with a list of all running processes. Must be identical to the provided joProcessQType.
Returns

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. The ErrorTrap() method is called with error information.

Remarks

The System Idle Process will always be the first process listed in the queue.

GetProcessJobs

GetProcessJobs Procedure (*JobProcessQ procq), long

Description

Gets a list of all processes in the current job and populates a queue with the result.

Parameters
Parameter Description
*JobProcessQ procq The queue to populate with a list of all processes in the current Job.
Returns

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. The ErrorTrap() method is called with error information.

JobObject Properties

init long Set to 1 when the Init method is called successfully. If init is 0 all other functions will return immediately.
hJob long Handle to the current API JobObject
hProcess long Pseudo Handle to the process that create the job (and hence is the first process in the job by default).
name cstring(128) The name of the Job
env string(08000h) String that stores the environment block for passing to a new process. Contains null separate environment setting and is terminated by a pair of nulls. This is not a standard Clarion string, and the AddEnvironment and CleanEnvironment methods should be used to manage it.
envLen long The length of the stored environment block.
Processes &JobProcessQ A queue that contains information about all processes started for the current job using the CreateProcess or AddProcess methods. If EndProcess is called it is removed from this queue automatically.

Properties used to get and set Job information

The following properties store information that is related to the current job. The GetInformation method updates them, and SetInformation can be used to update the job after changing the object properties.
securityAttributes like(joSECURITY_ATTRIBUTES) Security attributes for the current Job. By default these are based on the process that created the Job.
basicAccounting like(joJOBOBJECT_BASIC_ACCOUNTING_INFORMATION) Basic account information for the job (memory usage, processes etc.)
basicIoAndAccounting like(joJOBOBJECT_BASIC_AND_IO_ACCOUNTING_INFORMATION) Accounting information and IO (disk read/writes etc.)
basicLimits like(joJOBOBJECT_BASIC_LIMIT_INFORMATION) Job limits, including process and time limits, memory limitations, processor affinity, priority etc.
basicProcessIdList like(joJOBOBJECT_BASIC_PROCESS_ID_LIST) List of processes in the job
basicUIRestrictions like(joJOBOBJECT_BASIC_UI_RESTRICTIONS) Restricts creation of desktops, changing display settings, shutting down windows, clipboard access etc.
extendedLimits like(joJOBOBJECT_EXTENDED_LIMIT_INFORMATION) Memory limits (per process and job, peek memory usage etc.)
securityLimits like(joJOBOBJECT_SECURITY_LIMIT_INFORMATION) Security limits (prevent admin token access etc.)
completionPort like(joJOBOBJECT_ASSOCIATE_COMPLETION_PORT) Associate a completion port with a Job
endTimeInfo like(joJOBOBJECT_END_OF_JOB_TIME_INFORMATION) The action that the system will perform when the end-of-job time limit has been exceeded