adnansaleem

Visual FoxPro forms to Blazor: events, buffering, validation

Move a Visual FoxPro form to Blazor and EF Core: read the .scx as a table, move Valid rules into the domain, and replace table buffering with rowversion.

By M. Adnan Saleem · · 10 min read

  • Visual FoxPro
  • Blazor
  • C#
  • .NET
  • Entity Framework Core
  • SQL Server
  • legacy migration
  • forms
  • optimistic concurrency
  • validation

I migrated 42 financial workflows off Visual FoxPro to C# and .NET Core as the only engineer on the project, with Angular and Blazor on the front end. The data and the reports get most of the attention in a migration like that, and I have written up both. This one is about the part users touch every day: the forms. A FoxPro form is not only a screen. It holds business rules in its event code, and it decides when an edit reaches the table. Both have to land somewhere deliberate in the new system.

The .scx is a table too

Microsoft's Visual FoxPro reference lists the form file, .scx, among the file types that are stored as tables, and says you can browse them like any other table. Each row is one object on the form: the form itself, a text box, a grid column, a button. The METHODS memo holds that object's event code. So the first step is the same as for reports: query the file instead of clicking through the designer.

* In Visual FoxPro: a form is a table, one row per object, with its code in METHODS
USE invoice.scx ALIAS scx
SELECT parent, objname, baseclass, methods ;
    FROM scx WHERE NOT EMPTY(methods) ;
    INTO CURSOR formcode
BROWSE   && every event handler on the form, with the object it belongs to

Read every row of that cursor and sort the code into three piles. Business rules (a due date cannot precede the invoice date). Screen behaviour (disable a field, move focus, show a total). Data handling (open a table, set buffering, commit, revert). Only the first pile is the expensive one to get wrong, and it is the pile that must not end up in the new screen.

Map the events, not the controls

Rebuilding a form control by control produces a FoxPro form in HTML. Map what each event was for instead. These are the equivalents I would start from; they are not one to one, and the table says where they differ.

FoxPro form events and where the code goes in Blazor
FoxProWhat it was forIn Blazor and .NET
LoadOpen tables before any control existsOnInitializedAsync or OnParametersSetAsync, reading through a service or a short-lived DbContext
InitSet up controls; controls run theirs before the form'sComponent state set in the same methods; there is no control tree to prepare
ValidCheck a value; returning .F. keeps focus in the controlThe rule goes to the domain model; the form shows the message. Do not trap focus on the web.
WhenDecide whether a control may receive focusA disabled or readonly attribute computed from state
InteractiveChangeReact to each edit@bind:after, used sparingly
ClickRun a command@onclick, or the form's submit handler for Save
Destroy, UnloadClose tables, release objectsIAsyncDisposable on the component, if anything is held at all

A typical FoxPro invoice screen, reduced to the three handlers that matter:

* Form.Load: open the table with optimistic table buffering
SET MULTILOCKS ON
USE invoices
=CURSORSETPROP("Buffering", 5, "invoices")

* txtDueDate.Valid: the business rule lives in the control
IF THIS.Value < ThisForm.txtIssued.Value
    MESSAGEBOX("The due date cannot be before the invoice date.")
    RETURN .F.   && focus stays in the field
ENDIF

* cmdSave.Click: commit the buffer, or show why not and undo
IF NOT TABLEUPDATE(.T., .F., "invoices")
    =AERROR(laErr)
    MESSAGEBOX(laErr[2])
    =TABLEREVERT(.T., "invoices")
ENDIF

Validation: rules in the domain, messages in the form

The Valid handler is where FoxPro applications kept many of their rules, because it was the convenient place. The trouble is that the rule then only runs when someone types into that control. An import, a batch job or a second screen editing the same field skips it. In the new system the rule moves into the entity or domain service, where every path that changes an invoice goes through it, as in DDD and CQRS without the ceremony.

public sealed class Invoice
{
    public int InvoiceId { get; private set; }
    public DateOnly IssuedOn { get; private set; }
    public DateOnly DueOn { get; private set; }
    public decimal Amount { get; private set; }
    public bool Posted { get; private set; }
    [Timestamp] public byte[] RowVersion { get; private set; } = [];

    // Was the Valid code of txtDueDate and txtAmount on the FoxPro form
    public void Reschedule(DateOnly dueOn, decimal amount)
    {
        if (Posted) throw new DomainException("A posted invoice cannot be changed.");
        if (dueOn < IssuedOn) throw new DomainException("The due date cannot be before the invoice date.");
        DueOn = dueOn;
        Amount = amount;
    }
}

// Shape only: what the screen can check without asking the database
public sealed class InvoiceForm
{
    public DateOnly DueOn { get; set; }

    [Range(0.01, 9_999_999.99, ErrorMessage = "Enter an amount above zero.")]
    public decimal Amount { get; set; }

    public static InvoiceForm From(Invoice i) => new() { DueOn = i.DueOn, Amount = i.Amount };
}

The form keeps only checks about shape: required, a number above zero, a date that parses. Those run in the browser through DataAnnotationsValidator and give instant feedback. Anything that needs other data, such as the invoice date or whether the invoice is posted, is decided by the domain on save, and its message is shown in the form.

Buffering becomes a unit of work

With optimistic table buffering (CURSORSETPROP("Buffering", 5)), FoxPro keeps edits in a buffer until TABLEUPDATE() commits them or TABLEREVERT() throws them away, and the update fails if another user changed the record in the meantime. That is exactly the behaviour users rely on: edit freely, then Save or Revert. EF Core gives the same three parts.

  • The buffer is the form model. Nothing touches the database while the user edits.
  • TABLEUPDATE is a short-lived DbContext from IDbContextFactory, used for one save. Microsoft's Blazor guidance is a context per operation, not one per circuit.
  • The conflict check is a rowversion column. The page keeps the version it loaded and hands it back as the original value, so SaveChanges throws DbUpdateConcurrencyException if someone else saved first.
@page "/invoices/{Id:int}"
@rendermode InteractiveServer
@inject IDbContextFactory<AppDb> DbFactory

<h1>Invoice @Id</h1>

<EditForm Model="form" OnValidSubmit="SaveAsync">
    <DataAnnotationsValidator />
    <label>Due date <InputDate @bind-Value="form.DueOn" /></label>
    <label>Amount <InputNumber @bind-Value="form.Amount" /></label>
    <ValidationMessage For="() => form.Amount" />
    <button type="submit" disabled="@saving">Save</button>
    <button type="button" @onclick="RevertAsync" disabled="@saving">Revert</button>
</EditForm>

@if (message is not null)
{
    <p role="status">@message</p>
}

@code {
    [Parameter] public int Id { get; set; }
    private InvoiceForm form = new();
    private byte[] version = [];
    private bool saving;
    private string? message;

    protected override Task OnParametersSetAsync() => RevertAsync();

    // TABLEREVERT: throw the edits away and read the row again
    private async Task RevertAsync()
    {
        await using var db = await DbFactory.CreateDbContextAsync();
        var invoice = await db.Invoices.AsNoTracking().SingleAsync(i => i.InvoiceId == Id);
        form = InvoiceForm.From(invoice);
        version = invoice.RowVersion;
        message = null;
    }

    // TABLEUPDATE: one short-lived context per save, checked against the version the user loaded
    private async Task SaveAsync()
    {
        if (saving) return;
        saving = true;
        try
        {
            await using var db = await DbFactory.CreateDbContextAsync();
            var invoice = await db.Invoices.SingleAsync(i => i.InvoiceId == Id);
            db.Entry(invoice).Property(i => i.RowVersion).OriginalValue = version;
            invoice.Reschedule(form.DueOn, form.Amount);
            await db.SaveChangesAsync();
            version = invoice.RowVersion;
            message = "Saved.";
        }
        catch (DbUpdateConcurrencyException)
        {
            message = "Someone else changed this invoice while you were editing it. Revert to see their version.";
        }
        catch (DomainException ex)
        {
            message = ex.Message;
        }
        finally
        {
            saving = false;
        }
    }
}

The conflict message says what happened and what to do. A FoxPro application often showed the raw error from AERROR(), or forced the update with lForce. Forcing is the one behaviour I would not carry over without asking the people who use the screen, because it means the last person to press Save silently wins.

Grids that edited the table directly

A FoxPro grid bound to a buffered table lets users edit rows in place, and data-entry staff can be very fast with it. In a web application in-place editing is expensive to build well: keyboard movement between cells, validation per cell, conflicts per row. I would show the list read-only with QuickGrid, as in the reports article, and edit one row in a form like the one above. Then watch the people who used the grid. If they really did enter dozens of rows at a sitting, that one screen earns an editable grid; most screens do not.

Keyboard habits are requirements

Long-time users of a FoxPro screen work it from the keyboard, and those habits are part of the specification even though no code mentions them. Write them down before the new screen exists. Two that catch people out: in FoxPro, Enter in a text box usually moves to the next field, while in an HTML form it submits; and the tab order of the old form was set deliberately, so match it. Put focus in the first field on load, keep Save reachable without the mouse, and keep the field labels the users already know, even when the column names differ.

Prove the rules moved

The inventory from the .scx is the checklist. Every Valid and When handler that carried a business rule gets a test against the domain model, named in the users' words. The tests run without a browser and without a database, which makes them cheap enough to cover every rule.

public class InvoiceRules
{
    // One test per Valid or When handler found in the .scx inventory
    [Fact]
    public void Due_date_before_issue_date_is_refused()
    {
        var invoice = Invoices.Open(issuedOn: new(2026, 3, 1), dueOn: new(2026, 3, 31), amount: 100m);
        var ex = Assert.Throws<DomainException>(() => invoice.Reschedule(new(2026, 2, 28), 100m));
        Assert.Equal("The due date cannot be before the invoice date.", ex.Message);
    }

    [Fact]
    public void Posted_invoice_cannot_be_changed()
    {
        var invoice = Invoices.Posted();
        Assert.Throws<DomainException>(() => invoice.Reschedule(invoice.DueOn, invoice.Amount));
    }
}

Then run the old and new screens side by side on the same records for a week, the same way the migration guide moves one workflow at a time, and retire the FoxPro form when the people who use it stop opening it.

Mistakes I would check for first

  • Copying Valid code into the component. The rule then runs on one screen only. Put it in the domain.
  • One DbContext for the life of the page. On Blazor Server that is one context per circuit, shared by every event. Create one per save.
  • No concurrency token. Two users editing the same invoice is the case table buffering handled for you. Without a rowversion, the second save wins silently.
  • Trapping focus until a field is valid. It worked in FoxPro; on the web it fights screen readers and the browser. Show the message and let the user move on.
  • Rebuilding every screen as it was. Ask what each form is used for now. Some exist only because the old tables needed them.

The tables behind these screens came across as described in Visual FoxPro to SQL Server: a repeatable data migration. Everything on the FoxPro side, including how I work on these projects, is on the Visual FoxPro migration page, and the engagement itself is the FoxPro to .NET case study.

Quick answers

The short version

Can a Visual FoxPro form be converted to Blazor automatically?

Not usefully. The .scx file can be read as a table, which gives you every control and its event code, but the business rules in that code should move into a domain layer and the screen should be redesigned for the web. Use the inventory as a checklist, not as input to a converter.

What replaces TABLEUPDATE and TABLEREVERT in .NET?

A short-lived Entity Framework Core DbContext per save replaces TABLEUPDATE, and reloading the record replaces TABLEREVERT. A rowversion column gives the same conflict check as optimistic buffering: SaveChanges throws DbUpdateConcurrencyException if another user saved first.

Where should the code from a FoxPro Valid event go?

Business rules go into the entity or domain service, so imports, batch jobs and other screens enforce them too. Only shape checks, such as required fields and number ranges, stay in the Blazor form as data annotations.

Keep reading

Related articles

  1. Visual FoxPro to .NET and C#: a step-by-step migration guideHow to convert a legacy Visual FoxPro app to C#, .NET and SQL Server when the old code is the only spec: inventory, data, domain rules, reports, cutover.
  2. Replacing Visual FoxPro reports with Blazor and SQL ServerHow to retire FoxPro .frx reports without losing a number: inventory, totals in T-SQL, a Blazor QuickGrid screen, CSV and PDF exports, and parity tests.
  3. Visual FoxPro to SQL Server: a repeatable data migrationMoving Visual FoxPro tables into SQL Server: a mapping for every field type, deleted rows, code pages, and a staging load with control totals you can rehearse.

The project behind this

Read the case study

What I built, where, and the numbers that came out of it.

Related experience: Visual FoxPro migration, .NET developer.

↑ ↓ to move · Enter to run · Esc to close