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 VBScript Downloads
Dim fso, outFile
Set fso = CreateObject("Scripting.FileSystemObject")
'Create a Unicode (utf-16) output text file.
Set outFile = fso.CreateTextFile("output.txt", True, True)
success = 0
' Assumes Chilkat is unlocked. See Global Unlock Sample.
success = 0
' Obtain a delegated Microsoft Graph token using the calendar authorization example.
' See Authorize Outlook Calendar with OAuth2 and PKCE.
set token = CreateObject("Chilkat.JsonObject")
token.Strict = 1
success = token.LoadFile("qa_data/tokens/outlookCalendar.json")
If (success <> 1) Then
outFile.WriteLine("Could not read the private calendar token cache.")
WScript.Quit
End If
If ((token.JsonTypeOf("access_token") <> 1) Or (token.StringOfEquals("access_token","",1) = 1)) Then
outFile.WriteLine("Expected a nonempty access_token in the JSON.")
WScript.Quit
End If
set http = CreateObject("Chilkat.Http")
http.AuthToken = token.StringOf("access_token")
http.RequireSslCertVerify = 1
http.FollowRedirects = 0
http.ConnectTimeout = 20
http.ReadTimeout = 30
http.SetRequestHeader "Accept","application/json"
set resp = CreateObject("Chilkat.HttpResponse")
set result = CreateObject("Chilkat.JsonObject")
result.Strict = 1
http.SetRequestHeader "Prefer","outlook.timezone=""UTC"", IdType=""ImmutableId"", odata.maxpagesize=50"
set fac = CreateObject("Chilkat.FileAccess")
success = fac.DirEnsureExists("qa_data/outlookCalendar")
If (success <> 1) Then
outFile.WriteLine("Could not create the private synchronization directory.")
WScript.Quit
End If
cachePath = "qa_data/outlookCalendar/calendar-sync.json"
backupPath = "qa_data/outlookCalendar/calendar-sync.json.bak"
set state = CreateObject("Chilkat.JsonObject")
state.Strict = 1
If (fac.FileExists(cachePath) = 1) Then
success = state.LoadFile(cachePath)
If (success <> 1) Then
outFile.WriteLine("Invalid checkpoint; recover the matching data and cursor from the private .bak file before continuing.")
WScript.Quit
End If
If ((state.JsonTypeOf("resumeUrl") <> 1) Or (state.StringOfEquals("resumeUrl","",1) = 1)) Then
outFile.WriteLine("Expected a nonempty resumeUrl in the JSON.")
WScript.Quit
End If
If ((state.JsonTypeOf("startDateTime") <> 1) Or (state.StringOfEquals("startDateTime","",1) = 1)) Then
outFile.WriteLine("Expected a nonempty startDateTime in the JSON.")
WScript.Quit
End If
If ((state.JsonTypeOf("endDateTime") <> 1) Or (state.StringOfEquals("endDateTime","",1) = 1)) Then
outFile.WriteLine("Expected a nonempty endDateTime in the JSON.")
WScript.Quit
End If
If (state.JsonTypeOf("items") <> 3) Then
outFile.WriteLine("Expected an items object in the checkpoint.")
WScript.Quit
End If
Else
set windowTime = CreateObject("Chilkat.CkDateTime")
success = windowTime.SetFromCurrentSystemTime()
If (success <> 1) Then
outFile.WriteLine("Could not get the current time.")
WScript.Quit
End If
windowStart = windowTime.GetAsTimestamp(0)
success = windowTime.AddDays(30)
If (success <> 1) Then
outFile.WriteLine("Could not calculate the window end.")
WScript.Quit
End If
windowEnd = windowTime.GetAsTimestamp(0)
set endpoint = CreateObject("Chilkat.StringBuilder")
success = endpoint.Append("https://graph.microsoft.com/v1.0/me/calendarView/delta?startDateTime=")
success = endpoint.Append(http.UrlEncode(windowStart))
success = endpoint.Append("&endDateTime=")
success = endpoint.Append(http.UrlEncode(windowEnd))
success = state.UpdateString("startDateTime",windowStart)
success = state.UpdateString("endDateTime",windowEnd)
success = state.UpdateString("resumeUrl",endpoint.GetAsString())
success = state.UpdateNewObject("items")
End If
set hash = CreateObject("Chilkat.Crypt2")
hash.HashAlgorithm = "sha256"
hash.Charset = "utf-8"
hash.EncodingMode = "hex"
set link = CreateObject("Chilkat.StringBuilder")
set itemPath = CreateObject("Chilkat.StringBuilder")
set seenLinks = CreateObject("Chilkat.Hashtable")
set previous = CreateObject("Chilkat.JsonObject")
previous.Strict = 1
pageCount = 0
Do While (pageCount < 100)
url = state.StringOf("resumeUrl")
link.Clear
success = link.Append(url)
If (link.StartsWith("https://graph.microsoft.com/v1.0/",1) <> 1) Then
outFile.WriteLine("Unexpected continuation host or API version; no request sent.")
WScript.Quit
End If
If (seenLinks.Contains(url) = 1) Then
outFile.WriteLine("Repeated continuation URL; stopping.")
WScript.Quit
End If
success = seenLinks.AddInt(url,1)
success = http.HttpNoBody("GET",url,resp)
' A false result can still include an HTTP error response.
If ((success <> 1) And (resp.StatusCode = 0)) Then
outFile.WriteLine("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.")
WScript.Quit
End If
If (resp.StatusCode <> 200) Then
outFile.WriteLine("Unexpected HTTP status: " & resp.StatusCode)
outFile.WriteLine("Request ID: " & resp.GetHeaderField("request-id"))
If (resp.StatusCode = 429) Then
outFile.WriteLine("Retry-After: " & resp.GetHeaderField("Retry-After"))
End If
If (resp.StatusCode = 401) Then
outFile.WriteLine("Refresh the Graph access token or authorize again.")
End If
WScript.Quit
End If
success = result.Load(resp.BodyStr)
If (success <> 1) Then
outFile.WriteLine("Expected a well-formed JSON response.")
WScript.Quit
End If
If (result.JsonTypeOf("value") <> 4) Then
outFile.WriteLine("Expected a value array; checkpoint unchanged.")
WScript.Quit
End If
' Exactly one continuation member must be a nonempty string.
nextType = result.JsonTypeOf("""@odata.nextLink""")
deltaType = result.JsonTypeOf("""@odata.deltaLink""")
finished = 0
If ((nextType = 1) And (deltaType = -1)) Then
resumeUrl = result.StringOf("""@odata.nextLink""")
Else
If ((deltaType <> 1) Or (nextType <> -1)) Then
outFile.WriteLine("Invalid delta continuation; checkpoint unchanged.")
WScript.Quit
End If
resumeUrl = result.StringOf("""@odata.deltaLink""")
finished = 1
End If
link.Clear
success = link.Append(resumeUrl)
If (link.StartsWith("https://graph.microsoft.com/v1.0/",1) <> 1) Then
outFile.WriteLine("Invalid continuation URL; checkpoint unchanged.")
WScript.Quit
End If
success = previous.Load(state.Emit())
If (success <> 1) Then
outFile.WriteLine("Could not snapshot the previous checkpoint.")
WScript.Quit
End If
i = 0
Do While (i < result.SizeOfArray("value"))
result.I = i
If ((result.JsonTypeOf("value[i].id") <> 1) Or (result.StringOfEquals("value[i].id","",1) = 1)) Then
outFile.WriteLine("Expected a nonempty value[i].id in the JSON.")
WScript.Quit
End If
eventId = result.StringOf("value[i].id")
itemKey = hash.HashStringENC(eventId)
If (hash.LastMethodSuccess <> 1) Then
outFile.WriteLine("Could not form a local record key.")
WScript.Quit
End If
' Hash only for a JSON-safe local key. Preserve the original opaque ID in the record.
itemPath.Clear
success = itemPath.Append("items.")
success = itemPath.Append(itemKey)
If (state.JsonTypeOf(itemPath.GetAsString()) <> 3) Then
success = state.UpdateNewObject(itemPath.GetAsString())
End If
success = itemPath.Append(".")
state.PathPrefix = itemPath.GetAsString()
success = state.UpdateString("id",eventId)
If (result.JsonTypeOf("value[i].@removed") = 3) Then
' Hide records with removed=true from the local date-range view.
success = state.UpdateBool("removed",1)
outFile.WriteLine("Removed from the local view: " & eventId)
Else
success = state.UpdateBool("removed",0)
If (result.JsonTypeOf("value[i].subject") = 1) Then
success = state.UpdateString("subject",result.StringOf("value[i].subject"))
End If
If (result.JsonTypeOf("value[i].type") = 1) Then
success = state.UpdateString("type",result.StringOf("value[i].type"))
End If
If (result.JsonTypeOf("value[i].start.dateTime") = 1) Then
success = state.UpdateString("start.dateTime",result.StringOf("value[i].start.dateTime"))
End If
If (result.JsonTypeOf("value[i].start.timeZone") = 1) Then
success = state.UpdateString("start.timeZone",result.StringOf("value[i].start.timeZone"))
End If
If (result.JsonTypeOf("value[i].end.dateTime") = 1) Then
success = state.UpdateString("end.dateTime",result.StringOf("value[i].end.dateTime"))
End If
If (result.JsonTypeOf("value[i].end.timeZone") = 1) Then
success = state.UpdateString("end.timeZone",result.StringOf("value[i].end.timeZone"))
End If
state.PathPrefix = ""
outFile.WriteLine("Updated local event: " & eventId)
End If
state.PathPrefix = ""
i = i + 1
Loop
success = state.UpdateString("resumeUrl",resumeUrl)
success = 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 <> 1) Then
outFile.WriteLine("Could not back up the previous checkpoint; no replacement attempted.")
WScript.Quit
End If
success = state.WriteFile(cachePath)
If (success <> 1) Then
outFile.WriteLine("Checkpoint write failed. Restore the private .bak before continuing.")
WScript.Quit
End If
pageCount = pageCount + 1
If (finished = 1) Then
outFile.WriteLine("Synchronization round complete; saved the delta link for the next run.")
WScript.Quit
End If
Loop
outFile.WriteLine("Paused after 100 pages; the saved nextLink resumes on the next run.")
outFile.Close