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:
StringTheory

The StringTheory class provides a full string handling class that dynamically allocates memory as needed and provides a wide variety of string handling and manipulation methods, including:

PipeServer and PipeClient

The PipeServer and PipeClient classes wrap up the Windows named pipe API. While we recommend NetTalk for interprocess 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.

Base Methods and Properties

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

General Method Reference

DebugConditionally output to the Windows debug output depending on whether the .debug property is set to true or not.
DebugOutputUnconditionally output a string to the Windows debug output.
ErrorTrapCallback method used to trap errors.
FormatMessageConverts an API error code into the associated error message.
ToCStringCreates a new cstring from the passed string.
FreeCstringSafely frees a cstring reference variable.
Ulong64ToRealConverts an unsigned 64 bit integer to a Real
GetRegReturns the value of the specified registry key.
PutRegSets the value of the specified registry key.
General Property Reference
displayErrorsSets whether or not the class displays errors using the Message function.
logErrorsSets whether or not errors are sent to the Windows Debug Output
errorCodeThe last error code
errorMessageThe last error message
debugDetermines whether or not debug output is produced
debugPrefixThe 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
msgA 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     StringTheory
 
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.

DebugOutput

DebugOutput 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
msgThe error message.
errThe 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
errorCodeThe 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
sThe 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     StringTheory
 
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
cA 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
lpiA 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
sSubKeyPathThe path of the key to retrieve the value for.
sValueThe 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
sSubKeyPathThe path of the key to set the value for.
sValueNameThe name of the value to set.
sValueThe actual value to set the entry to
lTypeThe value type to set. Can be one of the following:
EquateValue Definition
jo:REG_NONE0No value type
jo:REG_SZ1Unicode nul terminated string
jo:REG_EXPAND_SZ2Unicode nul terminated string (with environment variable references)
jo:REG_BINARY3Free form binary
jo:REG_DWORD4 32-bit number
jo:REG_DWORD_LITTLE_ENDIAN432-bit number (same as REG_DWORD)
jo:REG_DWORD_BIG_ENDIAN532-bit number
jo:REG_LINK6Symbolic Link (unicode)
jo:REG_MULTI_SZ7Multiple Unicode strings
jo:REG_RESOURCE_LIST8Resource list in the resource map
jo:REG_FULL_RESOURCE_DESCRIPTOR9
jo:REG_RESOURCE_REQUIREMENTS_LIST10
jo:REG_QWORD11 64-bit number
jo:REG_QWORD_LITTLE_ENDIAN11 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.

Base 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 longLog 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 longThe 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

AddProcessAdd an existing (running) process to the Job.
CloseAllClose all processes associated with the current job.
CreateJobCreate a new Job. Called automatically by the Init method.
EndProcessTerminate a running process.
ExecuteFileRun a file using the default application associated with it, or start a program
GetCurrentUserTokenGets the current User's token (which stores the users security attributes).
GetInformationGet information about the Job.
GetProcessJobsFills the passed queue with all processes related to the current Job.
GetSessionsGet a list of sessions on the current machine (log in users and system sessions).
InitInitialize the object, load the DLLs required, and optionally create a new Job Object.
KillTerminate the Job, release all handles and free all memory allocated.
KillProcessKill one or more processes with the specified name.
LoadLibsLoad the libraries (DLLs) required for the functionality provided.
LocateProcedureLocate a procedure in a dynamically loaded library.
LogonUserRetrieves a the token representing the specified user.
RunAsUserRun a process as the currently logged in user.
SetInformationSet information (such as limits) for the current Job.
CreateProcessStart a process (processes are started as a part of the current Job by default).
StoreProcessInfoStore information related to a specific process. Called internally to update the Processes queue.
AddEnvAdd an environment variable to the stored Environment block.
ClearEnvironmentClear the stored environment block
ListProcessesList all processes running on the system and stores them in a queue (much like the Windows task manager does).
HandleFromPIDReturns the Process Handle when passed the Process ID (PID)
GetProcessPathReturns the full path to the executable for a process
DeviceNameForDriveReturns the full device name when passed the drive identifier (for example 'C:'  or 'D:')
GetDrivesPopulates a queue with a list of all drives and their full NT Device Names.

JobObject Property Reference

initSet to 1 when the Init method is called successfully. If init is 0 all other functions will return immediately.
hJobHandle to the current API JobObject
hProcessPseudo Handle to the process that create the job (and hence is the first process in the job by default)
nameName for the job
envString that stores the environment for passing to a new process. Contains null separate environment setting and is terminated by a pair of nulls
envLenThe current environment length
securityAttributesThe Security Attributes for the started Job
basicAccountingBasic account information for the job (memory usage, processes etc.)
basicIoAndAccountingAccounting information and IO (disk read/writes etc.)
basicLimitsJob limits, including process and time limits, memory limitations, processor affinity, priority etc.
basicProcessIdListList of processes in the job
basicUIRestrictionsRestricts creation of desktops, changing display settings, shutting down windows, clipboard access etc.
extendedLimitsMemory limits (per process and job, peek memory usage etc.)
securityLimitsSecurity limits (prevent admin token access etc.)
completionPortAssociate a completion port with a job
endTimeInfoThe action that the system will perform when the end-of-job time limit has been exceeded
ProcessesA 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 hProcessA 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

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 JobNameThe 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 QueryInformation 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 procNumThe 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 fileNameThe 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 infoClassThe information class for the limits to be queried. This parameter can be one of the following values:
ValueMeaning
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 SessionsA 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
processNameThe handle to the library to load to the function from.
killAll = trueOptional 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 = trueOptional 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
hLibThe handle to the library to load to the function from.
procNameThe 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

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
userNameThe 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.
domainSpecifies 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.
passwordSpecifies 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.
logonTypeThe type of logon to perform, defaults to jo:LOGON32_LOGON_BATCH (4). May be one of the following:
ValueMeaning
jo:LOGON32_LOGON_BATCHThis 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_INTERACTIVEThis 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_NETWORKThis 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_CLEARTEXTThis 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_SERVICEIndicates a service-type logon. The account provided must have the service privilege enabled.
jo:LOGON32_LOGON_UNLOCKThis 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.
longonProviderThe logon provider, defaults to jo:LOGON32_PROVIDER_DEFAULT (0). May be one of the following values:
ValueMeaning
LOGON32_PROVIDER_DEFAULTUse 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_WINNT50Use the negotiate logon provider.

Windows NT: This value is not supported.
LOGON32_PROVIDER_WINNT40Use the NTLM logon provider.
LOGON32_PROVIDER_WINNT35Use 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

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', '')

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
processPathThe name and path of the executable to run.
argumentsCommand 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 infoClassThe 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 appThe name of the application that was started (and optionally the path). Can be empty if cmd contains the application name
string cmdThe 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 envThe environment block for the process.
string dirStarting directory
*joPROCESS_INFORMATION piThe API process information used in the process creation
*joSTARTUPINFO siThe startup information returned by the process creation API
HANDLE hRead = 0Optional handle to the standard output of the process for reading data from the process. Passed to WriteData.
HANDLE hWrite = 0Optional 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 pAppNameThe name and path of the application to run, can include command line parameters and options
ushort pModeAllows 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=0Uses 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 = 0Optional 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 = 0Optional 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 pAppNameThe 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 = 0Optional 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 = 0Optional 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 = 0Allows 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 applicationNameThe 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 commandLineThe 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 currentDirectoryThe 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 = 0Allows 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 envThe name of the environment variable. This may NOT contain the equals sign character ('=')
string valThe value for the variable
long cgi=0If 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 sDriveThe 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'.
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 PIDThe 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 processListThe 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 procqThe 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 longSet to 1 when the Init method is called successfully. If init is 0 all other functions will return immediately.
hJob longHandle 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 longThe length of the stored environment block.
Processes &JobProcessQA 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

StringTheory

Using the StringTheory class

String Theory Method Reference
AppendAppend a value to the end of the string
Base64DecodeDecode a string that is encoded using Base64
Base64EncodeEncode the string using Base64 encoding method
ClipLengthGet the length of the string, ignoring trailing spaces
CountReturns the number of times that the SearchValue appears in the current string
CropRemoves part of the string from either the front, or rear, or both, of the string
ErrorTrapCalled if an OS error occurs
ExtensionOnlySplits the extension part out of a file name.
FileNameFromPathSplits the file name part out of a fully qualified path name
FormatMessageInterprets the windows API error code
FreeClears the string and returns all the memory used by the string
FreeLinesFrees the Queue populated by the Split method
FromBlobRetrieves the data from the passed BLOB and stores it.
GetLineGets a specific line after a call to the Split method
GetValueReturns the current value of the string
InstringSearch for a string in a sub string
JoinCreates a string from the separate lines (where the lines are made by Split)
LengthThe current length of the string
LoadFileLoad a file off the disk into the string
LowerChange all the characters in the string to be lower case
MD5Generates the MD5 Hash of a string
PathOnlyGets the path part of a fully qualified file name
PrependAdds a sub string to the front of the string
RandomFills the string with random characters
RecordsReturns the number of records after a call to the Split method
ReplaceReplaces one, or more, instances of the seachstring with a new value
SaveFileSaves the current string to disk
SetLengthSets the length of the string
SetValueAssigns a new value to the current string
SliceReturns a substring of the current string
SplitSplits the string into components parts
SubReturns a substring of the current string
ToCStringCreates a CString and copies in the current string value
ToBlobSaves the data stored by the StringTheory object in the passed BLOB.
UpperConverts all the lower case characters to upper case
TraceSends a string to the DebugView program for logging
StringTheory Property Reference
base64Set to true when string is base 64 encoded
linesA queue of strings created by the Split method
logErrorsIf true, errors will be logged via the trace method
valueThe current string value
winErrorCodeThe most recent windows api error code

Using the StringTheory Class

In general a StringTheory object is declared as simply as

st StringTheory

Where st is the label name (and can be almost anything.) The length of the string is undefined, and is dynamic. In other words the string will automatically grow, and shrink as required. You do not need to worry about the length.

Values are assigned into the string using the SetValue method, or by loading a file off the disk using the LoadFile method.
st.SetValue('hello world')
st.LoadFile('c:\windows\win.ini')


After that the string can be manipulated in a number of different ways, using the methods described below. For example to Base64 encode the string;

st.Base64Encode

StringTheory Method Reference

MethodProcedureDescription
Append (string NewValue, [Long Clip=false])Appends the NewValue to the current string currently stored in the object. If the clip parameter is omitted, or false, then the string being appended is not clipped.
In Clarion 5.5 the Append keyword is reserved, so in Clarion 5.5, for this method, use the method name AppendA instead.
See also the Prepend method.
Base64Decode () Procedure If the Base64 property is set to True, then decodes the current string using the Base64 decode algorithm. The Base64 property is then set to False.
Base64Encode ()If the Base64 property is false, then encodes the current string in Base64 format. The Base64 property is set to True.
ClipLength ()Returns the length of the current string, ignoring any trailing spaces.
See also the Length method for returning the length of the string including trailing spaces.
Count (string SearchValue,[long pStep],[Long Start],[Long End],[Long NoCase])Returns the number of times that the SearchValue appears in the current string.
The search area can be limited using Start and End. If omitted, or zero, the whole string is used.
For case insensitive matches set the NoCase parameter to true. The default value is false.
This method does not alter the current string.
Crop ([Long Start],[Long End])Sets the string to be a subset of itself. The portions of the original string outside the slice are discarded.
For example, if the current string contains 123456789 and the method
.slice(4,7) is called
then the current string will contain 4567
If the Start parameter is omitted, then the string will only be cropped at the end.
If the End parameter is omitted, then the string will only be cropped at the front.
ErrorTrap (string MethodName, string Message)This method is called when there is an error raised in the Load or Save methods. If the LogErrors property is set to true then the error message will be passed on to the trace method. This is an ideal method to use to add custom error handling to the Load and Save methods.
ExtensionOnly ([String FileName])Returns just the extension part of the filename, i.e. the part after the last .
If the FileName parameter is omitted, then the current string value is used.
The current string value is not altered by this method.

See also
PathOnly and ExtensionOnly
FileNameOnly ([String FileName])If the passed string contains a fully qualified filename, i.e. a filename including the path, then this method strips off the path part, and returns just the filename part.
If the FileName parameter is omitted, then the current string value is used.
The current string value is not altered by this method.
See also the PathOnly and ExtensionOnly methods.

Example
st   stringtheory
s    string(255)
  code
  s =
command(0)
  s = st.FileNameFromPath(s)
FormatMessage (long Error)This method converts the Windows Error Code into a Text description of the error.
See also ErrorTrap method, and WinErrorCode property.
Free ()A method used to free the memory used by the Split command. This safely, and without leaking memory empties the existing queue of lines.
See also the Split method.
FreeLines ()A method used to free the the Lines Queue populated by the Split command. This safely, and without leaking memory, empties the existing queue of lines.
See also the Split method.
FromBlob (*blob blobField)Load the value from a BLOB into the StringTheory object

Parameters
*blob blobField

The BLOB to retrieve the data from.

Return Value
Returns true (1) for success and zero for failure

Examples
s               StringTheory
blobContents    string
  code
 
  s.FromBlob(MailData.Text)     ! Store the data
    blobContents = s.GetValue()   ! Get the stored data
GetLine (long LineNumber)Returns the value of a specific line in the string, after calling the Split method.
See also the Split method
GetValue (string NewValue)Returns the value of the string currently stored in the object.
See also the SetValue method.
Instring (string SearchValue,[Long Step],[Long Start],[Long End],[string NoCase])Searches for the substring in the current string.
If the Step parameter is omitted then it defaults to 1, not the length of the search string.
If the Start parameter is omitted then the search starts at the beginning of the string.
If the End parameter is omitted then the search goes to the end of the string.
If the NoCase parameter is omitted then the search is case sensitive.
Returns the position of the first match.
This method does not alter the current string.

Special note: Unlike the Clarion INSTRING command, the default value of Step is 1, not the length of the Search value.
Join (String Boundary, [String Quote],[string QuoteEnd])The opposite of the Split method. The current string value is cleared. The string is then constructed from the parts in the Lines Queue. The result is placed in the current value.
Each line is separated from the others using the Boundary parameter.
If a Quote parameter is used, and a line contains the boundary character(s), then the line will be prefixed by the Quote parameter (if it isn't already). The line will also be ended by either the QuoteEnd parameter (if it exists) or the Quote Parameter.
The Lines Queue remains as-is after this call. It is not cleared.
Length ()Returns the current length of the string currently stored in the object.
In Clarion 5.5 the Length keyword is reserved, so in Clarion 5.5, for this method, use the method name LengthA instead.
Loadfile (String FileName)Loads a file off the disk, and places it in the current string value. The maximum size of the file is limited only by the maximum size of a string in Clarion.

See also the SaveFile method.

Example
st  stringtheory
 
code
    st.loadFile('
c:\windows\win.ini')
Lower ()Converts all the characters in the current string to lower case.
MD5 ()Returns the MD5 hash value of the current string.
Derived from the RSA Data Security, Inc. MD5 Message-Digest Algorithm.
This method is only included if your project has the MD5=>1 project define included.

PathOnly ([String FileName])If the passed string contains a fully qualified filename, i.e. a filename including the path, then this method strips off the filename part, and returns just the path part. If the FileName parameter is omitted, then the current string value is used. The current string value is not altered by this method.

See also the FileNameFromPath and ExtensionOnly methods.

Example
st   stringtheory
s    string(255)
 
code
    s =
command(0)
    s = st.PathOnly(s)
Prepend (String NewValue)The opposite of the Append method. The passed parameter is added to the front of the current string.
Random ([Long Length], [Long Flags])Fills the string with random characters.
If the length parameter is omitted then the default length is 16 characters.
The flags parameter determines which characters can be in the string;
st:Upper : Upper case characters from A to Z are allowed
st:Lower : Lower case characters from A to Z are allowed
st:Number : digits from 0 through 9 are allowed
st:AlphaFirst : Regardless of the other bit settings, the first character must be an uppercase letter, A through Z.
If the Flags parameter is omitted then only characters from A to Z are allowed.

This function is useful when generating random file names, or creating GUID strings or things like that.
Because of the ability to generate only digits it's also useful for generating really large random numbers (in a string).
Records ()Returns the number of lines parsed after a call to the Split method.
Replace (String OldValue, String NewValue, [Long Count],[Long Start],[Long End],[Long pNoCase])Searches for instances of Old Value in the current string and replaces them with NewValue.
If the Count parameter is set, then the method will terminate after Count instances of OldValue have been found, and replaced.
If the NoCase parameter is true then a case-insensitive search will be done. The default is case sensitive.
SaveFile

SaveFile
(String FileName, [Long AppendFlag])

(String NewValue, String FileName, [Long AppendFlag])
Saves the current string to the disk as a file, or appends the current string to an existing file on the disk.
If the NewValue parameter is used, then the value in that string is saved, rather than the current string.
If the AppendFlag parameter is set to true then the string is appended to the current file. If it set to false then the current string is saved, and the current values in the file, if the file already exists, is lost.
SetLength (long NewLength)Sets the space allocated to the string to a specific length. This is mostly for internal use to be used when extra space is required - for example in the base64 encoding method. This method is not needed when calling SetValue as that adjusts the length of the string automatically.
See also the Length method to get the current length of the string.
SetValue (string NewValue, [Long Clip])Sets the value of the object to the parameter passed. The passed string can be of any size. If the clip parameter is omitted, or false, then the value being added to the string is not clipped.

See also the GetValue method. If the value you are passing into the object is Base64 encoded, then set the Base64 property to 1 at the same time
Slice (Long Start, [Long End])Returns a substring of the current string. The current string is not altered.
If the end parameter is omitted then the string from the Start position to the end of the string is returned.
See also the Sub method.
Split (string Boundary, [String Quote],[string QuoteEnd])The current string is "split" into a number of strings, which are then easily accessible in the Lines Queue. This allows for the easy parsing of "anything separated lists", for example the semi-colon separated lists used for emails, or the string returned from a multi-select FILEDIALOG command.
The Boundary parameter lets you specify the separating character.
The optional pQuote parameter allows you to specify a "quote" character which negates the boundary. For example in the following comma separated list, the double quote character wraps a string that negates the comma.
Bruce Johnson,"Cape Town, South Africa"
This string would be parsed into 2 parts, the name and the address. The Quoting characters ARE included in the parsed result.
If the start, and end, quote characters are different, then the QuoteEnd parameter can be used. For example
<Bruce Johnson>,<Cape Town, South Africa>
If a string consists of multiple lines then the multi-character boundary <13,10> can be used.

See Also the DisposeLines, Records and GetLine methods.
Sub (Long Start, [Long Length])Returns a substring of the current string. The current string is not altered.
If the length parameter is omitted then the single character at the Start position is returned.

See also the Slice method.
ToBlob (*blob blobField)Saves the current value to the passed BLOB.

Parameters
*blob blobField

The BLOB field to store the value in.

Return Value
Returns True (1) for success or (0) for failure. If an error occurs the ErrorTrap() method is called with additional information.

Examples
s.SetValue(plainText, true! Store a value in the StringTheory object
s.ToBlob(MailData.Text)     
! Store the value in the passed BLOB
ToCString ()Returns a pointer to a Cstring. The contents of the Cstring will be set to the current string. This is useful if you wish to pass the string to other functions that require a Cstring.

NOTE: POTENTIAL MEMORY LEAK WARNING: 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.

Examples
c  &cstring
st StringTheory

 
code
    st.SetValue('
hello world')
    c &= st.ToCstring()
   
! use cstring here
    Dispose(c)
Upper ()Converts all the characters in the current string to upper case.
Trace (string Message)The passed Message is sent to Debugview.
DebugView is a useful free utility provided by Microsoft for viewing the all output to the system debug log, as well as allowing it to be filtered, specified strings to be highlighted etc. DebugView is a free 286KB download, available for all version of Windows from XP onwards, from http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx.

StringTheory Property Reference

Base64 longSet to True (1) if the string currently in the object is Base64 encoded. Set to False (0) if not. Note that if you set a string directly, using the SetValue method
Lines queueA queue of strings populated by the Split method.
LogErrors longSet to True (1) then errors sent to the ErrorTrap method will be forwarded to the Trace method, for output to the DebugView logging tool.
Value stringThe current value of the string. You should use the GetValue and SetValue methods to access the string, rather than accessing the property directly.
WinErrorCode longThe Windows Error code generated by the Load or Save method.