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

OneDrive: Synchronize a Local File Index with Delta Queries

See more OneDrive Examples

Build and maintain a local metadata index for one drive. The first run follows root/delta to a deltaLink; later runs start at that saved URL. Keep a separate checkpoint for each account, drive, and projection. Empty pages still have to be followed. OneDrive reports deletion with the deleted facet, not Outlook's @removed annotation.

Repeated item IDs are applied in received order, with the last occurrence winning. Partial updates preserve omitted fields; parent IDs support renames and moves without relying on returned paths. IDs remain strings and large sizes are stored as decimal text. Tombstones are retained rather than deleting local data. A real file synchronizer must download changed content, reconcile local edits, and remove a deleted folder only after the round is complete and it is empty.

The checkpoint stores data and continuation together, with a private matching backup before replacement. Use atomic durable storage and one writer in production. Intermediate pages are not a completed snapshot; roundComplete becomes true only at deltaLink. An expired state (410) requires reconciliation and a fresh baseline, not silent loss of local changes. The 100-page execution bound saves progress for the next run. Continuation URLs are private and must not be edited.

Keep drive IDs and item IDs as opaque strings, retaining the drive context with each item. Encode individual path segments, not an entire URL or a slash-separated path in one call. An item ID remains stable across rename/move within its drive; a name-based path changes. OneDrive does not use Outlook's ImmutableId preference.

Permission: Files.Read.

Uses direct Chilkat.Http requests to Microsoft Graph v1.0 in the global cloud. The delegated token is read from the private qa_data/tokens/oneDrive.json file created by the PKCE authorization example. Personal Microsoft accounts and Microsoft 365 work/school accounts can use delegated authorization when the app registration supports them. Refresh expired tokens; scopes and actual file access both matter.

For app-only Microsoft 365 access, use client credentials with administrator-approved application permissions. /me requires a signed-in user; app-only calls must address an authorized user, site, or drive explicitly. Client credentials do not grant access to personal OneDrive accounts. National clouds use their own authority and Graph hosts.

Check the expected HTTP status before using a response body. A false method result can still contain an HTTP error response; status zero means no response arrived. For 401, renew authorization; for 403, check permissions, access grants, and policy; for 429, honor Retry-After with a bounded retry. Reconcile uncertain writes before repeating them. Keep credentials, file contents, upload/download URLs, and detailed diagnostics private.

Microsoft documentation

Chilkat B4X Downloads

B4X
Dim success As Boolean = False

'  Assumes Chilkat is unlocked. See Global Unlock Sample.
success = False
'  Obtain a delegated Graph token with this example's file permissions.
'  See OneDrive OAuth2 with PKCE.
Dim token As ChilkatJsonObject
token.Initialize
token.Strict = True
success = token.LoadFile("qa_data/tokens/oneDrive.json")
If success <> True Then
    Log("Could not load the private OneDrive token cache.")
    Return
End If

If (token.JsonTypeOf("access_token") <> 1) Or (token.StringOfEquals("access_token", "", True) = True) Then
    Log("Expected a nonempty access_token in the JSON.")
    Return
End If

Dim http As ChilkatHttp
http.Initialize("http")
http.AuthToken = token.StringOf("access_token")
http.RequireSslCertVerify = True
http.FollowRedirects = False
http.ConnectTimeout = 20
http.ReadTimeout = 120
http.SetRequestHeader("Accept", "application/json")
Dim resp As ChilkatHttpResponse
resp.Initialize
Dim result As ChilkatJsonObject
result.Initialize
result.Strict = True
Dim driveId As String = "YOUR_DRIVE_ID"
'  Use a distinct stable application account key and cache path per account.
Dim accountKey As String = "YOUR_LOCAL_ACCOUNT_KEY"
Dim fac As ChilkatFileAccess
fac.Initialize
success = fac.DirEnsureExists("qa_data/oneDrive")
If success <> True Then
    Log("Could not create the private synchronization directory.")
    Return
End If

Dim cachePath As String = "qa_data/oneDrive/items-sync.json"
Dim backupPath As String = "qa_data/oneDrive/items-sync.json.bak"
Dim state As ChilkatJsonObject
state.Initialize
state.Strict = True
If fac.FileExists(cachePath) = True Then
    success = state.LoadFile(cachePath)
    If success <> True Then
        Log("Invalid checkpoint; recover the matching data and cursor from the private .bak file before continuing.")
        Return
    End If

    If (state.JsonTypeOf("resumeUrl") <> 1) Or (state.StringOfEquals("resumeUrl", "", True) = True) Then
        Log("Expected a nonempty resumeUrl in the JSON.")
        Return
    End If

    If (state.JsonTypeOf("driveId") <> 1) Or (state.StringOfEquals("driveId", "", True) = True) Then
        Log("Expected a nonempty driveId in the JSON.")
        Return
    End If

    If state.StringOfEquals("driveId", driveId, True) <> True Then
        Log("This checkpoint belongs to another drive. Use a separate cache.")
        Return
    End If

    If state.StringOfEquals("accountKey", accountKey, True) <> True Then
        Log("This checkpoint belongs to another account; nothing requested.")
        Return
    End If

    If state.JsonTypeOf("items") <> 3 Then
        Log("Expected an items object in the checkpoint.")
        Return
    End If

Else
    Dim endpoint As ChilkatStringBuilder
    endpoint.Initialize
    endpoint.Append("https://graph.microsoft.com/v1.0/drives/")
    endpoint.Append(http.UrlEncode(driveId))
    endpoint.Append("/root/delta?$select=id,name,size,parentReference,file,folder,eTag,deleted")
    state.UpdateString("driveId", driveId)
    state.UpdateString("accountKey", accountKey)
    state.UpdateString("resumeUrl", endpoint.GetAsString)
    state.UpdateNewObject("items")
End If

Dim hash As ChilkatCrypt2
hash.Initialize("hash")
hash.HashAlgorithm = "sha256"
hash.Charset = "utf-8"
hash.EncodingMode = "hex"
Dim link As ChilkatStringBuilder
link.Initialize
Dim itemPath As ChilkatStringBuilder
itemPath.Initialize
Dim seenLinks As ChilkatHashtable
seenLinks.Initialize
Dim previous As ChilkatJsonObject
previous.Initialize
previous.Strict = True
Dim pageCount As Int = 0
Do While (pageCount < 100)
    Dim url As String = state.StringOf("resumeUrl")
    link.Clear
    link.Append(url)
    If link.StartsWith("https://graph.microsoft.com/v1.0/", True) <> True Then
        Log("Unexpected continuation host or API version; no request sent.")
        Return
    End If

    If seenLinks.Contains(url) = True Then
        Log("Repeated continuation URL; stopping.")
        Return
    End If

    seenLinks.AddInt(url, 1)
    success = http.HttpNoBody("GET", url, resp)
    '  A false result can still include an HTTP error response.
    If (success <> True) And (resp.StatusCode = 0) Then
        Log("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.")
        Return
    End If

    If resp.StatusCode = 410 Then
        Log("Delta state expired. Reconcile local edits and rebuild a fresh drive baseline; preserve the existing cache.")
        Return
    End If

    If resp.StatusCode <> 200 Then
        Log("Unexpected HTTP status: " & resp.StatusCode)
        Log("Request ID: " & resp.GetHeaderField("request-id"))
        If resp.StatusCode = 429 Then
            Log("Retry-After: " & resp.GetHeaderField("Retry-After"))
        End If

        If resp.StatusCode = 401 Then
            Log("Refresh the Graph access token or authorize again.")
        End If

        Return
    End If

    success = result.Load(resp.BodyStr)
    If success <> True Then
        Log("Expected a well-formed JSON response.")
        Return
    End If

    If result.JsonTypeOf("value") <> 4 Then
        Log("Expected a value array; checkpoint unchanged.")
        Return
    End If

    '  Exactly one continuation member must be a nonempty string.
    Dim nextType As Int = result.JsonTypeOf(Chr(34) & "@odata.nextLink" & Chr(34))
    Dim deltaType As Int = result.JsonTypeOf(Chr(34) & "@odata.deltaLink" & Chr(34))
    Dim finished As Boolean = False
    Dim resumeUrl As String
    If (nextType = 1) And (deltaType = -1) Then
        resumeUrl = result.StringOf(Chr(34) & "@odata.nextLink" & Chr(34))
    Else
        If (deltaType <> 1) Or (nextType <> -1) Then
            Log("Invalid delta continuation; checkpoint unchanged.")
            Return
        End If

        resumeUrl = result.StringOf(Chr(34) & "@odata.deltaLink" & Chr(34))
        finished = True
    End If

    link.Clear
    link.Append(resumeUrl)
    If link.StartsWith("https://graph.microsoft.com/v1.0/", True) <> True Then
        Log("Invalid continuation URL; checkpoint unchanged.")
        Return
    End If

    success = previous.Load(state.Emit)
    If success <> True Then
        Log("Could not snapshot the previous checkpoint.")
        Return
    End If

    Dim i As Int = 0
    Do While (i < result.SizeOfArray("value"))
        result.I = i
        If (result.JsonTypeOf("value[i].id") <> 1) Or (result.StringOfEquals("value[i].id", "", True) = True) Then
            Log("Expected a nonempty value[i].id in the JSON.")
            Return
        End If

        Dim itemId As String = result.StringOf("value[i].id")
        Dim itemKey As String = hash.HashStringENC(itemId)
        If hash.LastMethodSuccess <> True Then
            Log("Could not form a local record key.")
            Return
        End If

        '  Hash only for a JSON-safe local key. Preserve the original opaque ID in the record.
        itemPath.Clear
        itemPath.Append("items.")
        itemPath.Append(itemKey)
        If state.JsonTypeOf(itemPath.GetAsString) <> 3 Then
            state.UpdateNewObject(itemPath.GetAsString)
        End If

        itemPath.Append(".")
        state.PathPrefix = itemPath.GetAsString
        state.UpdateString("id", itemId)
        If result.JsonTypeOf("value[i].deleted") = 3 Then
            '  Retain a tombstone; this example does not delete local files or folders.
            '  Process folder deletion only after the full round and only when the folder is empty.
            state.UpdateBool("removed", True)
            Log("Removed from the local view: " & itemId)
        Else
            state.UpdateBool("removed", False)
            If result.HasMember("value[i].name") = True Then
                If (result.JsonTypeOf("value[i].name") <> 1) Or (result.StringOfEquals("value[i].name", "", True) = True) Then
                    Log("Expected a nonempty value[i].name in the JSON.")
                    Return
                End If

                state.UpdateString("name", result.StringOf("value[i].name"))
            End If

            If result.HasMember("value[i].eTag") = True Then
                If (result.JsonTypeOf("value[i].eTag") <> 1) Or (result.StringOfEquals("value[i].eTag", "", True) = True) Then
                    Log("Expected a nonempty value[i].eTag in the JSON.")
                    Return
                End If

                state.UpdateString("eTag", result.StringOf("value[i].eTag"))
            End If

            If result.HasMember("value[i].parentReference.id") = True Then
                If (result.JsonTypeOf("value[i].parentReference.id") <> 1) Or (result.StringOfEquals("value[i].parentReference.id", "", True) = True) Then
                    Log("Expected a nonempty value[i].parentReference.id in the JSON.")
                    Return
                End If

                state.UpdateString("parentReference.id", result.StringOf("value[i].parentReference.id"))
            End If

            If result.HasMember("value[i].parentReference.driveId") = True Then
                If (result.JsonTypeOf("value[i].parentReference.driveId") <> 1) Or (result.StringOfEquals("value[i].parentReference.driveId", "", True) = True) Then
                    Log("Expected a nonempty value[i].parentReference.driveId in the JSON.")
                    Return
                End If

                state.UpdateString("parentReference.driveId", result.StringOf("value[i].parentReference.driveId"))
            End If

            '  Omitted fields are unchanged. Do not erase an earlier name or parent on a partial delta.
            '  Keep large sizes as decimal text in this demonstration's local index.
            If result.HasMember("value[i].size") = True Then
                state.UpdateString("sizeBytes", result.StringOf("value[i].size"))
            End If

            If result.JsonTypeOf("value[i].folder") = 3 Then
                state.UpdateString("kind", "folder")
            End If

            If result.JsonTypeOf("value[i].file") = 3 Then
                state.UpdateString("kind", "file")
            End If

            state.PathPrefix = ""
            Log("Updated local item: " & itemId)
        End If

        state.PathPrefix = ""
        i = i + 1
    Loop
    state.UpdateString("resumeUrl", resumeUrl)
    state.UpdateBool("roundComplete", finished)
    '  Save the data and cursor in one document. The backup contains the matching previous pair.
    success = previous.WriteFile(backupPath)
    If success <> True Then
        Log("Could not back up the previous checkpoint; no replacement attempted.")
        Return
    End If

    success = state.WriteFile(cachePath)
    If success <> True Then
        Log("Checkpoint write failed. Restore the private .bak before continuing.")
        Return
    End If

    pageCount = pageCount + 1
    If finished = True Then
        Log("Synchronization round complete; saved the delta link for the next run.")
        Return
    End If

Loop
Log("Paused after 100 pages; the saved nextLink resumes on the next run.")