OpenAI advertising measurement

    Allow OpenAI to measure page views and completed contact requests, including a hashed email address and, when available, a hashed customer ID from your contact record for matching? The contact form works either way. Your choice applies only to OpenAI advertising measurement. Privacy notice

    Change this choice any time using Advertising measurement settings in the footer.

    Emergency TriageExperiencing system crashes, corrupted TPS files, or sudden developer departure?
    Back to Blog
    Clarion Tips

    Practical Clarion ABC Tips: Safer File Access, Browse Filters and Embed Code

    Practical Clarion ABC Tips: Safer File Access, Browse Filters and Embed Code

    If you maintain a Clarion application you did not write, three areas deserve your attention first: how the code touches files, how it filters browses, and where embedded code lands inside generated methods. The ABC (Application Builder Class) templates give you library methods for all three, and they work best when you use the library instead of working around it.

    This article collects practical ABC tips for developers who edit real, running Clarion applications. The examples follow patterns from the SoftVelocity documentation and use illustrative names (a Customer file with the prefix CUS, a key called CUS:CustomerKey). Swap in your own dictionary names, and test any change on a copy of the application and its data first.

    First, know which template chain you are in

    Clarion has two template families. The older procedural ("Clarion") templates generate long, linear procedures. The ABC templates generate object-oriented code: each procedure is a thin wrapper around objects derived from the ABC Library. According to the SoftVelocity documentation, an ABC-generated procedure contains a single line of executable code, GlobalResponse = ThisWindow.Run(), and everything else lives in the ABC Library or in overridden methods the templates generate for you.

    The objects you will meet most often in an ABC procedure:

    • ThisWindow, derived from WindowManager (or ReportManager in reports)
    • BRW1, BRW2 and so on, derived from BrowseClass
    • ThisProcess, derived from ProcessClass
    • Access:FileName, a FileManager for each file
    • Relate:FileName, a RelationManager for each file

    Many older applications mix both styles, and some procedures contain hand-written code that predates ABC. Before changing anything, open the procedure in the Embeditor and confirm which style you are looking at. The rest of this article assumes ABC.

    Tip 1: Use Relate: and Access: instead of raw file statements

    In legacy code you see OPEN, ADD, PUT and DELETE followed by an ERRORCODE() check. SoftVelocity recommends writing embed code that uses the ABC Library methods, so that your code does not disturb anything the template-generated code is counting on. The transition guide maps the common statements like this:

    Legacy statementABC equivalentWhy it matters
    OPEN(File), SHARE(File), CheckOpen(File)Relate:File.Open()Opens the related files too, so referential integrity can be enforced
    CLOSE(File)Relate:File.Close()Closes the related files as well
    ADD(File)Access:File.Insert()Validates the record, handles auto-increment keys and does its own error handling
    PUT(File)Relate:File.Update(0)Applies the relationship constraints defined for the file
    DELETE(File)Relate:File.Delete(0)Applies the relationship constraints; the 0 means no confirmation dialog

    The ABC methods do their own error handling, so the old IF ERRORCODE() THEN STOP(ERROR()). line after each statement is not needed. Update and Delete also return a value that tells you whether they succeeded, and the tips below check it.

    If a file is in the procedure's Data / Tables pad, the templates generate the open and close calls for you, and the library only opens a file when it needs to. When you find hand-written OPEN and CLOSE statements in a procedure like that, check them against what the generated code already does.

    Tip 2: Choose Fetch or TryFetch on purpose

    Both methods get a specific record by key. Prime the key fields first, then call the method. If the key is not unique, you get the first record with that key value. The difference is what happens on failure:

    • Fetch handles errors for you and, on failure, clears the record buffer.
    • TryFetch returns Level:Notify on failure and does not clear the record buffer, so you decide what happens next.

    Both return Level:Benign on success. TryFetch fits maintenance code where you want to control the failure path yourself. Note what the return value tells you: Level:Notify means the fetch failed. It does not tell you why, and a missing record is only one possible reason. The example below reports a failed lookup without guessing at the cause.

    CUS:CustomerID = LOC:CustomerID                  ! prime the key field
    IF Access:Customer.TryFetch(CUS:CustomerKey) = Level:Benign
      LOC:CustomerName = CUS:Name                    ! success: the record is in the buffer
    ELSE
      LOC:CustomerName = ''                          ! failed: you decide what happens next
      MESSAGE('Could not read customer ' & LOC:CustomerID & '.', 'Lookup', ICON:Exclamation)
    END

    LOC:CustomerID and LOC:CustomerName are local variables declared in a data section embed of the procedure, which leads to a rule worth keeping in mind (see Tip 6).

    Tip 3: Loop through records with SaveFile, Next and RestoreFile

    A loop inside embed code moves the file's position and can change the record buffer. If a browse or form is relying on that position, you have just changed it under them. The ABC pattern is to bookmark the file state first and restore it afterwards. The state variable must be a USHORT.

    ! Declared in a data section embed:
    !   LOC:SaveState   USHORT
    !   LOC:Region      STRING(20)
    !   LOC:Count       LONG
    
    LOC:SaveState = Access:Customer.SaveFile()         ! bookmark file position and buffer
    CLEAR(CUS:Record)
    CUS:Region = LOC:Region                            ! prime the key for the range
    SET(CUS:RegionKey, CUS:RegionKey)                  ! start at the primed key values
    LOOP
      IF Access:Customer.Next() <> Level:Benign THEN BREAK.   ! end of file or error
      IF CUS:Region <> LOC:Region THEN BREAK.            ! left the range: stop
      IF CUS:Status = 'A'
        LOC:Count += 1
      END
    END
    Access:Customer.RestoreFile(LOC:SaveState)         ! put everything back

    SaveFile stores the file position and any active HOLD or WATCH, and saves a copy of the record buffer. RestoreFile puts them back. The SET statement is ordinary Clarion language, and ABC does not change it. Keep the range check in the loop: without it, the loop reads on past your range to the end of the key.

    Tip 4: Add, change and delete through the managers

    These patterns follow the ABC Library documentation. Names such as CUS:Name are placeholders for your own fields. Each one checks the return value, and the change and delete examples only run after a successful TryFetch, so they act on the record you asked for.

    ! Add a record
    IF Access:Customer.PrimeRecord() = Level:Benign    ! clears the record, primes auto-increment keys
      CUS:Name = LOC:NewName
      IF Access:Customer.Insert() <> Level:Benign
        Access:Customer.CancelAutoInc()                ! add failed: undo the auto-increment priming
      END
    END
    
    ! Change a record
    CUS:CustomerID = LOC:CustomerID
    IF Access:Customer.TryFetch(CUS:CustomerKey) = Level:Benign
      CUS:Status = 'I'
      IF Relate:Customer.Update(0) <> Level:Benign     ! subject to relationship rules
        MESSAGE('The customer could not be updated.', 'Update', ICON:Exclamation)
      END
    ELSE
      MESSAGE('Could not read customer ' & LOC:CustomerID & '.', 'Update', ICON:Exclamation)
    END
    
    ! Delete a record: only after a successful fetch, and only after the user confirms
    CUS:CustomerID = LOC:CustomerID
    IF Access:Customer.TryFetch(CUS:CustomerKey) = Level:Benign
      IF MESSAGE('Delete customer ' & CLIP(CUS:Name) & '?', 'Confirm delete', ICON:Question, BUTTON:Yes + BUTTON:No, BUTTON:No) = BUTTON:Yes
        IF Relate:Customer.Delete(0) <> Level:Benign   ! 0 = no built-in confirmation
          MESSAGE('The customer could not be deleted.', 'Delete', ICON:Exclamation)
        END
      END
    ELSE
      MESSAGE('Could not read customer ' & LOC:CustomerID & '.', 'Delete', ICON:Exclamation)
    END

    A few points about these patterns:

    • PrimeRecord clears the buffer, primes field values and increments auto-increment keys. The documentation says PrimeAutoInc adds a placeholder record for an auto-incrementing key, and CancelAutoInc removes it, which is why the SoftVelocity Insert example calls CancelAutoInc when the add fails.
    • Relate:Update and Relate:Delete work on the current record in the buffer. That is why both examples fetch the record first and touch it only inside the success branch. A delete that runs after a failed fetch acts on whatever record happens to be current.
    • Delete(0) skips the built-in confirmation, so confirm with the user yourself first. If you omit the parameter, Delete asks for confirmation by default.
    • Check the relationships defined for the file before you delete. Depending on the constraint set in the dictionary, Delete can refuse when child records exist (restrict), delete the child records too (cascade), delete only the parent (none) or clear the linking fields in child records (clear).

    Tip 5: Filter a browse at runtime with SetFilter

    You do not need to rebuild a browse to filter it. BrowseClass inherits SetFilter from ViewManager, and SoftVelocity's own transition guide uses it for runtime filtering. A few facts from the reference:

    • A filter belongs to the active sort order of the browse.
    • Each filter can carry an ID, and the ID must begin with a number. IDs are truncated after 30 characters.
    • Filters with different IDs are combined with AND.
    • Calling SetFilter again with the same ID replaces that filter. An empty expression removes it.
    • Filters are evaluated in ID order, highest number first, so the reference suggests giving the filter most likely to fail the highest number.

    Put this in the EVENT:Accepted embed for the control the user changes, here two check boxes, then refresh the window. The conditions are fixed expressions, so there is no user-typed text inside them. CUS:OnHold is an illustrative field.

    IF LOC:ActiveOnly
      BRW1.SetFilter('CUS:Status = ''A''', '3Status')   ! active customers only
    ELSE
      BRW1.SetFilter('', '3Status')                     ! empty expression removes this filter
    END
    
    IF LOC:HideOnHold
      BRW1.SetFilter('CUS:OnHold = 0', '2OnHold')       ! hide customers on hold
    ELSE
      BRW1.SetFilter('', '2OnHold')
    END
    
    ThisWindow.Reset(1)                                 ! force the browse to refresh

    When both boxes are ticked, the browse shows records where CUS:Status = 'A' and CUS:OnHold = 0.

    Why the reset line matters. SetFilter changes the filter on the browse's view. The ThisWindow.Reset(1) call afterwards unconditionally resets the window and every object registered with it, which includes calling ResetSort and UpdateWindow for each browse, so the list is rebuilt with the new filter. The reference says a forced reset should be used sparingly, because it resets everything. Reset(0), the default, resets only when circumstances require it, such as a new sort order or a changed reset field, so it does not reliably pick up a filter you changed by hand.

    Keep dynamic filters to controlled values. A check box, a drop list or a single letter, as in SoftVelocity's example, keeps the expression predictable. A filter built from free-form text that a user types is a different problem, because that text becomes part of the expression. It needs deliberate input handling and its own testing, so it is outside the scope of this article. For large tables, also look at the ViewManager range methods such as AddRange in the ABC Library Reference.

    Tip 6: Respect how embed code is generated

    Many ABC mistakes in inherited applications come from forgetting that an embed point is inside a generated method, not inside one long procedure.

    Declare your variables. An implicit variable such as X# exists only inside the method where you use it. Assign it in one embed and test it in another, and you are using two different variables, so the second one stays at zero. In legacy-template code this worked, because everything was one procedure. Declare real local variables in a data section embed. SoftVelocity points out the side benefit: the compiler then catches your spelling mistakes.

    Do not use OMIT across embeds. Starting an OMIT in one embed and ending it in another used to disable a small piece of generated code. In ABC it can disable much more than you intended, including the call to the parent method that handles standard behavior. To replace standard behavior, override the right method and issue a RETURN before the PARENT call. In a method that returns a value, the RETURN must supply one.

    Set properties early. Many behaviors are properties, not code. SoftVelocity's guidance is to set them near the end of ThisWindow.Init, after the objects exist and before the user sees the window. Two examples from the documentation:

    ! A browse that must calculate totals even while its tab is hidden
    BRW1.ActiveInvisible = TRUE
    
    ! In a report: skip the print preview when the user has turned it off
    IF NOT CTL:PrintPreview THEN ThisWindow.SkipPreview = TRUE.

    The same documentation shows a pattern for a "Copy record" button. Declare a flag (CopyFlag BYTE) in a data section, then in the BRW1.PrimeRecord method, immediately before the PARENT.PrimeRecord call, add:

    IF CopyFlag = TRUE
      SuppressClear = TRUE     ! keep the highlighted record's values for the new record
      CopyFlag = FALSE         ! reset so normal inserts still clear the record
    END

    Then in the Copy button's EVENT:Accepted embed, set CopyFlag = TRUE and post the Insert button's accepted event: POST(EVENT:Accepted, ?Insert). Per the documentation, the parent method still runs, so auto-increment keys are handled normally while the rest of the record starts from the copied values.

    Tip 7: Learn the method naming conventions

    ABC method names follow a consistent vocabulary, which makes unfamiliar code easier to read. Init sets an object up and Kill shuts it down. Take... methods process an item such as an event or record (TakeAccepted, TakeRecord). Set... methods set or activate an item. Try... methods make one attempt and return zero (Level:Benign) on success, where the plain version handles the error for you. Throw... methods pass an error to the error handler. When you open an old procedure and see a method name you do not recognize, the prefix usually tells you what it does.

    A note on changing code you did not write

    Every tip above is easier to apply safely when you know what the application already does. Our approach to legacy Clarion work is to stabilize first: get a working copy of the source and data, confirm the application builds and runs, and record the business rules that live in embed code before touching them. Many rules are buried in embeds and are written nowhere else. Once the system is stable and those rules are preserved, changes can be made in small steps that you test one at a time, which is the same idea behind modernizing in phases instead of rewriting.

    Need a second pair of eyes on a Clarion application?

    Clarion Programming Help brings 30 years of Clarion development experience to applications whose original developer is gone, systems that are crashing, and teams who want reliable ongoing support or a REST API bridge to modern tools. If you would like to talk through your situation, get in touch and tell us what you are working with.

    Sources