table top left corner

CapeSoft OddJob Class Reference

table top right corner
table left side

 

table top left corner   table top right corner
table left side

 

OddJob header linked to CapeSoft home page
Version: version number
CapeSoft Software copyright

 

table right side
table bottom left corner table bottom table bottom right corner


table top left corner Introduction table top right corner
table left side

OddJob provides the following classes:

JobObject

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

  • process control and enumeration;
  • Job creation and management;
  • Allows processes to be started, monitored and terminated;
  • Provides the ability to write data to a process' StdIn, and read from the StdOut - allowing communication with command line processes such as servers, compilers, script interpreters (such as PHP, Python and so on), etc.;
  • Create environment blocks for starting new processes (particularly useful when calling application such as the PHP CGI interface, which passes all data via environment variables).
  • And much more

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:

  • Dynamic memory allocation for strings (the string is always the length that it needs to be to hold any data);
  • File loading and saving;
  • Unicode and ANSI conversion and encoding
  • Copying data to and from BLOBs;
  • The ability to manipulate the string, search it, append to it, extract substrings etc.;
  • Base64 encoding and decoding;
  • Convert to Cstring;
  • Blowfish encryption and decryption (when used with Capesoft CryptoNite)
  • Text wrapping, Hex encoding and decoding, base conversion (convert between hexadecimal, decimal, octal etc.), split and merge strings, split and parse filenames etc.
  • and much more!

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.

 

table right side
table bottom left corner table bottom table bottom right corner


table top left corner Base Methods and Properties table top right corner
table left side

 

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

box General Method Reference

Debug Conditionally output to the Windows debug output depending on whether the .debug property is set to true or not.
DebugOutput 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.
   

box 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

 

table right side
table bottom left corner table bottom table bottom right corner

 

Base Methods and Properties

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

 

Base Methods

 

Debug Procedure (string msg)

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

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

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 ouput is enabled.

 

 

DebugOutput Procedure (string msg)

Identical to the Debug method, except that the ouput 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 Procedure (string msg, long err)
ErrorTrap Procedure ()

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

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 Procedure (long errorCode), string

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

errorCode

The Windows API error code.

Return Value

none

 


ToCString Procedure (*string s)

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

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.

Examples


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 Procedure (*cstring c)

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

 

Parameters

c

A cstring reference variable.

Return Value

None.

 

 

Ulong64ToReal Procedure (*joLARGE_INTEGER pli)

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

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 Procedure (long hKey, string sSubKeyPath, string sValue), ?

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

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 Procedure (long hKey, string sSubKeyPath, string sValueName, string sValue, long lType=1), long

Sets the specified registry key to the passed value.

Parameters

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  Resource list in the hardware description
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.

 

 

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 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.

 

 

table top left corner JobObject table top right corner
table left side

 

box Using the JobObject class

box 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.
   

box 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

 

table right side
table bottom left corner table bottom table bottom right corner

 

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 Procedure (unsigned hProcess), long

Add a current running process to the current job.

Parameters

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

 

 

CloseAll Function (), long, proc

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 Function (string jobName), long

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

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 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 Procedure (long procNum), long

Terminates the specific process that is associated with the job.

Parameters

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 Procedure (string fileName), long

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

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 Function (), unsigned

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.

Remarks

Remarks.

 

 

GetInformation Function (long infoClass), long

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

Parameters

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 Procedure (<*joSessionInfo Sessions>), ulong, virtual

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

Parameters

*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.

Remarks

Remarks.

 

 

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

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

<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 Procedure ()

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

Parameters

None

Returns

None

 

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

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

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 procceses 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.

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(processName, killAll, exactMatch)
  end

  return

 

 

LoadLibs Function (), long

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 Function (long hLib, string procName), long

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

Parameters

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 Function (string userName, <string domain>, string password, *HANDLE phToken, ulong logonType=4, ulong logonProvider=0)

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

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

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

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

 

 

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

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

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

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

 

 

SetInformation Function (long infoClass), long

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

Parameters

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 Procedure (string app, string cmd, string env, string dir, *joPROCESS_INFORMATION pi, *joSTARTUPINFO si, HANDLE hRead = 0, HANDLE hWrite = 0), virtual

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

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 independant 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 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

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

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 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.

 

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 functionlity 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 Procedure (string pAppName, <*StringTheory pOutput>, long noRead = 0, long noStore = 0, long mode=0), long, proc, virtual

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

Parameters

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 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.

 

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

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

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.

Remarks

Remarks.

 

 

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 Procedure ()

Clears the env property which stores the current environment block.

Parameters

None

Returns

None. 

 

 

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

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

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 seperation 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 Procedure (string sDrive), string

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

Parameters

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 Procedure (*joDrivesQType drivesQ), bool, proc

Lists all processes running on the system.

Parameters

*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 Procedure (*joProcessQType processQ), string

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

**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 Procedure (ulong PID), unsigned

Lists all processes running on the system.

Parameters

*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 Procedure (*joProcessQType processList), long, proc

Lists all processes running on the system.

Parameters

*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 Procedure (*JobProcessQ procq), long

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

Parameters

*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

Psuedo 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 seperate 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


 

table top left corner StringTheory table top right corner
table left side

 

box Using the StringTheory class

box String Theory Method Reference

Append Append a value to the end of the string
Base64Decode Decode a string that is encoded using Base64
Base64Encode Encode the string using Base64 encoding method
ClipLength Get the length of the string, ignoring trailing spaces
Count Returns the number of times that the SearchValue appears in the current string
Crop Removes part of the string from either the front, or rear, or both, of the string
ErrorTrap Called if an OS error occurs
ExtensionOnly Splits the extension part out of a file name.
FileNameFromPath Splits the file name part out of a fully qualified path name
FormatMessage Interprets the windows API error code
Free Clears the string and returns all the memory used by the string
FreeLines Frees the Queue populated by the Split method
FromBlob Retrieves the data from the passed BLOB and stores it.
GetLine Gets a specific line after a call to the Split method
GetValue Returns the current value of the string
Instring Search for a string in a sub string
Join Creates a string from the separate lines (where the lines are made by Split)
Length The current length of the string
LoadFile Load a file off the disk into the string
Lower Change all the characters in the string to be lower case
MD5 Generates the MD5 Hash of a string
PathOnly Gets the path part of a fully qualified file name
Prepend Adds a sub string to the front of the string
Random Fills the string with random characters
Records Returns the number of records after a call to the Split method
Replace Replaces one, or more, instances of the seachstring with a new value
SaveFile Saves the current string to disk
SetLength Sets the length of the string
SetValue Assigns a new value to the current string
Slice Returns a substring of the current string
Split Splits the string into components parts
Sub Returns a substring of the current string
ToCString Creates a CString and copies in the current string value
ToBlob Saves the data stored by the StringTheory object in the passed BLOB.
Upper Converts all the lower case characters to upper case
Trace Sends a string to the DebugView program for logging
   

 

box StringTheory Property Reference

base64 Set to true when string is base 64 encoded
lines A queue of strings created by the Split method
logErrors If true, errors will be logged via the trace method
value The current string value
winErrorCode The most recent windows api error code

 

table right side
table bottom left corner table bottom table bottom right corner

 

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

 

Append Procedure (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 Procedure ()

If the Base64 property is false, then encodes the current string in Base64 format. The Base64 property is set to True.

 

ClipLength Procedure ()

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 Procedure (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 Procedure ([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 Procedure (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 Procedure ([String FileName])

Returns just the extension part of the filename, ie 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 Procedure ([String FileName])

If the passed string contains a fully qualified filename, ie 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 Procedure (long Error)

This method converts the Windows Error Code into a Text description of the error.
See also ErrorTrap method, and WinErrorCode property.

 

Free procedure ()

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 Procedure ()

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 Procedure (*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 Procedure (long LineNumber)

Returns the value of a specific line in the string, after calling the Split method.
See also the Split method.

 

GetValue Procedure (string NewValue)

Returns the value of the string currently stored in the object.
See also the SetValue method.

 

Instring Procedure (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 Procedure (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 Procedure ()

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 Procedure (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 Procedure ()

Converts all the characters in the current string to lower case.

 

MD5 Procedure ()

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 Procedure ([String FileName])

If the passed string contains a fully qualified filename, ie 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 Procedure (String NewValue)

The opposite of the Append method. The passed parameter is added to the front of the current string.

 

Random Procedure ([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 Procedure ()

Returns the number of lines parsed after a call to the Split method.

 

Replace Procedure (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 Procedure (String FileName, [Long AppendFlag])
SaveFile Procedure (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 Procedure (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 Procedure (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 Procedure (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 Procedure (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 Procedure (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 Procedure (*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 Procedure ()

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 Procedure ()

Converts all the characters in the current string to upper case.

 

Trace Procedure (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 long

Set 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 queue

A queue of strings populated by the Split method.

LogErrors long

Set 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 string

The current value of the string. You should use the GetValue and SetValue methods to access the string, rather than accessing the property directly.

WinErrorCode long

The Windows Error code generated by the Load or Save method.

 

 

 


table right side
table bottom left corner table bottom table bottom right corner



All content © Copyright CapeSoft Software