Tips   >   Functions   >   Functions (All Contents)

Functions

Omnis Studio has a wealth of functions. Date functions, String functions, FileOps, FontOps, etc.

You can view the various functions and help tips for each function as follows:

  1. Press F9 to open the Catalog.
  2. Click on the Functions tab to see the list of available functions.
  3. Click on FileOps in column one of the Catalog
  4. Move your mouse over one of the FileOps functions in column two. If you have help tips turned on, a tooltip will appear giving you the syntax for the function and a short description of the function. (Right-click on the F9 Catalog and select Help Tips to toggle the help tips on our off. Right-click and select Save Window Setup to save the current state.)
Tip

You can drag any function from the F9 Catalog into a Do statement in the code editor. The function and its parameters will be copied into your Do statement.

There were a number of handy functions which I was not using because I didn't know about them, didn't understand what they did, or didn't now how or where to use them.

Quick demos are provided in this section for functions, where applicable.

Date Functions

This section provided explanations and demos of the various date function as applicable.

To view all of the date functions:

  1. Press F9 to open the Catalog.
  2. Click the Functions tab.
  3. Click Date and Time in column one. All of the date and time functions are displayed in column two.

    If you hover or one of the date functions a tooltip tip appears providing you with the syntax and a short description of the function.
Tip

You can drag and drop any of the functions into your code. Omnis Studio conveniently copies the function and parameter names into your code.

Many of the date functions require Date Parts contants values, (e.g. kDay, kDayOfWeek, kYear, kSaturday), or Date Codes values. (e.g. y - 1989, N - minutes)

To find the Date Parts and Date Codes:

  1. Press F9 to open the Catalog.
  2. Click the Constants tab.
  3. Click either Date Code or Date Parts in column one. The available constants will be displayed in column two.
Tip

If your are entering code in the code editor, you can drag and drop or double-click on any of the constants in the F9 Catalog. Omnis Studio will copy the constant to your code.

dadd()

Date Add

dadd(kDateCode,Value,Date)

Adds the Value, in kDateConstant units, to the Date.

; Delete 1 day from today.
Calculate NewDate as dadd(kDay,-1,#D)

; Add 2 weeks to today.
Calculate NewDate as dadd(kWeek,2,#D)

; Add 1 year to today.
Calculate NewDate as dadd(kYear,1,#D)

Click the Run Demo button in the StudioTips Browser for a demonstration.

dat()

Date

dat(StringOrNumber,[date format])

Converts a string or number to a date. The date format will be the default #FD format, unless you specific a format in the 2nd parameter. Be sure the date format of the string matches the #FD or include the optional date format parameter.

I find this function useful when importing dates from a text file or spreadsheet.

; Convert date string to a date variable.

Calculate String as '15-SEP-2006'
Calculate DateVar as dat(String,'D-m-y')

Calculate String as '2006-08-31'
Calculate DateVar as dat(String,'y-M-D')

Calculate String as '12/31/2005'
Calculate DateVar as dat(String,'M/D/y')

ddiff()

Date Difference

ddiff(kDateConstant,Date1,Date2)

Calculates the value of Date2 minus Date1 in kDateConstant units.

If you want a positive result the bigger date must be the second date parameter. (Think of it as ascending order).

Calculate Date1 as #D
Calculate Date2 as dadd(kDay,20,#D)

; The number of days between Date1 and Date2.
Calculate DaysDiff as ddiff(kDay,Date1,Date2)

Warning

ddiff() does not calculate decimal values. ddiff() simply truncates the decimal remainder .

If you want to know the difference between two dates by the number of weeks plus days, and you will need to calculate the difference using the kDay constant and then divide the result by 7.

; The number of full weeks between Date1 and Date2.
Calculate WeeksDiff as ddiff(kWeek,Date1,Date2)

; Use the mod() function to calculate the remainder in days.
Calculate RemainderInDays as mod(ddiff(kDay,Date1,Date2),7)

Click the Run Demo button in the StudioTips Browser to see the results of the above sample code.

dim()

Date Increment Months

dim(Date,NumberOfMonths)

Adds the NumberOfMonths to Date. NumberOfMonths can be a positive or negative integer.

; Calculate a new date that is one month after today.
Calculate NewDate as dim(#D,1)

Tip

Use the more flexible dadd() function instead. dadd(kMonth,2,Date)

Click the Run Demo button in the StudioTips Browser for a demonstration.

dname()

Date Name

dname(kDateConstant,Date)

Calculates the month name or day of week name of the date.

Calculate MonthName as dname(kMonth,#D)
Calculate DateName as dname(kDay,#D)

; The jst() function is more flexible.
Calculate DayMonthDateYearString as jst(#D,'D:w, n D, y')

Tip

Use the more flexible jst() function instead. jst(#D,'D:w, n D, y')

Click the Run Demo button in the StudioTips Browser for a demonstration.

dpart()

Date Part

dpart(kDateConstant,Date)

Calculates the kDateConstant value of Date.

Calculate DayOfWeek as dpart(kDayofWeek,#D)
Calculate DayOfYear as dpart(kDayofYear,#D)
Calculate WeekOfMonth as dpart(kWeekofMonth)
Calculate MonthOfYear as dpart(kMonth,#D)

Click the Run Demo button in the StudioTips Browser for a demonstration.

dtcy()

Date Century Year

dtcy(Date)

Calculates the year including century of a date. (e.g. 1985)

Calculate CenturyYearString as dtcy(#D)

Click the Run Demo button in the StudioTips Browser for a demonstration.

dtd()

Date Day

dtd(Date)

Calculates the day of a date (e.g. 6th).

Calculate Day as dtd(#D)

; The jst() function is more flexible.
Calculate DayMonthDateYearString as jst(#D,'D:w, n d, y')

Tip

Use the more flexible jst() function instead. jst(#D,'D:d')

Click the Run Demo button in the StudioTips Browser for a demonstration.

dtm()

Date Month

dtm(Date)

Calculates the month name of a date (e.g. September).

Calculate MonthName as dtm(#D)

; The jst() function is more flexible.
Calculate DayMonthDateYearString as jst(#D,'D:w, n D, y')

Tip

Use the more flexible jst() function instead. jst(#D,'D:n')

Click the Run Demo button in the StudioTips Browser for a demonstration.

dtw()

Date Weekday

dtw(Date)

Calculates the weekday name of a date (e.g. Wednesday).

Calculate DayOfWeekName as dtm(#D)

; The jst() function is more flexible.
Calculate DayMonthDateYearString as jst(#D,'D:w, n D, y')

Tip

Use the more flexible jst() function instead. jst(#D,'D:w')

Click the Run Demo button in the StudioTips Browser for a demonstration.

dty()

Date Year

dty(Date)

Calculates the year excluding the century of a date (e.g. 06).

Calculate YearWithoutCentury as dty(#D)

; The jst() function is more flexible.
Calculate DayMonthDateYearString as jst(#D,'D:w, n D, Y')

Tip

Use the more flexible jst() function instead. jst(#D,'D:Y')

Click the Run Demo button in the StudioTips Browser for a demonstration.

fday()

First Day

fday(kDateConstant,Date)

Calculates the first day of the kDateConstant unit.

Calculate FirstDateOfYear as fday(kYear,#D)
Calculate FirstDateOfMonth as fday(kMonth,#D)
Calculate FirstDateOfWeek as fday(kWeek,#D)

Click the Run Demo button in the StudioTips Browser for a demonstration.

getfye()

Get Fiscal Year End

getfye()

; Get the current (global) Omnis Studio fiscal year end.
Calculate OmnisFiscalYrEnd as getfye()

Warning

The fiscal year related date functions depend on the current Omnis Studio fiscal year end date. If your code makes use of the fiscal year date functions you must be careful to always set the Omnis Studio fiscal year end when you startup your application, or if the user can switch from one company to another company with different fiscal year ends within the same session of Omnis Studio. For setting the Omnis Studio fiscal year see the setfye() function.

Omnis Studio also has a fiscal year end date stored in each library's preference property.

; Each library has a $fiscalyearend property.
Calculate LibraryFiscalYrEnd as $clib.$prefs.$fiscalyearend()

  1. Select any library in the F2 Browser.
  2. Press F6 to open the Property Manager.
  3. Click the Prefs tab, and look for the $fiscalyearend property.
The $fiscalyearend property and getfye() function are independent of each other.

getws()

Get Week Start

getws()

Returns the day of the week which is set as the beginning of the week.

The day of the week is returned as one of the date part constants: kSunday, kMonday, kTuesday, kWednesday, kThursday, kFriday, kSaturday.

Omnis Studio also has a $weekstart property stored in each library's preference property.

; Get the current (global) Omnis Studio week start.
Calculate OmnisWeekStart as getws()

; Each library has a $weekstart property.
Calculate LibraryWeekStart as $clib.$prefs.$weekstart()

  1. Select any library in the F2 Browser.
  2. Press F6 to open the Property Manager.
  3. Click the Prefs tab, and look for the $weekstart property.
The $weekstart property and getws() function are independent of each other.

isoweek()

isoweek(Date)

Returns the ISO 8601 standard week number for the week containing the specified date.

; Get the ISO week for today.
Calculate ISOWeekNum as isoweek(#D)

Click the Run Demo button in the StudioTips Browser for a demonstration.

lday()

Last Day

lday(kDateConstant,Date)

Calculates the last day of the kDateConstant unit.

Calculate LastDateOfYear as lday(kYear,#D)
Calculate LastDateOfMonth as lday(kMonth,#D)
Calculate LastDateOfWeek as lday(kWeek,#D)

Click the Run Demo button in the StudioTips Browser for a demonstration.

nday()

Next Day

nday(kDateConstant,Date)

Calculates the next day occurence of the kDateConstant unit, after the Date.

Constants that can be used: kDay, kSunday, kMonday, kTuesday, kWednesday, kThursday, kFriday, kSaturday

Calculate NextDay as nday(kDay,#D)
Calculate NextSaturday as nday(kSaturday,#D)
Calculate NextWednesday as nday(kWednesday,#D)

Click the Run Demo button in the StudioTips Browser for a demonstration.

pday()

Previous Day

pday(kDateConstant,Date)

Calculates the previous day occurence of the kDateConstant unit, after the Date.

Constants that can be used: kDay, kSunday, kMonday, kTuesday, kWednesday, kThursday, kFriday, kSaturday

Calculate PrevDay as pday(kDay,#D)
Calculate PrevSaturday as pday(kSaturday,#D)
Calculate PrevWednesday as pday(kWednesday,#D)

Click the Run Demo button in the StudioTips Browser for a demonstration.

setfye()

Set Fiscal Year End

setfye('Month Day')

; Set the current (global) Omnis Studio fiscal year end.
Do setfye('JAN 31')

; Check the Omnis Studio fiscal year end.
Calculate OmnisFiscalYrEnd as getfye()

This affects fiscal kDateConstants such as:

kMonthofQuarter, kWeekofQuarter, kDayofQuarter

Warning

The fiscal year related date functions depend on the current Omnis Studio fiscal year end date. If your code makes use of the fiscal year date functions you must be careful to always set the Omnis Studio fiscal year end when you startup your application, or if the user can switch from one company to another company with different fiscal year ends within the same session of Omnis Studio.

Omnis Studio also has a fiscal year end date stored in each library's preference property.

; Each library has a $fiscalyearend property.
Calculate LibraryFiscalYrEnd as $clib.$prefs.$fiscalyearend()

  1. Select any library in the F2 Browser.
  2. Press F6 to open the Property Manager.
  3. Click the Prefs tab, and look for the $fiscalyearend property.

You can use notation to set the library fiscal year end property.

; Set the $fiscalyearend property for the current library.
Calculate LibraryFiscalYrEnd as dat('31-JAN-1900','D-m-Y')
Do $clib.$prefs.$fiscalyearend.$assign(LibraryFiscalYrEnd)

; Check the library fiscal year end property.
Calculate LibraryFiscalYrEnd as $clib.$prefs.$fiscalyearend()

setws()

SET WEEK START

setws(kDayConstant)

Sets the beginning of the week to a particular day, using one of the day of the week datepart constants.

The day of the week is returned as one of the datepart constants: kSunday, kMonday, kTuesday, kWednesday, kThursday, kFriday, kSaturday.

Set Week Start

setws(kDayConstant)

Sets the beginning of the week to a particular day. The datepart constants must be one of the following: kSunday, kMonday, kTuesday, kWednesday, kThursday, kFriday, kSaturday.

; Set the current (global) Omnis Studio week start day.
Do setws(kSunday)

; Check the Omnis Studio week start.
Calculate WeekStart as getws()

Omnis Studio also has a week start stored in each library's preference property.

; Each library has a $weekstart property.
Calculate LibraryWeekStart as $clib.$prefs.$weekstart()

  1. Select any library in the F2 Browser.
  2. Press F6 to open the Property Manager.
  3. Click the Prefs tab, and look for the $weekstart property.

You can use notation to set the library week start property.

; Set the $weekstart property for the current library.
Do $clib.$prefs.$weekstart.$assign(kSunday)

; Check the library fiscal year end property.
Calculate LibraryWeekStart as $clib.$prefs.$weekstart()

tim()

tim(StringOrNumber,[Format])

Convert a string or number to a time format.

The time format will default to the current #FT format, unless you specific a format in the 2nd parameter.

It is pretty hard to mess up the tim() function. You can send it '17:30' or '5:30 PM' and it works for any #FT setting.

; Check the Omnis Studio week start.
Calculate ShortTimeVar as tim('5:30 PM')
Calculate ShortTimeVar as tim('17:30')

FileOps

FileOps

stands for File Operations.

In Omnis Studio you can do file operations using the FileOps functions or the FileOps external.

The FileOps external is use for reading and writing file contents. For information on the FileOps External section listed under the Externals subject.

This section provided explanations and demos of the various FileOps functions.

To view all of the FileOps functions:

  1. Press F9 to open the Catalog.
  2. Click the Functions tab.
  3. Click FileOps in column one. All of the FileOps functions are displayed in column two.

    If you hover or one of the FileOps functions a tooltip tip appears providing you with the syntax and a short description of the function.
Tip

You can drag and drop any of the functions into your code. Omnis Studio conveniently copies the function and parameter names into your code.

Many of the FileOps functions require FileOps contants values (e.g. kFileOpsInclFiles, kFileOpsInfoFullName).

To find the FileOps constants:

  1. Press F9 to open the Catalog.
  2. Click the Constants tab.
  3. Click FileOps in column one. A list of the available FileOps constants will be displayed in column 2.
Tip

If your are entering code in the code editor, you can drag and drop or double-click on any of the constants in the F9 Catalog. Omnis Studio will copy the constant to your code.

Error Codes

A number of the FileOps functions return an error code. If the error code is a non-zero value, an error has occurred.

Omnis Studio provides a list of the possible FileOps error codes in the F1 Help. For example:

However, Omnis Studio does not provide a way to get the error code text from within Omnis Studio.

I created a $retFileOpsErrorText method which returns the error text for each of the known FileOps error codes. The method code is as follows:

; $retFileOpsErrorCodeText method.

Switch pErrorCode
   Case kFileOpsOK ;; 0
      Quit method '' ;; No Error
   Case kFileOpsNoOperation ;; 999
      Quit method 'Operation not supported on this platform'
   Case kFileOpsUnknownError ;; 998
      Quit method 'Unknown error'
   Case kFileOpsOutOfMemory ;; 12
      Quit method 'Out of memory'
   Case kFileOpsParamError ;; 1
      Quit method 'Too few parameters passed'
   Case kFileOpsDirFull ;; -33
      Quit method 'File/Directory full'
   Case kFileOpsDiskFull ;; -34
      Quit method 'Disk full'
   Case kFileOpsVolumeNotFound ;; -35
      Quit method "Specified volume doesn't exist"
   Case kFileOpsDiskIOError ;; -36
      Quit method 'Disk I/O error'
   Case kFileOpsBadName ;; -37
      Quit method "Bad file name or volume name (perhaps zero-length)"
   Case kFileOpsFileNotOpen ;; -38
      Quit method "File not open"
   Case kFileOpsEndOfFile ;; -39
      Quit method "Logical end-of-file reached during read operation"
   Case kFileOpsPositionBeforeStart ;; -40
      Quit method "Attempt to position before the start of the file"
   Case kFileOpsTooManyFilesOpen ;; -42
      Quit method "Too many files open"
   Case kFileOpsFileNotFound ;; -43
      Quit method "File not found"
   Case kFileOpsHardwareVolumeLock ;; -44
      Quit method "Volume is locked by a hardware setting"
   Case kFileOpsFileLocked ;; -45
      Quit method "File is locked"
   Case kFileOpsSoftwareVolumeLock ;; -46
      Quit method "Volume is locked by a software flag"
   Case kFileOpsMoreFilesOpen ;; -47
      Quit method "One or more files are open"
   Case kFileOpsAlreadyExists ;; -48
      Quit method "A file with the specified name already exists"
   Case kFileOpsAlreadyWriteOpen ;; -49
      Quit method "Only one access path a file can allow writing"
   Case kFileOpsNoDefaultVolume ;; -50
      Quit method "No default volume"
   Case kFileOpsVolumeNotOnline ;; -53
      Quit method "Volume not on-line"
   Case kFileOpsPermissionDenied ;; -54
      Quit method "Permission denied"
   Case kFileOpsReadOnlyFile ;; -54? Error in F1 Help documentation?
      Quit method "Read only file"
   Case kFileOpsVolumeAlreadyMounted ;; -55
      Quit method "Specified volume is already mounted and on-line"
   Case kFileOpsBadDrive ;; -56
      Quit method "No such drive number"
   Case kFileOpsInvalidFormat ;; -57
      Quit method "Volume lacks Macintosh-format directory"
   Case kFileOpsExternalSystemError ;; -58
      Quit method "External file system error"
   Case kFileOpsProblemDuringRename ;; -59
      Quit method "Problem during rename"
   Case kFileOpsBadMasterBlock ;; -60
      Quit method "Master directory block is bad; must re-initialize volume"
   Case kFileOpsCantOpenLockedFile ;; -61
      Quit method "Cannot open a locked file"
   Case kFileOpsDirectoryNotFound ;; -120
      Quit method "Directory not found"
   Case kFileOpsTooManyDirOpen ;; -121
      Quit method "Too many working directories open"
   Case kFileOpsCantMoveToOffspring ;; -122
      Quit method "Attempted to move into offspring"
   Case kFileOpsNonHFSOperation ;; -123
      Quit method "Attempt to do HFS operation on a non-HFS volume"
   Case kFileOpsInternalSystemError ;; -127
      Quit method "Internal file system error"
   Default
      Quit method con("Undocumented FileOps error code ",pErrorCode)
End Switch

In StudioTips I have copied the above code to the oFunctions object which is instantiated using the task variable, fn, of the Startup_Task. I can then call the method from anywhere in my code as follows:

; Get the error text for the error code from oFunctions.
Do fn.$retFileOpsErrorText(ErrorCode) Returns ErrorText

You may want to do something similar in your own application. Instead of prompting the user with an error message that says "File operations error -48 occurred", you can provide a more informative prompt like, "File Operations error. A file with the specified name already exists.".

Platform Sensitive Path Delimiter

sys(9)

returns the platform sensitive path delimiter.

Use sys(9) where applicable can help make your FileOps code platform independent.

; Calculate the file path name.
Calculate Path as con('DriveName',sys(9),'FolderName',sys(9),'FileName','.txt')

Uppercase File Paths

The Windows platform really used uppercase file paths. You need to be aware of this when writing any file operations related methods.

Using the replace() function on a file name, file path, or folder path is not a good idea.

The following line of code might work on the Mac and Linux platforms, but it will likely fail on the Windows platform.

Calculate NewPath as replace(OldPath,"Modules","Libraries")

One work around for Windows is to include the upp() or low() function... but then the NewPath which you calculate might not work for the Linux platform which is case-sensitive with respect to file paths.

In the above example a better way to replace "Modules" with "Libaries" in the OldPath is to find the position of the text in the path, and then replace the "Modules" with "Libraries" using the mid() function.

$changeworkingdir

Change Working Directory

Do FileOps.$changeworkingdir(Path) Returns ErrorCode

Changes the current working directory to the directory specified by Path. $changeworkingdir() only switches between folders on the same drive, not between drives.

The function returns an error number, or zero if successful.

Warning

Applications on Mac OS X do not have a working directory. If you use this function on Mac OS X, it returns the error code kFileOpsNoOperation ('999').

$converthsfpathtoposix

Do FileOps.$converthfspathtoposixpath(HfsPath,PosixPath)

Converts an HFS file path to a unix file path. The function returns an error number, or zero if successful.

$convertposixpathtohfs

Do FileOps.$convertposixpathtohfspath(PosixPath,HfsPath)

Converts unix file path to an HFS file path. The function returns an error number, or zero if successful.

$copyfile

Do FileOps.$copyfile(PathFrom,PathTo) Returns ErrorCode

Copies the file specified in PathFrom to the new location in PathTo

You can use this function to copy and rename the specified file to the same folder or a different location. The file named in PathTo should not already exist.

The function returns an error number, or zero if successful.

$createdir

Do FileOps.$createdir(Path) Returns ErrorCode

Creates the folder specified in path. The folder named in path must not already exist. The function returns an error number, or zero if successful.

$createdir() does not create intervening folders, it only creates the last folder named in path, therefore the intervening folders should already exist.

The following sample code can be used to automatically create intervening folders for a specified path.

; Calculate a path to a new preferences/studiotips folder inside the Omnis folder.
Calculate Path as sys(115)
Calculate Path as con(Path,'preferences',sys(9),'studiotips',sys(9))

; Split the path and then loop through the folders path checking each directory.
Do FileOps.$splitpathname(Path,Drive,FoldersPath,FileName,Ext) Returns ErrorCode

; Loop through the folders path checking to make sure each directory exists.
Calculate CheckPath as Drive
Calculate FoldersPath as trim(FoldersPath,kTrue,kTrue,sys(9))
Calculate ErrorCode as 0 ;; Preset to zero.
While len(FoldersPath)
   
   Calculate NextDir as strtok('FoldersPath',sys(9))
   Calculate CheckPath as con(CheckPath,sys(9),NextDir)
   
   ; Does the directory exists?
   If not(FileOps.$doesfileexist(CheckPath))
      
      ; Create the intervening directory.
      Do FileOps.$createdir(CheckPath) Returns ErrorCode
      If ErrorCode
         Break to end of loop
      End If
      
   End If
End While
If ErrorCode
   OK message (Icon) {The error code [ErrorCode] occurred when attempting to create the following directory:////[CheckPath]}
End If

$deletefile

Do FileOps.$deletefile(Path) Returns ErrorCode

Deletes the file or folder named in path. Files deleted are not moved into the Recycled bin or Trash can, they are deleted irreversibly. You can delete a folder with $deletefile(), but only if the directory is empty.

The function returns an error number, or zero if successful.

See the topic deleteDirectory in this section for code which drills down and deletes all the files and subdirectories of a directory and then delete the directory.

$doesfileexist

Does File or Directory Exist

Do FileOps.$doesfileexist(Path) Returns bFileExists

Returns true if the file or folder named in path exists.

$filelist

File List

Do FileOps.$filelist(kFileOpsInclConstants,TargetPath[,kFileOpsInfoConstants]) Returns List

Returns a list of files and/or directories inside the specified target path.

The kFileOpsInclConstants begin with kFileOpsIncl...

The kFileOpsInfoConstants begin with kFileOpsInfo...

; Get a list of the files in the target directory.
Do FileOps.$filelist(kFileOpsIncludeFiles,TargetPath) Returns List

; Get list of the files in the target directory. Include the date created & size.
Do FileOps.$filelist(kFileOpsIncludeFiles,TargetPath,kFileOpsInfoCreated+kFileOpsInfoSize) Returns List

; Get a list of the folders in the target directory.
Do FileOps.$filelist(kFileOpsIncludeDirectories,TargetPath) Returns List

; Get a list of the files and directories in the directory specified by Path
Do FileOps.$filelist(kFileOpsIncludeFiles+kFileOpsIncludeDirectories,TargetPath) Returns List

; Get a list of the volumes (drives) on the startup drive by Path
Do FileOps.$filelist(kFileOpsIncludeVolumes,TargetPath) Returns List

$getfileinfo

Get File Info

FileOps.$getfileinfo(Path,kFileInfoConstants) Returns FileInfoList

The kFileOpsInfoConstants begin with kFileOpsInfo...

Do FileOps.$getfileinfo(Path,kFileOpsInfoName+kFileOpsInfoCreated+kFileOpsInfoSize) Returns List

$getfilename

Get File Name

FileOps.$getfilename(Path[,Prompt,Filter,InitialDirectory]) Returns bFileSelected

Prompts the user to select a file and sets the Path variable to the selected file path. Returns true if the user selected a file.

The following sample code is used for the demo for this tip.

Calculate Title as 'Select an Omnis Studio library'
Calculate Filter as 'Omnis Studio (*.lbs)|*.lbs'

; $getfilename(Path[,Prompt,Filter,InitialDirectory])
Do FileOps.$getfilename(Path,Title,Filter) Returns bFileSelected
If bFileSelected
   OK message (Icon) {The path to the file you selected is:////[Path]}
Else
   OK message (Icon) {No file was selected.}
End If

Quit method kTrue

You can have multiple filters. The filter consists of a pipe delimited string.

Calculate Title as 'Select an xlv, txt, or csv file'
Calculate Filter as 'Excel (*.xlv)|*.xlv|Text (*.txt)|*.txt|CSV (*.csv)|*.csv'

; $getfilename(Path[,Prompt,Filter,InitialDirectory])
Do FileOps.$getfilename(Path,Title,Filter) Returns bFileSelected
If bFileSelected
   OK message (Icon) {The path to the file you selected is:////[Path]}
Else
   OK message (Icon) {No file was selected.}
End If

Quit method kTrue

$getunixpermissions

Do FileOps.$getunixpermissions(Path) Returns Path

Returns the Unix permissions string for the file identified by the specified path.

$getworkingdir

Get Working Directory

Do FileOps.$getworkingdir() Returns Path

Returns the current working directory.

Warning

Applications on Mac OS X do not have a working directory. If you use this function on Mac OS X, it returns an empty path.

$movefile

Move File

Do FileOps.$movefile(PathFrom,PathTo) Returns ErrorCode

Moves the file specified at PathFrom to the new location at PathTo. The file named in PathTo should not already exist. The function returns an error number, or zero if successful

You can use this function to move and rename the specified file.

$parentdir

Parent Directory

Do FileOps.$parentdir(Path) Returns ParentDirPath

Returns the path to the parent directory of the specified file path or folder path.

$putfilename

Put File Name

FileOps.$putfilename(Path[,PromptTitle,Filter,InitialPath]) Returns bFileSpecified

Opens the Save dialog with the specified file name and the file name as the value of Path.

If the user clicks Save, FileOps calculates Path as the full path including the file name and extension as entered by the user, and returns true. If the user clicks Cancel false is returned.

The following sample code is used for the demo for this tip.

Calculate Title as 'Save file as'
Calculate Path as 'FileOpsDemo.txt'
Do FileOps.$putfilename(Path,Title) Returns bFileSpecified
If bFileSpecified
   OK message (Icon) {You specified to save a file at:////[Path]}
Else
   OK message (Icon) {You did not specify a file path.}
End If

Tip

The prompt window defaults the Save As entry field to the value of Path so if you want to suggest a file name and extension to the user, calculate the file name and extension to Path before the $putfilename.

$readentirefile

Do FileOps.$readentirefile(Path,BinVar) Returns ErrorCode

Reads the entire file identified by path into the binary variable. The function returns an error code, or zero if successful.

When called on Mac OS, the data read into variable includes the Mac OS resource fork and file type information. On return, the value in variable has the following format:

  1. 12 byte header containing the Type (4 bytes), Creator (4 bytes), and Data fork size (4 bytes).
  2. Data fork information.
  3. Resource fork information.

The size of the data fork determines where the resource fork data is stored.

Under Windows and Unix, the Type defaults to ÔTEXTÕ, the Creator to ÔmdosÕ, and the resource fork is empty.

$rename

Rename File or Directory

Do FileOps.$rename(OldPath,NewPath) Returns ErrorCode

Renames the file or directory specified by the paths. The function returns an error number, zero if successful.

$selectdirectory

Select Directory

Do FileOps.$selectdirectory(Path[,Title,InitialDirectory]) Returns bDirSelected

Opens the select directory dialog with the specified title. Returns true and calculates Path as the full path of the directory selcted by the user. Returns false if the user click the Cancel button.

The following sample code is used for the demo for this tip.

Calculate Title as 'Select a folder'
Do FileOps.$selectdirectory(Path,Title) Returns bDirSelected
If bDirSelected
   OK message (Icon) {Path to the directly selected is:////[Path]}
Else
   OK message (Icon) {Directory not selected.}
End If
Quit method kTrue

$setfileinfo

Set File Info

Do FileOps.$setfileinfo(FilePath,kFileInfoConstant,Value,...) Returns ErrorCode

Sets the file info for the specified file and kFileInfo... constant to the specified value. You can include a series of constants and values.

Not all kFileOpsInfo... constants can be set. e.g. kFileInfoCreated, kFileInfoModified, kFileInfoSize can not be set.

; Set the file to read-only.
Do FileOps.$setfileinfo(Path,kFileOpsInfoReadOnly) Returns ErrorCode

; Sets the file to hidden.
Do FileOps.$setfileinfo(kFileOpsInfoHidden,kTrue) Returns ErrorCode

; Set the file to read-only and hidden.
Do FileOps.$setfileinfo(Path,kFileOpsInfoReadOnly,kTrue,kFileOpsInfoHidden,kTrue) Returns ErrorCode

$setunixpermissions

Calculate Permissions as '-rw-r--r--'
Do FileOps.$setunixpermissions(Path,Permissions) Returns Path

Sets the Unix permissions for the specified file.

$splitpathname

Split Path Name

Do FileOps.$splitpathname(Path,Drive,FolderPath,FileName,Ext) Returns ErrorCode

Splits the specified path into drive-name, directory-name, file-name, and file-extension. The path can be to a file or a directory.

The FolderPath includes preceeding and trailing path delimiters. The function returns an error number, or zero if successful.

Warning

If the path is a directory it must include the trailing path delimiter for $splitpathname to work correctly. If the trailing path delimiter is missing, the last directory in the path will be parsed as the FileName.

$writeentirefile

Do FileOps.$writeentirefile(Path,BinVar) Returns ErrorCode

Creates and writes the entire file identified by path, using the data supplied in the binary variable. The function returns an error code, or zero if successful.

If the file already exists, $writeentirefile() replaces it. The value in variable must have the following format:.

When called on Mac OS, the data read into variable includes the Mac OS resource fork and file type information. On return, the value in variable has the following format:

  1. 12 byte header containing the Type (4 bytes), Creator (4 bytes), and Data fork size (4 bytes).
  2. Data fork information.
  3. Resource fork information.

The size of the data fork determines where the resource fork data is stored.

Under Windows and Unix, the resource fork is not written.

deleteDirectory

See the topic deleteDirectory in this section for code which will drill down and delete all the files and subdirectories and then delete the directory.

The following sample code can be used to delete a directory which is not empty. The method will drill down deleting enclosed files and folders. Be careful with this method, it could be used to irreversibly delete all folder and files from a drive.

; This sample code is for a custom 'deleteDirectory' method.
; The method deletes a directory including all the contained files and subdirectories.

; The target directory path is passed in as the parameter 'pTargetDirPath'

; Make a list of any files inside the target directory.
Do FileOps.$filelist(kFileOpsIncludeFiles,pTargetDirPath,kFileOpsInfoFullName) Returns FilesList

; Loop through the list deleting each file.
For FilesList.$line from 1 to FilesList.$linecount step 1
   
   Calculate Path as FilesList.fullname
   Do FileOps.$deletefile(Path) Returns ErrorCode
   If ErrorCode
      OK message (Icon) {Error code [ErrorCode] occured while attempting to delete the file at:////[Path]}
      Break to end of loop
   End If
   
End For
If not(ErrorCode)
   
   ; Make a list of any directories inside the target directory.
   Do FileOps.$filelist(kFileOpsIncludeDirectories,pTargetDirPath,kFileOpsInfoFullName) Returns FilesList
   
   ; Loop through the list deleting directory and contents by calling this method.
   For FilesList.$line from 1 to FilesList.$linecount step 1
      
      Calculate Path as FilesList.fullname
      Do method deleteDirectory (Path) Returns ErrorCode
      If ErrorCode
         ; The called method already reported the error.
         Break to end of loop
      End If
      
   End For
   If not(ErrorCode)
      
      ; Delete the specified target directory.
      Do FileOps.$deletefile(pTargetDirPath) Returns ErrorCode
      If ErrorCode
         OK message (Icon) {Error code [ErrorCode] occured while attempting to delete the directory at:////[Path]}
      End If
   End If
End If
Quit method ErrorCode

kFileOpsInfoCreatorCode

The file creator code is a MacInstosh operating system only property. The creator code specifies the which application opens the file if the user double-clicks on the file to open it. It also affects the icon displayed for the file in the Finder.

Mac OS 9 does not require file extensions so the creator code is important to Mac OS 9 if the file does not have an extension.

Common creator codes are as follows:

  1. Adobe Acroat: CARO
  2. Excel : XCEL
  3. Word: MSWD
Tip

For cross-platform compatability (Win/Mac OS 9, Mac OS X) having the correct the file extension is the most important thing to do. Windows and Mac OS X set the file's icon and application based on the file extension. Mac OS 9 sets the application based on the file extension.

On Mac OS X the creator code can override the file extension mapped application. The file extension .pdf might be mapped to Preview, but if the creator is set to CARO the file's icon and application will point to Adobe Acrobat.

On Mac OS 9 if the creator code is not set the file's icon is will not be set, even if the file extension is set and mapped to an application.

kFileOpsInfoTypeCode

The file type code is a MacIntosh operating system only property. The type code controls which application opens the file if the user double-clicks on the file to open it.

Mac OS 9 does not require file extensions so the type code is important to Mac OS 9 if the file does not have an extension.

If the file has an extension that is listed in the Mac OS 9 Apple menu > Control Panels > File Exchange > PC Exchange tab, and Open unmapped files is checked, the application mapped to the file extension will be used to open the file.

On Mac OS X if the file has a recognizable extension the file will be opened with the application that is mapped to the extension. If the file does not have an extension, or one that is not recongnized by Mac OS X, then the file is opened with the application mapped to the type code if one is found.

Common type codes are as follows:

  1. PDF: 'PDF ' (Excluding the single quotes. Note the trailing space character!)
  2. Text: TEXT
  3. Tif: TIFF

The type codes for Word and Excel files seem to include the application version. (e.g. W8BN, XLS8) It is better to set the creator code than the type code for Word and Excel files.

Setting the type code on Mac OS 9 files is less important than setting the file extension and creator code.

On Mac OS X setting the type code and leaving the creator code blank lets the file be opened by the user's preferred application for the file type. (e.g. Setting the type code to 'PDF ' and leaving the creator code blank allows the Mac OS X to open the PDF in the user's preferred PDF viewer - Preview or Adobe Acrobat. The only reason for setting the type code on Mac OS X is so that the file type isn't lost if the user removes the file extension or doesn't include a file extension when the file is created.)

FontOps

The FontOps function let you calculate the size in pixels of text displayed in windows and size in inches or cms of text displayed in reports.

To view all of the FontOps functions:

  1. Press F9 to open the Catalog.
  2. Click the Functions tab.
  3. Click FontOps in column one. All of the FontOps functions are displayed in column two.

    If you hover or one of the functions a tooltip tip appears providing you with the syntax and a short description of the function.
Tip

You can drag and drop any of the functions into your code. Omnis Studio conveniently copies the function and parameter names into your code.

$replistfonts

Do FontOps.$replistfonts(List) Returns ErrorCode

Populates the specified list with the report fonts installed on your system, and indicates whether or not they are truetype. The list must contain two columns, the first character type, the second boolean. The function returns zero for success, less than zero for failure. Having built the list you can search and manipulate the list using the standard list functions and methods.

; Define the fonts list.
Do FontsList.$cols.$add('font',kCharacter,kSimplechar,100)
Do FontsList.$cols.$add('istruetype',kBoolean)

; Populate the fonts list with the fonts listed in the system class #WIWFONTS
Do FontOps.$replistfonts(FontsList) Returns ErrorCode
If ErrorCode
   OK message (Icon) {Error code: [ErrorCode]}
Else
   OK message (Icon) {There are [FontsList.$linecount] report fonts listed in your system.////The first font in the list is '[FontsList.1.font]'.////The last font in the list is '[FontsList.[FontsList.$linecount].font]'.}
End If

$reptextheight

Do FontOps.$reptextheight(font-name|font-table-index,point-size[,font-style,extra-points]) Returns Height

Returns the height in report units of the specified report font. You specify the font using either the font-name or font-table-index. When called with a font table index. $reptextheight() uses the window font system table of the current library which can be of the font. You can include a font-style constant and a number of extra-points.

; FontOps.$reptextheight(font-name|font-table-index,point-size[,font-style,extra-points])
Calculate FontName as 'Arial'
Do FontOps.$reptextheight(FontName,8) Returns Height
Do FontOps.$reptextheight(FontName,12,kItalic,2) Returns Height
Do FontOps.$reptextheight(FontName,72,kBold+kUnderline) Returns Height

$reptextwidth

Do FontOps.$reptextwidth(string, font-name|font-table-index,point-size[,font-style]) Returns Width

Returns the width in report units required to display the string using the specified report font. You specify the font using either the font-name or font-table-index. When called with a font table index, $reptextwidth() uses the report font system table of the current library which can contain up to 15 fonts numbered 1 to 15. You can include a font-style constant, or a combination of styles.

Calculate String as "Hello World!"
Calculate FontName as 'Arial'
; FontOps.$reptextwidth(string, font-name|font-table-index,point-size[,font-style])
Do FontOps.$reptextwidth(String,FontName,8) Returns Width
Do FontOps.$reptextwidth(String,FontName,12,kItalic) Returns Width
Do FontOps.$reptextwidth(String,FontName,72,kBold+kUnderline) Returns Width

$winlistfonts

Do FontOps.$winlistfonts(List) Returns ErrorCode

Populates the list with the window fonts installed on your system, and indicates whether or not they are truetype. The list must contain two columns, the first character type, the second boolean.

The function returns zero for success, less than zero for failure. Having built the list you can search and manipulate the list using the standard list functions and methods.

; Define the fonts list.
Do FontsList.$cols.$add('font',kCharacter,kSimplechar,100)
Do FontsList.$cols.$add('istruetype',kBoolean)

; Populate the fonts list with the fonts listed in the system class #WIWFONTS
Do FontOps.$winlistfonts(FontsList) Returns ErrorCode
If ErrorCode
   OK message (Icon) {Error code: [ErrorCode]}
Else
   OK message (Icon) {There are [FontsList.$linecount] window fonts listed in your system.////The first font in the list is '[FontsList.1.font]'.////The last font in the list is '[FontsList.[FontsList.$linecount].font]'.}
End If

$wintextheight

Do FontOps.$wintextheight(font-name|font-table-index,point-size[,font-style,extra-points]) Returns Height

Returns the height in screen units of the specified window font. You specify the font using either the font-name or font-table-index. When called with a font table index, $wintextheight() uses the window font system table of the current library. You can include font-style constants and a number of extra-points.

; FontOps.$wintextheight(font-name|font-table-index,point-size[,font-style,extra-points])
Calculate FontName as 'Arial'
Do FontOps.$wintextheight(FontName,8) Returns Height
Do FontOps.$wintextheight(FontName,12,kItalic,2) Returns Height
Do FontOps.$wintextheight(FontName,72,kBold+kUnderline) Returns Height

$wintextwidth

Do FontOps.$wintextwidth(string, font-name|font-table-index,point-size[,font-style]) Returns Width

Returns the width in screen units required to display the string using the specified window font. You specify the font using either the font-name or font-table-index. When called with a font table index, $wintextwidth() uses the window font system table of the current library. You can include font-style constants.

Calculate String as "Hello World!"
Calculate FontName as 'Arial'
; FontOps.$wintextwidth(string, font-name|font-table-index,point-size[,font-style])
Do FontOps.$wintextwidth(String,FontName,8) Returns Width
Do FontOps.$wintextwidth(String,FontName,12,kItalic) Returns Width
Do FontOps.$wintextwidth(String,FontName,72,kBold+kUnderline) Returns Width

String Functions

This section provided explanations and demos of the various string functions in Omnis Studio.

To view all of the string functions:

  1. Press F9 to open the Catalog.
  2. Click the Functions tab.
  3. Click String in column one. All of the string functions are displayed in column two.

    If you hover or one of the string functions a tooltip tip appears providing you with the syntax and a short description of the function.
Tip

You can drag and drop any of the functions into your code. Omnis Studio conveniently copies the function and parameter names into your code.

Tip

If your are entering code in the code editor, you can drag and drop or double-click on any of the constants in the F9 Catalog. Omnis Studio will copy the constant to your code.

asc - ASCII

asc(String,CharNum)

Returns the ASCII value of a character in a string. The position of the character is specified by CharNum. The value returned is between 0 and 255, or -1 if number is less than 1 or greater than the length of string.

; asc(string,number)
Calculate Ascii as asc('Quantity',1)

cap - Capitalize

cap(String)

Returns the capitalized representation of a string. The first letter of each and every word in the string will capitalized, the rest of the letters of each work will be lower case.

; cap(String)
Calculate CapString as cap('gRaVeS, hutton, MONKS')

chk - Check

chk(string1,string2,string3)

Returns true or false depending on a character-by-character comparison of string1 with string2 and string3 using the ASCII value of each character for the basis of the comparison.

Firstly, each character of string2 is compared with the corresponding character of string1 to ensure that, for each character, string2<=string1. A character is said to be less than or greater than another character if its ASCII code is less than or greater than the ASCII code of the corresponding character.

Secondly and provided string2<=string1, each character of string1 is compared with the corresponding character of string3 to ensure that, for each character, string1<=string3.

If both conditions are true, that is string2<=string1 and string1<=string3 are both satisfied, the function returns true, otherwise it returns false.

; Is 'b' >= '' and <= 'c'?
Do chk('b','','c') Returns FlagOK ;; Returns true.

; Is 'B' >= 'B' and <= 'C'?
Do chk('B','B','C') Returns FlagOK ;; Returns true.

; Is 'SD04' >= 'AA00' and <= 'ZZ99'?
Do chk('SD04','AA00','ZZ99') Returns FlagOK ;; Returns true.

; Is 'SDA4' >= 'AA00' and <= 'ZZ99'?
Do chk('SDA4','AA00','ZZ99') Returns FlagOK ;; Returns false.

chr - Characters

chr(CSVAsciiNumbers)

Returns a string by converting ASCII codes to characters. Any argument with a value less than zero or greater than 255 is ignored.

Only normal printable characters should be stored in Character or National fields. Also, since Omnis uses the character with ASCII value 0 as the end of string marker, this means that if you use this character in any other way, the part of the string following the 0 value is ignored.

Control characters in the data file may also cause problems when trying to import or export data.

Records with index fields which contain characters with ASCII value 255 may not have the correct index order. It is safe, however, to have unprintable characters in the text for the Transmit text commands.

Note

The lower ASCII values are non-visible characters. e.g. kCr=13, kTab=9, kLf=10

Click the Run Demo button in the StudioTips Browser window to view the ASCII characters from 1-255.

The following sample code is used to build the list for the demo.

; Define the list.
Do List.$define()
Do List.$cols.$add('asciivalue',kInteger,kLongint)
Do List.$cols.$add('character',kCharacter,kSimplechar,10)

; Loop through the ascii characters from 1 to 255 building the list.
For Counter from 1 to 255 step 1
   Do List.$add(Counter,chr(Counter))
End For

; The list can now be viewed in a string grid or data grid.


con - Concatenate

con(string1,string2[,string3]...)

Returns a string by concatenating two or more string values. con() has a limit of 100 parameters.

Calculate FirstNameA as "Jack"
Calculate FirstNameB as "Jill"
Calculate LastName as "Hill"
Calculate FullName as con(FirstNameA," and ",FirstNameB," ",LastName)
; Results in "Jack and Jill Hill"

Note the use of spaces in the above example.

The pick() function can be useful in combination with con() where you only want a character or string included if the value of another string is not empty.

Calculate FirstNameA as "Jack"
Calculate FirstNameB as ""
Calculate LastName as "Hill"
Calculate FullName as con(FirstNameA," and ",FirstNameB," ",LastName)
; Results in "Jack and Hill"

; The pick() function can be used to decide whether or not to include ' and '.
Calculate FullName as con(FirstNameA,pick(FirstNameB<>"",""," and "),FirstNameB," ",LastName)
; Results in "Jack Hill"

decstr - Decode String

decstr(String,Key)

Decodes a string which was previously encoded using the encstr() function. If the key is omitted, Omnis uses its default value for the key.

; Set the key.
Calculate Key as 'MySecretKey'

; Encode the string.
Calculate Encode as encstr('piano',Key)

; Decode the encoded string.
Calculate Decode as decstr(Encode,Key)

encstr - Encode String

encstr(String,Key)

Encodes the string using the key. If key is omitted, Omnis uses its default value. The return value of encstr() is a string that is difficult to decode without knowing the key. To decode the string, and return the original value, use the decstr() function.

; Set the key.
Calculate Key as 'MySecretKey'

; Encode the string.
Calculate Encode as encstr('piano',Key)

; Decode the encoded string.
Calculate Decode as decstr(Encode,Key)

Tip

For tougher encryption see the Blowfish External under the Externals subject.

isnumber - Is Number

isnumber(String)

Returns true if the specified string can be evaluated as a number, otherwise false is returned.

; isnumber(String)
Calculate bNumber as isnumber('5,678.45')
Calculate bNumber as isnumber('123QRJ')
Calculate bNumber as isnumber('123 45')

jst - Justify

jst()

is a function with many uses.

Search the F1 Help for jst to see all the different possibilities.

Listed below are just a few examples of some of things you can do with the jst() function.

; Today's date in the format: 'Saturday, 29th November 2010'
Calculate DateString as jst(#D,'D:w, d n y')
Calculate DateString as jst(#D,'D:y-M-D') ;; Return format YYYY-DD-MM

; Current time formated different ways.
Calculate TimeString as jst(#T,'T:h:N A') ;; Return format '2:07 PM'

Calculate TimeString as jst(#T,'T:H-N') ;; Return format '14-07'


; PcÊpads the part of the field not filled by the data to be filled by specified character.
Calculate LeftPadString as jst('abc','-5P*') ;; Returns '**abc'
Calculate RightPadString as jst('abc','10P~') ;; Returns '**abc'

Calculate ValueString as jst(Value,'A') ;; Returns 'NULL' when Value is null



Calculate TruncateString as jst('abcdef','4X') ;; Returns 'abcd'

left - Left

left(String,Length)

The left() function returns a substring of specified length, starting at the beginning of the specified string.

Calculate LeftString as left('The fox jumped',7)

len - Length

len(String)

Returns the length of a string, that is, number of characters.

Calculate Length as len('Hello World!')

low - Lowercase

code>low(String)

Returns the lower case representation of a string. Any non-alphabetic characters in the strings are unaffected by low().

Calculate String as low('Hello World!')

mid - Mid

mid(String,Position,Length)

Returns a substring of a specified length, starting at a specified position, from a larger string.

If Position is less than 1 it is taken as 1. If Position is greater than the length of the string, an empty string is returned.

If Length is not included, or is greater than the maximum length of any substring of string starting at position, the returned substring will be the remainder of string starting at Position.

mid('Information',6,3) ;; returns 'mat' int(mid(12.45,2,3)) ;; is the same as int('2.4'), returns 2
mid('interaction',6,24) ;; returns 'action'
mid('dog,cat,mouse',1,pos(",","dog,cat,mouse")-1) ;; returns 'dog'

natcmp - National Sort Compare

natcmp(Value1,Value2)

Returns the result of comparing two values using the national sort ordering. 0 if the strings are equal, 1 if Value1 > Value2, and -1 if Value 1 < Value2.

Both values are converted to strings before doing the comparison. Omnis uses the same rules for comparing the strings as it does for normal strings, except that it uses the national sort ordering.

pos - Position

pos(Substring,String)

Returns the position of a substring within a larger string. The substring must be contained within string in its entirety for the returned value to be non-zero. Also, the comparison is case sensitive and only the first occurrence of substring is returned. Use the low() function for case-insenstitive comparisons.

Calculate Posn as pos('Mouse','Mickey Mouse') ;; Returns 8
Calculate Posn as pos('mouse','Mickey Mouse') ;; Returns 0 case sensitive.
Calculate Posn as pos('mouse',low('Mickey Mouse')) ;; Returns 8. Note use of low()

replace - Replace

replace(source-string, target-string, replacement-string)

Replaces the first occurrence of the target-string, within the source-string, with the replacement-string. The replace() function returns the new string containing the changes, if any.

Calculate String as 'Joe Smith'
Calculate NewString as replace(String,'Joe','John') ;; Returns 'John Smith'

replaceall - Replace All

replaceall(source-string, target-string, replacement-string)

Replaces all occurrences of the target-string, within the source-string, with the replacement-string. The replaceall() function returns the new string containing the changes, if any.

; To figure out the total width of a headed list from the $columnwidths.
Calculate ColWidths as '30,40,100,250'

; Replace the commas with + characters.
Calculate String as replaceall(ColWidths,",","+")

; Evaluate the string to calculate the total width.
Calculate TotalWidth as eval(String)

right - Right

right(string,length)

Returns a substring of specified length, starting from the end of the specified string.

Calculate String as "The Fox Jumped"
Calculate RightString as right(String,6) ;; Returns 'Jumped'

rpos - Right Position

rpos(Substring,String)

Returns the furthest right position of a substring within a larger string. The substring must be contained within string in its entirety for the returned value to be non-zero. Also, the comparison is case sensitive. Use the low() function to make the comparision case-insensitive.

Calculate String as "The fox jumped over the fence."

; Get the position of the last space in the string.
Calculate Posn as rpos(' ',String)

; Get the last word.
Calculate LastWord as mid(String,Posn+1)

strpbrk - String Pointer to Break

strpbrk(string1, string2)

Returns a substring of string1 from the point where any of the characters in string2 match string1.

Calculate String as "This is a test"
Calculate String as strpbrk(String,"absj") ;; returns "s a test"
Calculate String as strpbrk(String,"a") ;; returns "a test

strspn - String Span

strspn(string1, string2)

Returns the index of the first character in string1 that does not match any of the characters in the string2. The strspn() function computes the length of the maximum initial segment of the first string which consists entirely of characters in the second string. strspn() is case sensitive.

Calculate String as "This is a test"
Calculate Length as strspn(String,'aehit')
; Returns 1. "s" is missing, but the first letter "T" is upper case, so 1 is returned.

Calculate String as "This is a test"
Calculate Length as strspn(low(String),'aehit')
; Returns 4, the 's' character in 'This' Using the low() function on the string, makes the function case insensitive.

Calculate String as "This is a test"
Calculate Length as strspn(low(String),'aehist')
; Returns 5, the 'space' character.

Calculate String as "This is a test"
Calculate Length as strspn(low(String),' aehist')
; Returns 15. The length of 'This is a test' is 14. All characters match, so the index must be one greater than the length of the string.

; Using the low() function on the string, makes the function case insensitive. To test for an non-alpha character.

Calculate String as 'ABC3'
Calculate Length as strspn(low(String),'abcdefghijklmnopqrstuvwxyz')
; To test for an non-alphanumeric character.

Calculate String as 'ABC34%'
Calculate Length as strspn(low(String),'abcdefghijklmnopqrstuvwxyz0123456789')

strtok - String Tokenize

strtok('string1', string2)

Tokenizes string1, using string2 as the delimiter with which to tokenize. This function returns tokens which are a substring of string1 until any character in string2 matches a character in string1. When strtok() is called, the token found in string1 is removed, so that the function looks for the next token the next time it is called.

Warning

You must remember to enclose the string1 variable in quotes or the strtok() function will not work. e.g. 'String1'

The strtok() function is great for parsing strings!

; Parse a comma delimited string into a list.
Calculate CSVString as "fox,dog,cat,mouse"
Do List.$cols.$add('name',kCharacter,kSimplechar,1000)
While len(CSVString)
   
   Calculate SubString as strtok("CSVString",",")
   Do List.$add(SubString)
   
End While

; Parse a string from a text file with carriage returns into a list.
Calculate String as con("Line1",kCr,"Line2",kCr,"Line3")
Do List.$cols.$add('test',kCharacter,kSimplechar,100000)
While len(String)
   
   Calculate SubString as strtok("String",kCr)
   Do List.$add(SubString)
   
End While


style - Style

style(style-character[,value])

Inserts a style-character represented by an Omnis constant into a calculation. Depending on the style character, you can also specify a value, which itself can be a constant from the Text Escapes constants group. This function is particularly useful for formatting the columns of a headed list box field. You can insert an icon by specifying its ID, a center tab, right tab, left tab, a color value, or text property such as italic. For example, to format the columns in a headed list box you could use the following calculation:

con(Col1,style(kEscBmp,1756),kTab,Col2,style(kEscColor,kRed),kTab,Col3,style(kEscStyle,kItalic))

This gives Col1 a blue spot icon, Col2 is red, and Col3 italic.

trim - Trim

trim(string[,leading=kTrue,trailing=kTrue,character=space_char])

Removes the specified leading and/or trailing character from the string. You specify the character to be removed in the character argument. If this is omitted the space character is removed from the string by default. The character can only be a single character.

; Remove leading and trailing spaces.
Calculate String as trim(" this is a string with leading and trailing spaces ")

; Remove leading and trailing commas.
Calculate String as trim(",fox,cat,mouse,",kTrue,kTrue,",")

; Remove trailing path delimiter.
Calculate String as trim(FolderPath,kFalse,kTrue,sys(9))

; Remove trailing carriage returns and spaces.
Calculate String as trim(trim(String,kFalse,kTrue,kCr))

upp - Uppercase

upp(string)

Returns the upper case representation of a string.

Calculate String as upp("Hello World!")

; String functions can be combined.
Calculate String as trim(upp(mid("Hello World! ",1,5)))


retAlphaNumeric

The following is a custom method which removes non-alphanumeric characters from an input string.

The method uses the strspn() function to find the first non-matching character in the string, and then con() and mid() to remove the non-matching character from the string.

Calculate String as pString
Calculate Length as len(String)
If Length
   
   Repeat
      
      Calculate IllegalCharPosn as strspn(String,"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_")
      If IllegalCharPosn>Length
         Break to end of loop
      End If
      
      Calculate String as con(mid(String,1,IllegalCharPosn-1),mid(String,IllegalCharPosn+1))
      Calculate Length as Length-1
      
   Until break
   
End If
Quit method String

Sys Functions

The sys() functions are great, but getting at the list of them through F1 Help is a bit of a hassle.

This section provides you with documentation, tips, and demos for each of the sys() functions.

Also included are some undocumented sys() functions. See the bottom of the list.

Syntax: sys(number)

Returns information about the current system depending on a number argument.

Using the sys() functions, you can obtain system information such as the current printer name, the pathname of the current library, the screen width or height in pixels, etc.

sys(1) Omnis version #

Returns the Omnis version number.

sys(2) Omnis program type

Returns the Omnis program type byte:

sys(3) Company name

The company name entered on installation.

sys(4) Your name

Your name entered on installation.

sys(5) Omnis serial #

The Omnis serial number entered on installation.

sys(9) Pathname separator

Returns the pathname separator for the current platform:

sys(10) Library file pathname

Returns the pathname of the current library file.

You can also use notation: $clib().$pathname

sys(11,..,20) Data file pathnames

Returns the pathname(s) of the current open data file segment(s) (empty if none are open).

sys(21) Print file name

Returns the pathname of the current print file name (empty if not open).

sys(22) Import file name

Returns the pathname of the current import file name (empty if not open).

sys(23) Port name

Returns the current port name (empty if no port open).

sys(24) Report device

Returns the current report device, for example, Printer, Screen, Preview, File (Screen is the default).

sys(30,..,49) Menus installed

Returns the name of the installed user-defined menu(s) starting from the left-most menu (empty if none are installed).

You can also use notation to make a list of all the installed menus.

; Make a list of all the installed menus.
Do $imenus.$makelist($ref().$name) Returns List

sys(50,..,79) Windows open

Returns the name of the open user-defined window(s) starting with the top window (empty if none are open).

You can use notation to make a list of all the open windows.

; Make a list of all the open windows.
Do $iwindows.$makelist($ref().$name,$ref.$title) Returns List

sys(80) Report name

Returns the current report name (empty if no report set).

sys(85) Current method

Returns the name of currently executing method in the form ClassName/MethodName.

Note

You can not pass sys(185) as a square bracket parameter. It will continue to evaluate/change to the next currently executing method. You can't freeze sys(85) and pass it.

The solution I found was to pass $cmethod, receive it as an item reference parameter, and then evaluate the reference. (e.g. prMethod.$class().$name)

sys(86) Event parameters

Returns a list of event parameters for the current event. The first parameter is always pEventCode
containing an event code representing the event, for example, evClick for a click on a button: a
second or third event parameter may be supplied which tells you more about the event.

sys(90) Method Stack

Returns the number of methods on the method stack. This does not work for client requests running in a thread of the Multi-threaded Server.

You can use sys(90) at the beginning of a timer object method, to prevent it from interrupting other methods.

; Check if there are any other method running before running the timer method.
If sys(90)>1
   ; Do nothing
Else
   ; Run the timer triggered method/code.
End If

sys(91) Decimal separator

Returns the decimal separator.

sys(92) Thousand separator

Returns the thousand separator

sys(93) Parameter separator

Returns the parameter separator for calculations.

sys(94) Field name separator

Returns the file class field name separator.

sys(122) Web client listener

Returns true if the web client server communications listener started successfully; it returns false if listener startup failed, or has not yet occurred.

sys(185) Current method

Returns the name of currently executing method in the format:

Library name.class name/method name/Line number

Note

You can not pass sys(185) as a square bracket parameter. It will continue to evaluate/change to the next currently executing method. You can't freeze sys(185) and pass it.

sys(190) Classes loaded from disk

Returns the number of times Omnis has loaded a class from disk and added it to the memory class cache. See comments below in sys(191).

sys(191) Classes deleted from memory

Returns the number of times Omnis deleted a memory class cache entry, when it added a class to the cache, meaning that the class deleted from the cache may need to be reloaded.

sys(190) and sys(191) provide information you can use to monitor the impact of changing the preference $root.$prefs.$maxcachedclasses. Too low a value for this preference may result in a performance hit due to too many classes being repeatedly loaded from disk.

sys(192) Method Stack

The sys(192) function caters for both error handlers and other situations where information about the method stack might be useful. It returns a list representing the current method call stack (with a line for each line that would appear on the debugger stack menu). The first line in the list corresponds to the call to sys(192), and subsequent lines correspond to how the method running the previous line was called.

The list has the following columns:

  1. classitem - item reference to the class containing the method.
  2. object - the name of the object containing the method in the class; empty if it is a class method.
  3. method - the name of the method.
  4. line - the line number in the method, of the method line resulting in the method on the previous line running.
  5. linetext - the text for the method line.
  6. params - the parameters passed to the method. This is a two-column list, with columns name and value. The value is the value that would be displayed as a variable tooltip for the parameter.
  7. methoditem - item reference to the method.

sys(193) Trace log contents

Returns the contents of the trace log to a list. Available in both runtime and design mode. Useful for debugging runtime problems.

Send to trace log has an option, Diagnostic message. When this option is checked, the message will only be logged if the trace log is set to Log diagnostic messages. See F1 Help for more information.

sys(194) Open Windows

Generates a list of open window in the IDE. The list has columns as follows:

The current line is non-zero if and only if the window is the top design window, i.e. the top class editor or method editor window. When deciding the top design window, the catalog, component store, and property inspector are ignored.

sys(195) Selected Objects

Returns the list of selected objects, if there is a top design window (as defined by sys(194) above), and if the top design window is a window, report, toolbar, menu, or remote form editor (NOT a method editor).

The list has one column: objectitem - the item reference of the selected object

sys(196) VCS Build Properties

Returns the list of all open libraries (including private libraries) and their VCS build properties. The list has the following columns:

  1. name - the internal name of the library
  2. pathname - the pathname of the library file
  3. vcsbuildersname - the $vcsbuildersname property of the library
  4. vcsbuildnotes - the $vcsbuildnotes property of the library
  5. vcsbuilddate - the $vcsbuilddate property of the library

sys(198) Bind Web Client Port

Returns an integer which indicates the status of binding the web client server port number to the socket on which the server receives incoming connections.The value is -1 if bind has not been attempted yet, 0 if bind was successful, or a positive value (a socket layer error code) if the bind failed.

sys(199) Method Commands List

Returns a list with a row for each method command. The list has two columns:

  1. group - the command group
  2. command - the command name
These are all the Omnis commands. If, End if, Set report name, etc.

sys(204) Notation Methods

Returns a list with a row for each function. The list has three columns:

  1. group - the function group
  2. function - the function name
  3. description - the function description
These are all the functions listed in the F9 Catalog > Functions tab.

sys(205) Byte Ordering

Returns the byte ordering of the hardware. True (1) for big-endian machines, false (0) for little-endian machines.

sys(210) Number of Processors

Returns the number of processors for the current machine (depending on the information reported by the operating system, the value may not reflect logical processor cores).

sys(212) Sort Fields Executing

Returns the list of sort fields for the executing method stack. The list has the following columns:

  1. name - the name of the sort field
  2. descending - boolean, true if this field is sorted in descending order
  3. upper - boolean, true if this field is sorting of this field is case-insensitive
  4. subtotals - boolean, true if subtotals are printed when the sort field changes
  5. upper - boolean, true if a new page is started when the sort field changes
(I think this function applies to a report class instance when the report is being printed.)

sys(3000) Trace to file start

The first time you issue a sys(3000) during a session of Omnis Studio, Omnis creates a sequential log file that is named SEQLOG#.TXT, where # is a number. The file is created in the sys(115) directory. Each time you quit and restart Omnis Studio, the next time you issue a sys(3000) Omnis Studio will start a new trace log file. The file name will have the next sequential number appended to it. e.g. SEQLOGO.TXT, SEQLOGO1.TXT, SEQLOGO2.TXT

Omnis Studio then writes the trace log messages to that file.

The first time you issue a sys(3001) during a session of Omnis Studio, Omnis give you an OK message telling you the trace log file name. Subsquent uses of sys(3001) during the same session of Omnis Studio do not trigger the OK message.

The sys(3000) function is very useful thing if you have a procedure that crashes Omnis Studio. By issuing sys(3000) and then running the code which causes Omnis Studio to crash, you can then open the trace log file and get some hints as to when in your methods the crash is occurring.

Warning

If you delete the file with Omnis Studio still open and try to issue a sys(3000), Omnis will inform you that it can't find the file. Only delete the file after you quit Omnis Studio. To clear the trace file, open the file, select and delete all text and then close the file.

Note

The Send to trace log method does not work for sending text to the sys(3000) file trace log.

Click Run Demo in the StudioTips Browser to see how it works.

sys(3001) Trace to file stop

Stop trace to file.

See sys(3000) for more information.

sys(4019) Externals browser

Opens the External components Browser

sys() Loop

Loop through the sys functions. It's interesting what you can find out when you put sys(#) in a loop. :-)

; Loop through all the sys() functions.
For Num from 1 to 5000 step 1
   If len(sys(Num))>0
      Yes/No message Loop through sys() functions (Icon) {////sys([Num]) = [sys(Num)]////////Continue?}
      If flag false
         Break to end of loop
      End If
   End If
End For
Quit method kTrue

Click the Run Demo button in the StudioTips Browser if you want to loop through the all the sys functions. You can click No any time you want to stop the loop.

Sys Functions - Database

This section provides you with documentation, tips, and demos for each of data file and database related the sys() functions.

sys(81) Search name

Returns the current search name (empty if no search set).

sys(82) Main file name

Returns the main file name (empty if no main file set).

sys(83) Records in main file

Returns the number of records in main file.

sys(130) Server name

(Old DAMS only) Returns the server name for the current session.

For example, 'Oracle version [1.2Êr0]' (empty if no server connected).

sys(131) SQL error code

(Old DAMS only) Returns the SQL error code, or 0 for no error.

sys(132) SQL error text

(Old DAMS only) Returns the SQL error text for the current error code (empty if not available).

sys(133) SQL select table # columns

(Old DAMS only) Returns the number of columns for the current Select table.

sys(134) SQL rows processed

(Old DAMS only) Returns the number of rows processed by the previous Insert, Delete, or Update statement, returnsÊ0 for most other statements.

; Notation equivalent in table class method
Do $cinst.$rowsaffected() Returns Num

sys(135) SQL rows fetched

(Old DAMS only) Returns the number of rows fetched from the Select table.

; Notation equivalent in table class method
Do $cinst.$rowsfetched() Returns Num

sys(136) SQL current cursor

(Old DAMS only) Returns the name of the current cursor.

sys(137) SQL current session

(Old DAMS only) Returns the name of the current session.

sys(138) SQL results sets

(Old DAMS only) Returns the number of Result sets to come back from the server following a Select. ReturnsÊ0 if no more results.

Sys Functions - Hardware

This section provides you with documentation, tips, and demos for each of hardware related the sys() functions.

sys(6) Platform code

Returns the platform code of the current executable:

sys(7) OS Version #

Returns a string containing the version number of the current OS.

For example, returns "3.11" under Windows for Workgroups versionÊ3.11, "4.0" under Windows 95, and "7.5" when running under the MacOS System Software 7.5.

sys(8) Omnis platform type

Returns the platform type of the current Omnis program as a string: 'MAC600', 'WIN32',ÕUNIXÕ,ÕSOLARISÕ

sys(87) Horiz screen res

Returns horizontal screen resolution in pixels per inch

sys(88) Vert screen res

Returns vertical screen resolution in pixels per inch

sys(101) Printer name

Returns the current printer name, and network path (empty if not connected).

This is useful to put in your Startup_Task method. If the user doesn't have a printer selected, it can take you quite a while to figure this out what the problem is when the call to say "none of my reports will print", or "my application crashes every time I try to print a report".

; Test to make sure the user has selected a printer.
If sys(101)=''&sys(6)<>'U' ;; Test for selected printer.
   OK message [sys(85)] (Icon,Sound bell) {You currently do not have a printer selected.////Reports will not run until you select a printer.}
End If

sys(104) Screen width

Returns the screen width in pixels.

sys(105) Screen height

Returns the screen height in pixels.

sys(106) App heap size

MacOS Classic: returns the application heap size in bytes.
Mac OS X: not relevant - returns a fixed large value.
Other platforms: returns the size in bytes of available physical memory.

sys(107) App free memory

MacOS Classic: returns the current free memory in bytes in the application heap after adding memory used for discardable objects.
Mac OS X: not relevant - returns a fixed large value.
Other platforms: returns the total size in bytes of physical memory.

sys(108) Free memory

MacOS Classic: returns the current free memory in bytes in the application heap without adding memory used for discardable objects.
Mac OS X: not relevant - returns a fixed large value.
Other platforms: returns a number between 0 and 100 that gives a general idea of current memory utilization, in which 0 indicates no memory use and 100 indicates full memory use.

sys(109) Unused memory

Returns the unused memory in bytes. On Windows and Unix, this is the number of bytes available in the paging file, added to the number of bytes of available physical memory.

sys(110) CPU type

Returns the CPU type for PCs, Macs, and compatibles.

For PC:
3Ê=Ê80386,
4Ê=Ê80486
5Ê=ÊPentium

For PC:
3Ê=Ê68030
4Ê=Ê68040.

For PowerMac:
257Ê=ÊPowerPC 601
259Ê=ÊPowerPC 603
260Ê=ÊPowerPC 604
262 = PowerPC 603e
263 = PowerPC 603ev
264 = PowerPC 750 & G3
265 = PowerPC 604e
266 = PowerPC 604ev
268 = G4
313 = G5

sys(111) Apple ROM version

(MacOS only) returns the Apple ROM version: 121Ê=ÊSI, 124Ê=ÊIIsi, CI & FX.

sys(112) Balloon help

(MacOS only) returnsÊ1 (true) if balloon help is available, 0 otherwise.

Since the Mac OS X version of Omnis does not support balloon help, the return value is always zero on Mac OS X.

sys(113) Publish and Subscribe

(MacOS only) returns 1 (true) if Publish and Subscribe is available, 0 otherwise.

Since the Mac OS X version of Omnis does not support Publish and Subscribe, the return value is always zero on Mac OS X.

sys(114) Apple events

(MacOS only) returnsÊ1 (true) if Apple events are available, 0 otherwise.

sys(115) Omnis App pathname

On all platforms except Windows Vista returns the pathname of the folder containing the Omnis executable, including the terminating path separator.
On Windows Vista returns the pathname of the folder containing the installed writeable files, including the terminating path separator (usually a sub-folder of the AppData Local folder). To get the pathame of the folder containing the Omnis executable, use sys(215).

sys(116) Linux lowercase filenames

(Linux only) returns 1 (true) if Omnis has been configured to force all file names to be lower case, 0 otherwise.

sys(118) Windows OS information

(Windows only) returns additional information about the operating system version.

The information includes major and minor version numbers, a build number, a platform identifier, and information about product suites and the latest Service Pack installed on the system. This function returns the operating system version information in the Windows OSVERSIONINFOEX structure, so you should obtain information about this structure for full details about the information returned (see the Microsoft web site).

sys(120) Windows dialog width

(Windows only) Returns the width of the current dialog base-width unit based on the current system font; this differs for Small and Large font mode.

sys(121) Windows dialog height

(Windows only) Returns the height of the current dialog base-width unit based on the current system font; this differs for Small and Large font mode.

sys(197) Windows XP Themes

Returns true (1) if running on Windows XP with themes enabled, false (0) if not.

sys(203) Win32 Omnis as Service

(Win32 only) returns 1 (true) if Omnis is running as a service.

sys(209) App Bundle Folder

(Mac OS X) Returns the pathname of the folder containing the Omnis.app bundle, including the terminating path separator; this may be different to the pathname of the folder containing the Omnis executable (returned by sys(115)) if you are using Omnis as a bundle. For other platforms, returns the same pathname as sys(115).

sys(215) Omnis Executable pathname

Returns the pathname of the folder containing the Omnis executable, including the terminating path separator.

Other Functions

There are some many functions in Omnis Studio, we tend to forget about some of them.

I had created a "$retRemoveLeadingTrailingSpaces" method that used the mid() function in two While loops. I was proud of this fine function until Rudolf Bargholz pointed out the "trim()". Wow ... trim() did the job a lot easier in a single line of code and has all kinds of flexibility.

This topic covers some of the handy Omnis Studio functions not covered by the other topics in this section.

mod - Modulus

mod(number1,number2)

Returns the remainder of a number division, that is, when number1 is divided by number2 to produce a remainder; it is a true modulus function.

Calculate Remainder as mod(6,4) ;; Returns 2

Calculate Remainder as mod(4,6) ;; Returns 4

Calculate Remainder as mod(-5,-2) ;; Returns -1

Calculate Remainder as mod(4,2) ;; Returns 0

msgcancelled - Message Cancelled

Use this function to detect if the user cancels in a Yes/No or No/Yes message which has the optional Cancel button checked.

Yes/No message (Cancel button) {Do you want to proceed?}
If flag false
If msgcancelled()
user chose Cancel
Else
user chose No
End If
Else
user chose Yes
End If

pick - Pick

pick(number,value0,value1[,value2]...)

Selects an item from a list of values (strings or numbers) depending on the value or result of the number argument. The number argument is rounded to an integer and used to select the item. value0 is returned if the result is 0, value1 if the result is 1, value2 if the result is 2, and so on.

If the number is less than zero or greater than the number of values in the list, an empty value is returned. Note the list of values can be a mixture of string and numeric values.

I find pick() to work great for working with radio button results, picking day or month short forms, and for concatenating fields where some of the field values might be empty.

rnd - Round

rnd(Value,DecimalPlaces)

Calculate RoundedValue as rnd(2.105693,5) ;; ReturnsÊ2.10569
Calculate RoundedValue as rnd(2.105693,3) ;; ReturnsÊ2.106
Calculate RoundedValue as rnd(0.5,1) ;; ReturnsÊ1

Warning

The return value of the rnd() function is a character string. This is the only representation of the returned number guaranteed to hold the result correctly, due to potential floating point inaccuracies. You need to be careful when comparing the return values of two calls to rnd(), since the return values are character strings, and will be compared as strings.

The rnd() function in Omnis does not round to the left of the decimal place. Excel does this with negative parameter values: -1,-2,-3. You can round to the left of the decimal place by:

  1. Multiplying the value by .1, .01, .001
  2. Rounding the multiplied value to zero decimal places.
  3. Multiplying the result by 10,100,1000,

The above can be compressed into one-liners as follows:

; Round to the left of the decimal. Nearest 10.
Calculate RoundedValue as rnd(1386*.1,0)*10 ;; ReturnsÊ1390

; Round to the left of the decimal. Nearest 100.
Calculate RoundedValue as rnd(1386*.01,0)*100 ;; ReturnsÊ1400

; Round to the left of the decimal. Nearest 1000.
Calculate RoundedValue as rnd(1386*.001,0)*1000 ;; ReturnsÊ1000