Sample code for 30+ languages & platforms
PowerBuilder 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 PowerBuilder Downloads

PowerBuilder
integer li_rc
long li_Success
oleobject loo_Token
oleobject loo_Http
oleobject loo_Resp
oleobject loo_Result
string ls_DriveId
string ls_AccountKey
oleobject loo_Fac
string ls_CachePath
string ls_BackupPath
oleobject loo_State
oleobject loo_Endpoint
oleobject loo_Hash
oleobject loo_Link
oleobject loo_ItemPath
oleobject loo_SeenLinks
oleobject loo_Previous
long li_PageCount
string ls_Url
long li_NextType
long li_DeltaType
long li_Finished
string ls_ResumeUrl
long i
string ls_ItemId
string ls_ItemKey

li_Success = 0

//  Assumes Chilkat is unlocked. See Global Unlock Sample.
li_Success = 0
//  Obtain a delegated Graph token with this example's file permissions.
//  See OneDrive OAuth2 with PKCE.
loo_Token = create oleobject
li_rc = loo_Token.ConnectToNewObject("Chilkat.JsonObject")
if li_rc < 0 then
    destroy loo_Token
    MessageBox("Error","Connecting to COM object failed")
    return
end if
loo_Token.Strict = 1
li_Success = loo_Token.LoadFile("qa_data/tokens/oneDrive.json")
if li_Success <> 1 then
    Write-Debug "Could not load the private OneDrive token cache."
    destroy loo_Token
    return
end if

if (loo_Token.JsonTypeOf("access_token") <> 1) OR (loo_Token.StringOfEquals("access_token","",1) = 1) then
    Write-Debug "Expected a nonempty access_token in the JSON."
    destroy loo_Token
    return
end if

loo_Http = create oleobject
li_rc = loo_Http.ConnectToNewObject("Chilkat.Http")

loo_Http.AuthToken = loo_Token.StringOf("access_token")
loo_Http.RequireSslCertVerify = 1
loo_Http.FollowRedirects = 0
loo_Http.ConnectTimeout = 20
loo_Http.ReadTimeout = 120
loo_Http.SetRequestHeader("Accept","application/json")
loo_Resp = create oleobject
li_rc = loo_Resp.ConnectToNewObject("Chilkat.HttpResponse")

loo_Result = create oleobject
li_rc = loo_Result.ConnectToNewObject("Chilkat.JsonObject")

loo_Result.Strict = 1
ls_DriveId = "YOUR_DRIVE_ID"
//  Use a distinct stable application account key and cache path per account.
ls_AccountKey = "YOUR_LOCAL_ACCOUNT_KEY"
loo_Fac = create oleobject
li_rc = loo_Fac.ConnectToNewObject("Chilkat.FileAccess")

li_Success = loo_Fac.DirEnsureExists("qa_data/oneDrive")
if li_Success <> 1 then
    Write-Debug "Could not create the private synchronization directory."
    destroy loo_Token
    destroy loo_Http
    destroy loo_Resp
    destroy loo_Result
    destroy loo_Fac
    return
end if

ls_CachePath = "qa_data/oneDrive/items-sync.json"
ls_BackupPath = "qa_data/oneDrive/items-sync.json.bak"
loo_State = create oleobject
li_rc = loo_State.ConnectToNewObject("Chilkat.JsonObject")

loo_State.Strict = 1
if loo_Fac.FileExists(ls_CachePath) = 1 then
    li_Success = loo_State.LoadFile(ls_CachePath)
    if li_Success <> 1 then
        Write-Debug "Invalid checkpoint; recover the matching data and cursor from the private .bak file before continuing."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        return
    end if

    if (loo_State.JsonTypeOf("resumeUrl") <> 1) OR (loo_State.StringOfEquals("resumeUrl","",1) = 1) then
        Write-Debug "Expected a nonempty resumeUrl in the JSON."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        return
    end if

    if (loo_State.JsonTypeOf("driveId") <> 1) OR (loo_State.StringOfEquals("driveId","",1) = 1) then
        Write-Debug "Expected a nonempty driveId in the JSON."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        return
    end if

    if loo_State.StringOfEquals("driveId",ls_DriveId,1) <> 1 then
        Write-Debug "This checkpoint belongs to another drive. Use a separate cache."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        return
    end if

    if loo_State.StringOfEquals("accountKey",ls_AccountKey,1) <> 1 then
        Write-Debug "This checkpoint belongs to another account; nothing requested."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        return
    end if

    if loo_State.JsonTypeOf("items") <> 3 then
        Write-Debug "Expected an items object in the checkpoint."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        return
    end if

else
    loo_Endpoint = create oleobject
    li_rc = loo_Endpoint.ConnectToNewObject("Chilkat.StringBuilder")

    loo_Endpoint.Append("https://graph.microsoft.com/v1.0/drives/")
    loo_Endpoint.Append(loo_Http.UrlEncode(ls_DriveId))
    loo_Endpoint.Append("/root/delta?$select=id,name,size,parentReference,file,folder,eTag,deleted")
    loo_State.UpdateString("driveId",ls_DriveId)
    loo_State.UpdateString("accountKey",ls_AccountKey)
    loo_State.UpdateString("resumeUrl",loo_Endpoint.GetAsString())
    loo_State.UpdateNewObject("items")
end if

loo_Hash = create oleobject
li_rc = loo_Hash.ConnectToNewObject("Chilkat.Crypt2")

loo_Hash.HashAlgorithm = "sha256"
loo_Hash.Charset = "utf-8"
loo_Hash.EncodingMode = "hex"
loo_Link = create oleobject
li_rc = loo_Link.ConnectToNewObject("Chilkat.StringBuilder")

loo_ItemPath = create oleobject
li_rc = loo_ItemPath.ConnectToNewObject("Chilkat.StringBuilder")

loo_SeenLinks = create oleobject
li_rc = loo_SeenLinks.ConnectToNewObject("Chilkat.Hashtable")

loo_Previous = create oleobject
li_rc = loo_Previous.ConnectToNewObject("Chilkat.JsonObject")

loo_Previous.Strict = 1
li_PageCount = 0
do while (li_PageCount < 100)
    ls_Url = loo_State.StringOf("resumeUrl")
    loo_Link.Clear()
    loo_Link.Append(ls_Url)
    if loo_Link.StartsWith("https://graph.microsoft.com/v1.0/",1) <> 1 then
        Write-Debug "Unexpected continuation host or API version; no request sent."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

    if loo_SeenLinks.Contains(ls_Url) = 1 then
        Write-Debug "Repeated continuation URL; stopping."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

    loo_SeenLinks.AddInt(ls_Url,1)
    li_Success = loo_Http.HttpNoBody("GET",ls_Url,loo_Resp)
    //  A false result can still include an HTTP error response.
    if (li_Success <> 1) AND (loo_Resp.StatusCode = 0) then
        Write-Debug "No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

    if loo_Resp.StatusCode = 410 then
        Write-Debug "Delta state expired. Reconcile local edits and rebuild a fresh drive baseline; preserve the existing cache."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

    if loo_Resp.StatusCode <> 200 then
        Write-Debug "Unexpected HTTP status: " + string(loo_Resp.StatusCode)
        Write-Debug "Request ID: " + loo_Resp.GetHeaderField("request-id")
        if loo_Resp.StatusCode = 429 then
            Write-Debug "Retry-After: " + loo_Resp.GetHeaderField("Retry-After")
        end if

        if loo_Resp.StatusCode = 401 then
            Write-Debug "Refresh the Graph access token or authorize again."
        end if

        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

    li_Success = loo_Result.Load(loo_Resp.BodyStr)
    if li_Success <> 1 then
        Write-Debug "Expected a well-formed JSON response."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

    if loo_Result.JsonTypeOf("value") <> 4 then
        Write-Debug "Expected a value array; checkpoint unchanged."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

    //  Exactly one continuation member must be a nonempty string.
    li_NextType = loo_Result.JsonTypeOf("~"@odata.nextLink~"")
    li_DeltaType = loo_Result.JsonTypeOf("~"@odata.deltaLink~"")
    li_Finished = 0

    if (li_NextType = 1) AND (li_DeltaType = -1) then
        ls_ResumeUrl = loo_Result.StringOf("~"@odata.nextLink~"")
    else
        if (li_DeltaType <> 1) OR (li_NextType <> -1) then
            Write-Debug "Invalid delta continuation; checkpoint unchanged."
            destroy loo_Token
            destroy loo_Http
            destroy loo_Resp
            destroy loo_Result
            destroy loo_Fac
            destroy loo_State
            destroy loo_Endpoint
            destroy loo_Hash
            destroy loo_Link
            destroy loo_ItemPath
            destroy loo_SeenLinks
            destroy loo_Previous
            return
        end if

        ls_ResumeUrl = loo_Result.StringOf("~"@odata.deltaLink~"")
        li_Finished = 1
    end if

    loo_Link.Clear()
    loo_Link.Append(ls_ResumeUrl)
    if loo_Link.StartsWith("https://graph.microsoft.com/v1.0/",1) <> 1 then
        Write-Debug "Invalid continuation URL; checkpoint unchanged."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

    li_Success = loo_Previous.Load(loo_State.Emit())
    if li_Success <> 1 then
        Write-Debug "Could not snapshot the previous checkpoint."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

    i = 0
    do while (i < loo_Result.SizeOfArray("value"))
        loo_Result.I = i
        if (loo_Result.JsonTypeOf("value[i].id") <> 1) OR (loo_Result.StringOfEquals("value[i].id","",1) = 1) then
            Write-Debug "Expected a nonempty value[i].id in the JSON."
            destroy loo_Token
            destroy loo_Http
            destroy loo_Resp
            destroy loo_Result
            destroy loo_Fac
            destroy loo_State
            destroy loo_Endpoint
            destroy loo_Hash
            destroy loo_Link
            destroy loo_ItemPath
            destroy loo_SeenLinks
            destroy loo_Previous
            return
        end if

        ls_ItemId = loo_Result.StringOf("value[i].id")
        ls_ItemKey = loo_Hash.HashStringENC(ls_ItemId)
        if loo_Hash.LastMethodSuccess <> 1 then
            Write-Debug "Could not form a local record key."
            destroy loo_Token
            destroy loo_Http
            destroy loo_Resp
            destroy loo_Result
            destroy loo_Fac
            destroy loo_State
            destroy loo_Endpoint
            destroy loo_Hash
            destroy loo_Link
            destroy loo_ItemPath
            destroy loo_SeenLinks
            destroy loo_Previous
            return
        end if

        //  Hash only for a JSON-safe local key. Preserve the original opaque ID in the record.
        loo_ItemPath.Clear()
        loo_ItemPath.Append("items.")
        loo_ItemPath.Append(ls_ItemKey)
        if loo_State.JsonTypeOf(loo_ItemPath.GetAsString()) <> 3 then
            loo_State.UpdateNewObject(loo_ItemPath.GetAsString())
        end if

        loo_ItemPath.Append(".")
        loo_State.PathPrefix = loo_ItemPath.GetAsString()
        loo_State.UpdateString("id",ls_ItemId)
        if loo_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.
            loo_State.UpdateBool("removed",1)
            Write-Debug "Removed from the local view: " + ls_ItemId
        else
            loo_State.UpdateBool("removed",0)
            if loo_Result.HasMember("value[i].name") = 1 then
                if (loo_Result.JsonTypeOf("value[i].name") <> 1) OR (loo_Result.StringOfEquals("value[i].name","",1) = 1) then
                    Write-Debug "Expected a nonempty value[i].name in the JSON."
                    destroy loo_Token
                    destroy loo_Http
                    destroy loo_Resp
                    destroy loo_Result
                    destroy loo_Fac
                    destroy loo_State
                    destroy loo_Endpoint
                    destroy loo_Hash
                    destroy loo_Link
                    destroy loo_ItemPath
                    destroy loo_SeenLinks
                    destroy loo_Previous
                    return
                end if

                loo_State.UpdateString("name",loo_Result.StringOf("value[i].name"))
            end if

            if loo_Result.HasMember("value[i].eTag") = 1 then
                if (loo_Result.JsonTypeOf("value[i].eTag") <> 1) OR (loo_Result.StringOfEquals("value[i].eTag","",1) = 1) then
                    Write-Debug "Expected a nonempty value[i].eTag in the JSON."
                    destroy loo_Token
                    destroy loo_Http
                    destroy loo_Resp
                    destroy loo_Result
                    destroy loo_Fac
                    destroy loo_State
                    destroy loo_Endpoint
                    destroy loo_Hash
                    destroy loo_Link
                    destroy loo_ItemPath
                    destroy loo_SeenLinks
                    destroy loo_Previous
                    return
                end if

                loo_State.UpdateString("eTag",loo_Result.StringOf("value[i].eTag"))
            end if

            if loo_Result.HasMember("value[i].parentReference.id") = 1 then
                if (loo_Result.JsonTypeOf("value[i].parentReference.id") <> 1) OR (loo_Result.StringOfEquals("value[i].parentReference.id","",1) = 1) then
                    Write-Debug "Expected a nonempty value[i].parentReference.id in the JSON."
                    destroy loo_Token
                    destroy loo_Http
                    destroy loo_Resp
                    destroy loo_Result
                    destroy loo_Fac
                    destroy loo_State
                    destroy loo_Endpoint
                    destroy loo_Hash
                    destroy loo_Link
                    destroy loo_ItemPath
                    destroy loo_SeenLinks
                    destroy loo_Previous
                    return
                end if

                loo_State.UpdateString("parentReference.id",loo_Result.StringOf("value[i].parentReference.id"))
            end if

            if loo_Result.HasMember("value[i].parentReference.driveId") = 1 then
                if (loo_Result.JsonTypeOf("value[i].parentReference.driveId") <> 1) OR (loo_Result.StringOfEquals("value[i].parentReference.driveId","",1) = 1) then
                    Write-Debug "Expected a nonempty value[i].parentReference.driveId in the JSON."
                    destroy loo_Token
                    destroy loo_Http
                    destroy loo_Resp
                    destroy loo_Result
                    destroy loo_Fac
                    destroy loo_State
                    destroy loo_Endpoint
                    destroy loo_Hash
                    destroy loo_Link
                    destroy loo_ItemPath
                    destroy loo_SeenLinks
                    destroy loo_Previous
                    return
                end if

                loo_State.UpdateString("parentReference.driveId",loo_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 loo_Result.HasMember("value[i].size") = 1 then
                loo_State.UpdateString("sizeBytes",loo_Result.StringOf("value[i].size"))
            end if

            if loo_Result.JsonTypeOf("value[i].folder") = 3 then
                loo_State.UpdateString("kind","folder")
            end if

            if loo_Result.JsonTypeOf("value[i].file") = 3 then
                loo_State.UpdateString("kind","file")
            end if

            loo_State.PathPrefix = ""
            Write-Debug "Updated local item: " + ls_ItemId
        end if

        loo_State.PathPrefix = ""
        i = i + 1
    loop
    loo_State.UpdateString("resumeUrl",ls_ResumeUrl)
    loo_State.UpdateBool("roundComplete",li_Finished)
    //  Save the data and cursor in one document. The backup contains the matching previous pair.
    li_Success = loo_Previous.WriteFile(ls_BackupPath)
    if li_Success <> 1 then
        Write-Debug "Could not back up the previous checkpoint; no replacement attempted."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

    li_Success = loo_State.WriteFile(ls_CachePath)
    if li_Success <> 1 then
        Write-Debug "Checkpoint write failed. Restore the private .bak before continuing."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

    li_PageCount = li_PageCount + 1
    if li_Finished = 1 then
        Write-Debug "Synchronization round complete; saved the delta link for the next run."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

loop
Write-Debug "Paused after 100 pages; the saved nextLink resumes on the next run."


destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Fac
destroy loo_State
destroy loo_Endpoint
destroy loo_Hash
destroy loo_Link
destroy loo_ItemPath
destroy loo_SeenLinks
destroy loo_Previous