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.
Chilkat PowerBuilder Downloads
integer li_rc
long li_Success
oleobject loo_Token
oleobject loo_Http
oleobject loo_Resp
oleobject loo_Result
oleobject loo_Fac
string ls_CachePath
string ls_BackupPath
oleobject loo_State
oleobject loo_WindowTime
string ls_WindowStart
string ls_WindowEnd
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_EventId
string ls_ItemKey
li_Success = 0
// Assumes Chilkat is unlocked. See Global Unlock Sample.
li_Success = 0
// Obtain a delegated Microsoft Graph token using the calendar authorization example.
// See Authorize Outlook Calendar with OAuth2 and 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/outlookCalendar.json")
if li_Success <> 1 then
Write-Debug "Could not read the private calendar 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 = 30
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
loo_Http.SetRequestHeader("Prefer","outlook.timezone=~"UTC~", IdType=~"ImmutableId~", odata.maxpagesize=50")
loo_Fac = create oleobject
li_rc = loo_Fac.ConnectToNewObject("Chilkat.FileAccess")
li_Success = loo_Fac.DirEnsureExists("qa_data/outlookCalendar")
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/outlookCalendar/calendar-sync.json"
ls_BackupPath = "qa_data/outlookCalendar/calendar-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("startDateTime") <> 1) OR (loo_State.StringOfEquals("startDateTime","",1) = 1) then
Write-Debug "Expected a nonempty startDateTime 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("endDateTime") <> 1) OR (loo_State.StringOfEquals("endDateTime","",1) = 1) then
Write-Debug "Expected a nonempty endDateTime 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("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_WindowTime = create oleobject
li_rc = loo_WindowTime.ConnectToNewObject("Chilkat.CkDateTime")
li_Success = loo_WindowTime.SetFromCurrentSystemTime()
if li_Success <> 1 then
Write-Debug "Could not get the current time."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Fac
destroy loo_State
destroy loo_WindowTime
return
end if
ls_WindowStart = loo_WindowTime.GetAsTimestamp(0)
li_Success = loo_WindowTime.AddDays(30)
if li_Success <> 1 then
Write-Debug "Could not calculate the window end."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Fac
destroy loo_State
destroy loo_WindowTime
return
end if
ls_WindowEnd = loo_WindowTime.GetAsTimestamp(0)
loo_Endpoint = create oleobject
li_rc = loo_Endpoint.ConnectToNewObject("Chilkat.StringBuilder")
loo_Endpoint.Append("https://graph.microsoft.com/v1.0/me/calendarView/delta?startDateTime=")
loo_Endpoint.Append(loo_Http.UrlEncode(ls_WindowStart))
loo_Endpoint.Append("&endDateTime=")
loo_Endpoint.Append(loo_Http.UrlEncode(ls_WindowEnd))
loo_State.UpdateString("startDateTime",ls_WindowStart)
loo_State.UpdateString("endDateTime",ls_WindowEnd)
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.StringArray")
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_WindowTime
destroy loo_Endpoint
destroy loo_Hash
destroy loo_Link
destroy loo_ItemPath
destroy loo_SeenLinks
destroy loo_Previous
return
end if
if loo_SeenLinks.Find(ls_Url,0) >= 0 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_WindowTime
destroy loo_Endpoint
destroy loo_Hash
destroy loo_Link
destroy loo_ItemPath
destroy loo_SeenLinks
destroy loo_Previous
return
end if
loo_SeenLinks.Append(ls_Url)
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_WindowTime
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_WindowTime
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_WindowTime
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_WindowTime
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_WindowTime
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_WindowTime
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_WindowTime
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_WindowTime
destroy loo_Endpoint
destroy loo_Hash
destroy loo_Link
destroy loo_ItemPath
destroy loo_SeenLinks
destroy loo_Previous
return
end if
ls_EventId = loo_Result.StringOf("value[i].id")
ls_ItemKey = loo_Hash.HashStringENC(ls_EventId)
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_WindowTime
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_EventId)
if loo_Result.JsonTypeOf("value[i].@removed") = 3 then
// Hide records with removed=true from the local date-range view.
loo_State.UpdateBool("removed",1)
Write-Debug "Removed from the local view: " + ls_EventId
else
loo_State.UpdateBool("removed",0)
if loo_Result.JsonTypeOf("value[i].subject") = 1 then
loo_State.UpdateString("subject",loo_Result.StringOf("value[i].subject"))
end if
if loo_Result.JsonTypeOf("value[i].type") = 1 then
loo_State.UpdateString("type",loo_Result.StringOf("value[i].type"))
end if
if loo_Result.JsonTypeOf("value[i].start.dateTime") = 1 then
loo_State.UpdateString("start.dateTime",loo_Result.StringOf("value[i].start.dateTime"))
end if
if loo_Result.JsonTypeOf("value[i].start.timeZone") = 1 then
loo_State.UpdateString("start.timeZone",loo_Result.StringOf("value[i].start.timeZone"))
end if
if loo_Result.JsonTypeOf("value[i].end.dateTime") = 1 then
loo_State.UpdateString("end.dateTime",loo_Result.StringOf("value[i].end.dateTime"))
end if
if loo_Result.JsonTypeOf("value[i].end.timeZone") = 1 then
loo_State.UpdateString("end.timeZone",loo_Result.StringOf("value[i].end.timeZone"))
end if
loo_State.PathPrefix = ""
Write-Debug "Updated local event: " + ls_EventId
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_WindowTime
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_WindowTime
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_WindowTime
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_WindowTime
destroy loo_Endpoint
destroy loo_Hash
destroy loo_Link
destroy loo_ItemPath
destroy loo_SeenLinks
destroy loo_Previous