Sample code for 30+ languages & platforms
Visual FoxPro Requires Chilkat v11.6.0+

Outlook Calendar: Synchronize a Calendar View with Delta Queries

See more Outlook Calendar Examples

Build a local view of the default calendar for a fixed 30-day window, then retrieve changes on later runs. The first request uses /me/calendarView/delta. Each page can include new or updated events and @removed tombstones. Keep IDs as strings. This example stores a small projection (subject, type, start, end) under JSON-safe hash keys, retaining the original ID in each record. Repeated changes overwrite the same record; records with removed=true are tombstones to exclude from the local view. It is a demonstration cache, not a complete event archive.

The checkpoint saves the local data, original window and exact nextLink or deltaLink together. Follow these opaque URLs without adding or rebuilding query parameters, and send the same Prefer header on every request. Do not use $select with calendarView delta. The v1.0 API tracks the primary calendar. A removed item should be removed from this local date-range view; it does not always mean the event was globally deleted. Preserve omitted fields on partial updates.

Use one writer and a separate protected cache per account, window and ID preference. An intermediate nextLink resumes an unfinished round; a deltaLink starts the next round for the same fixed window. A moving agenda needs a new baseline when its window changes. HTTP 410 or a sync-state error requires a new full synchronization and deliberate reconciliation of the old view, not an endless retry of the rejected token.

Validation and HTTP failures do not advance the saved cursor. Before replacing a checkpoint, the example saves a backup containing the previous matching data and cursor. Recover that pair if the main file is damaged; replaying a page is safe for these upserts and tombstones. Production applications should commit the data and cursor atomically in a database transaction or equivalent storage operation. The 100-page limit saves a continuation before pausing.

Delegated permission: Calendars.Read.

Uses Microsoft Graph v1.0 in the global cloud with a delegated access token saved by the calendar OAuth2 example. Both personal Outlook.com accounts and Microsoft 365 work/school accounts with a mailbox can use this flow. The app registration must support the selected account type. A token for SMTP/IMAP/POP or another API is not a Graph token.

/me means the signed-in user and requires delegated authentication. An unattended Microsoft 365 service instead needs application permissions and administrator consent, and addresses an explicit mailbox through /users/{id-or-userPrincipalName}. That client-credentials flow does not apply to personal Outlook.com accounts. These samples target the global cloud; national clouds use different authority and Graph hosts.

HTTP methods can return false for an HTTP error as well as a connection failure. The code distinguishes those cases and checks the expected status before reading JSON. For 401, refresh the access token or authorize again; for 403, check permissions, mailbox access, and tenant policy. For 429, honor Retry-After before a bounded retry. Do not automatically repeat a write after an uncertain outcome. Keep detailed errors and calendar data private.

Microsoft documentation

Chilkat Visual FoxPro Downloads

Visual FoxPro
LOCAL lnSuccess
LOCAL loToken
LOCAL loHttp
LOCAL loResp
LOCAL loResult
LOCAL loFac
LOCAL lcCachePath
LOCAL lcBackupPath
LOCAL loState
LOCAL loWindowTime
LOCAL lcWindowStart
LOCAL lcWindowEnd
LOCAL loEndpoint
LOCAL loHash
LOCAL loLink
LOCAL loItemPath
LOCAL loSeenLinks
LOCAL loPrevious
LOCAL lnPageCount
LOCAL lcUrl
LOCAL lnNextType
LOCAL lnDeltaType
LOCAL lnFinished
LOCAL lcResumeUrl
LOCAL i
LOCAL lcEventId
LOCAL lcItemKey

lnSuccess = 0

*  Assumes Chilkat is unlocked. See Global Unlock Sample.
lnSuccess = 0
*  Obtain a delegated Microsoft Graph token using the calendar authorization example.
*  See Authorize Outlook Calendar with OAuth2 and PKCE.
loToken = CreateObject('Chilkat.JsonObject')
loToken.Strict = 1
lnSuccess = loToken.LoadFile("qa_data/tokens/outlookCalendar.json")
IF (lnSuccess <> 1) THEN
    ? "Could not read the private calendar token cache."
    RELEASE loToken
    CANCEL
ENDIF

IF ((loToken.JsonTypeOf("access_token") <> 1) OR (loToken.StringOfEquals("access_token","",1) = 1)) THEN
    ? "Expected a nonempty access_token in the JSON."
    RELEASE loToken
    CANCEL
ENDIF

loHttp = CreateObject('Chilkat.Http')
loHttp.AuthToken = loToken.StringOf("access_token")
loHttp.RequireSslCertVerify = 1
loHttp.FollowRedirects = 0
loHttp.ConnectTimeout = 20
loHttp.ReadTimeout = 30
loHttp.SetRequestHeader("Accept","application/json")
loResp = CreateObject('Chilkat.HttpResponse')
loResult = CreateObject('Chilkat.JsonObject')
loResult.Strict = 1
loHttp.SetRequestHeader("Prefer",'outlook.timezone="UTC", IdType="ImmutableId", odata.maxpagesize=50')
loFac = CreateObject('Chilkat.FileAccess')
lnSuccess = loFac.DirEnsureExists("qa_data/outlookCalendar")
IF (lnSuccess <> 1) THEN
    ? "Could not create the private synchronization directory."
    RELEASE loToken
    RELEASE loHttp
    RELEASE loResp
    RELEASE loResult
    RELEASE loFac
    CANCEL
ENDIF

lcCachePath = "qa_data/outlookCalendar/calendar-sync.json"
lcBackupPath = "qa_data/outlookCalendar/calendar-sync.json.bak"
loState = CreateObject('Chilkat.JsonObject')
loState.Strict = 1
IF (loFac.FileExists(lcCachePath) = 1) THEN
    lnSuccess = loState.LoadFile(lcCachePath)
    IF (lnSuccess <> 1) THEN
        ? "Invalid checkpoint; recover the matching data and cursor from the private .bak file before continuing."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        CANCEL
    ENDIF

    IF ((loState.JsonTypeOf("resumeUrl") <> 1) OR (loState.StringOfEquals("resumeUrl","",1) = 1)) THEN
        ? "Expected a nonempty resumeUrl in the JSON."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        CANCEL
    ENDIF

    IF ((loState.JsonTypeOf("startDateTime") <> 1) OR (loState.StringOfEquals("startDateTime","",1) = 1)) THEN
        ? "Expected a nonempty startDateTime in the JSON."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        CANCEL
    ENDIF

    IF ((loState.JsonTypeOf("endDateTime") <> 1) OR (loState.StringOfEquals("endDateTime","",1) = 1)) THEN
        ? "Expected a nonempty endDateTime in the JSON."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        CANCEL
    ENDIF

    IF (loState.JsonTypeOf("items") <> 3) THEN
        ? "Expected an items object in the checkpoint."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        CANCEL
    ENDIF

ELSE
    loWindowTime = CreateObject('Chilkat.CkDateTime')
    lnSuccess = loWindowTime.SetFromCurrentSystemTime()
    IF (lnSuccess <> 1) THEN
        ? "Could not get the current time."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loWindowTime
        CANCEL
    ENDIF

    lcWindowStart = loWindowTime.GetAsTimestamp(0)
    lnSuccess = loWindowTime.AddDays(30)
    IF (lnSuccess <> 1) THEN
        ? "Could not calculate the window end."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loWindowTime
        CANCEL
    ENDIF

    lcWindowEnd = loWindowTime.GetAsTimestamp(0)
    loEndpoint = CreateObject('Chilkat.StringBuilder')
    loEndpoint.Append("https://graph.microsoft.com/v1.0/me/calendarView/delta?startDateTime=")
    loEndpoint.Append(loHttp.UrlEncode(lcWindowStart))
    loEndpoint.Append("&endDateTime=")
    loEndpoint.Append(loHttp.UrlEncode(lcWindowEnd))
    loState.UpdateString("startDateTime",lcWindowStart)
    loState.UpdateString("endDateTime",lcWindowEnd)
    loState.UpdateString("resumeUrl",loEndpoint.GetAsString())
    loState.UpdateNewObject("items")
ENDIF

loHash = CreateObject('Chilkat.Crypt2')
loHash.HashAlgorithm = "sha256"
loHash.Charset = "utf-8"
loHash.EncodingMode = "hex"
loLink = CreateObject('Chilkat.StringBuilder')
loItemPath = CreateObject('Chilkat.StringBuilder')
loSeenLinks = CreateObject('Chilkat.Hashtable')
loPrevious = CreateObject('Chilkat.JsonObject')
loPrevious.Strict = 1
lnPageCount = 0
DO WHILE (lnPageCount < 100)
    lcUrl = loState.StringOf("resumeUrl")
    loLink.Clear()
    loLink.Append(lcUrl)
    IF (loLink.StartsWith("https://graph.microsoft.com/v1.0/",1) <> 1) THEN
        ? "Unexpected continuation host or API version; no request sent."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loWindowTime
        RELEASE loEndpoint
        RELEASE loHash
        RELEASE loLink
        RELEASE loItemPath
        RELEASE loSeenLinks
        RELEASE loPrevious
        CANCEL
    ENDIF

    IF (loSeenLinks.Contains(lcUrl) = 1) THEN
        ? "Repeated continuation URL; stopping."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loWindowTime
        RELEASE loEndpoint
        RELEASE loHash
        RELEASE loLink
        RELEASE loItemPath
        RELEASE loSeenLinks
        RELEASE loPrevious
        CANCEL
    ENDIF

    loSeenLinks.AddInt(lcUrl,1)
    lnSuccess = loHttp.HttpNoBody("GET",lcUrl,loResp)
    *  A false result can still include an HTTP error response.
    IF ((lnSuccess <> 1) AND (loResp.StatusCode = 0)) THEN
        ? "No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loWindowTime
        RELEASE loEndpoint
        RELEASE loHash
        RELEASE loLink
        RELEASE loItemPath
        RELEASE loSeenLinks
        RELEASE loPrevious
        CANCEL
    ENDIF

    IF (loResp.StatusCode <> 200) THEN
        ? "Unexpected HTTP status: " + STR(loResp.StatusCode)
        ? "Request ID: " + loResp.GetHeaderField("request-id")
        IF (loResp.StatusCode = 429) THEN
            ? "Retry-After: " + loResp.GetHeaderField("Retry-After")
        ENDIF

        IF (loResp.StatusCode = 401) THEN
            ? "Refresh the Graph access token or authorize again."
        ENDIF

        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loWindowTime
        RELEASE loEndpoint
        RELEASE loHash
        RELEASE loLink
        RELEASE loItemPath
        RELEASE loSeenLinks
        RELEASE loPrevious
        CANCEL
    ENDIF

    lnSuccess = loResult.Load(loResp.BodyStr)
    IF (lnSuccess <> 1) THEN
        ? "Expected a well-formed JSON response."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loWindowTime
        RELEASE loEndpoint
        RELEASE loHash
        RELEASE loLink
        RELEASE loItemPath
        RELEASE loSeenLinks
        RELEASE loPrevious
        CANCEL
    ENDIF

    IF (loResult.JsonTypeOf("value") <> 4) THEN
        ? "Expected a value array; checkpoint unchanged."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loWindowTime
        RELEASE loEndpoint
        RELEASE loHash
        RELEASE loLink
        RELEASE loItemPath
        RELEASE loSeenLinks
        RELEASE loPrevious
        CANCEL
    ENDIF

    *  Exactly one continuation member must be a nonempty string.
    lnNextType = loResult.JsonTypeOf('"@odata.nextLink"')
    lnDeltaType = loResult.JsonTypeOf('"@odata.deltaLink"')
    lnFinished = 0

    IF ((lnNextType = 1) AND (lnDeltaType = -1)) THEN
        lcResumeUrl = loResult.StringOf('"@odata.nextLink"')
    ELSE
        IF ((lnDeltaType <> 1) OR (lnNextType <> -1)) THEN
            ? "Invalid delta continuation; checkpoint unchanged."
            RELEASE loToken
            RELEASE loHttp
            RELEASE loResp
            RELEASE loResult
            RELEASE loFac
            RELEASE loState
            RELEASE loWindowTime
            RELEASE loEndpoint
            RELEASE loHash
            RELEASE loLink
            RELEASE loItemPath
            RELEASE loSeenLinks
            RELEASE loPrevious
            CANCEL
        ENDIF

        lcResumeUrl = loResult.StringOf('"@odata.deltaLink"')
        lnFinished = 1
    ENDIF

    loLink.Clear()
    loLink.Append(lcResumeUrl)
    IF (loLink.StartsWith("https://graph.microsoft.com/v1.0/",1) <> 1) THEN
        ? "Invalid continuation URL; checkpoint unchanged."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loWindowTime
        RELEASE loEndpoint
        RELEASE loHash
        RELEASE loLink
        RELEASE loItemPath
        RELEASE loSeenLinks
        RELEASE loPrevious
        CANCEL
    ENDIF

    lnSuccess = loPrevious.Load(loState.Emit())
    IF (lnSuccess <> 1) THEN
        ? "Could not snapshot the previous checkpoint."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loWindowTime
        RELEASE loEndpoint
        RELEASE loHash
        RELEASE loLink
        RELEASE loItemPath
        RELEASE loSeenLinks
        RELEASE loPrevious
        CANCEL
    ENDIF

    i = 0
    DO WHILE (i < loResult.SizeOfArray("value"))
        loResult.I = i
        IF ((loResult.JsonTypeOf("value[i].id") <> 1) OR (loResult.StringOfEquals("value[i].id","",1) = 1)) THEN
            ? "Expected a nonempty value[i].id in the JSON."
            RELEASE loToken
            RELEASE loHttp
            RELEASE loResp
            RELEASE loResult
            RELEASE loFac
            RELEASE loState
            RELEASE loWindowTime
            RELEASE loEndpoint
            RELEASE loHash
            RELEASE loLink
            RELEASE loItemPath
            RELEASE loSeenLinks
            RELEASE loPrevious
            CANCEL
        ENDIF

        lcEventId = loResult.StringOf("value[i].id")
        lcItemKey = loHash.HashStringENC(lcEventId)
        IF (loHash.LastMethodSuccess <> 1) THEN
            ? "Could not form a local record key."
            RELEASE loToken
            RELEASE loHttp
            RELEASE loResp
            RELEASE loResult
            RELEASE loFac
            RELEASE loState
            RELEASE loWindowTime
            RELEASE loEndpoint
            RELEASE loHash
            RELEASE loLink
            RELEASE loItemPath
            RELEASE loSeenLinks
            RELEASE loPrevious
            CANCEL
        ENDIF

        *  Hash only for a JSON-safe local key. Preserve the original opaque ID in the record.
        loItemPath.Clear()
        loItemPath.Append("items.")
        loItemPath.Append(lcItemKey)
        IF (loState.JsonTypeOf(loItemPath.GetAsString()) <> 3) THEN
            loState.UpdateNewObject(loItemPath.GetAsString())
        ENDIF

        loItemPath.Append(".")
        loState.PathPrefix = loItemPath.GetAsString()
        loState.UpdateString("id",lcEventId)
        IF (loResult.JsonTypeOf("value[i].@removed") = 3) THEN
            *  Hide records with removed=true from the local date-range view.
            loState.UpdateBool("removed",1)
            ? "Removed from the local view: " + lcEventId
        ELSE
            loState.UpdateBool("removed",0)
            IF (loResult.JsonTypeOf("value[i].subject") = 1) THEN
                loState.UpdateString("subject",loResult.StringOf("value[i].subject"))
            ENDIF

            IF (loResult.JsonTypeOf("value[i].type") = 1) THEN
                loState.UpdateString("type",loResult.StringOf("value[i].type"))
            ENDIF

            IF (loResult.JsonTypeOf("value[i].start.dateTime") = 1) THEN
                loState.UpdateString("start.dateTime",loResult.StringOf("value[i].start.dateTime"))
            ENDIF

            IF (loResult.JsonTypeOf("value[i].start.timeZone") = 1) THEN
                loState.UpdateString("start.timeZone",loResult.StringOf("value[i].start.timeZone"))
            ENDIF

            IF (loResult.JsonTypeOf("value[i].end.dateTime") = 1) THEN
                loState.UpdateString("end.dateTime",loResult.StringOf("value[i].end.dateTime"))
            ENDIF

            IF (loResult.JsonTypeOf("value[i].end.timeZone") = 1) THEN
                loState.UpdateString("end.timeZone",loResult.StringOf("value[i].end.timeZone"))
            ENDIF

            loState.PathPrefix = ""
            ? "Updated local event: " + lcEventId
        ENDIF

        loState.PathPrefix = ""
        i = i + 1
    ENDDO
    loState.UpdateString("resumeUrl",lcResumeUrl)
    loState.UpdateBool("roundComplete",lnFinished)
    *  Save the data and cursor in one document. The backup contains the matching previous pair.
    lnSuccess = loPrevious.WriteFile(lcBackupPath)
    IF (lnSuccess <> 1) THEN
        ? "Could not back up the previous checkpoint; no replacement attempted."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loWindowTime
        RELEASE loEndpoint
        RELEASE loHash
        RELEASE loLink
        RELEASE loItemPath
        RELEASE loSeenLinks
        RELEASE loPrevious
        CANCEL
    ENDIF

    lnSuccess = loState.WriteFile(lcCachePath)
    IF (lnSuccess <> 1) THEN
        ? "Checkpoint write failed. Restore the private .bak before continuing."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loWindowTime
        RELEASE loEndpoint
        RELEASE loHash
        RELEASE loLink
        RELEASE loItemPath
        RELEASE loSeenLinks
        RELEASE loPrevious
        CANCEL
    ENDIF

    lnPageCount = lnPageCount + 1
    IF (lnFinished = 1) THEN
        ? "Synchronization round complete; saved the delta link for the next run."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loWindowTime
        RELEASE loEndpoint
        RELEASE loHash
        RELEASE loLink
        RELEASE loItemPath
        RELEASE loSeenLinks
        RELEASE loPrevious
        CANCEL
    ENDIF

ENDDO
? "Paused after 100 pages; the saved nextLink resumes on the next run."

RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loFac
RELEASE loState
RELEASE loWindowTime
RELEASE loEndpoint
RELEASE loHash
RELEASE loLink
RELEASE loItemPath
RELEASE loSeenLinks
RELEASE loPrevious