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 Go Downloads
success := false
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success = false
// Obtain a delegated Microsoft Graph token using the calendar authorization example.
// See Authorize Outlook Calendar with OAuth2 and PKCE.
token := chilkat.NewJsonObject()
token.SetStrict(true)
success = token.LoadFile("qa_data/tokens/outlookCalendar.json")
if success != true {
fmt.Println("Could not read the private calendar token cache.")
token.DisposeJsonObject()
return
}
if (token.JsonTypeOf("access_token") != 1) || (token.StringOfEquals("access_token","",true) == true) {
fmt.Println("Expected a nonempty access_token in the JSON.")
token.DisposeJsonObject()
return
}
http := chilkat.NewHttp()
http.SetAuthToken(token.StringOf("access_token"))
http.SetRequireSslCertVerify(true)
http.SetFollowRedirects(false)
http.SetConnectTimeout(20)
http.SetReadTimeout(30)
http.SetRequestHeader("Accept","application/json")
resp := chilkat.NewHttpResponse()
result := chilkat.NewJsonObject()
result.SetStrict(true)
http.SetRequestHeader("Prefer","outlook.timezone=\"UTC\", IdType=\"ImmutableId\", odata.maxpagesize=50")
fac := chilkat.NewFileAccess()
success = fac.DirEnsureExists("qa_data/outlookCalendar")
if success != true {
fmt.Println("Could not create the private synchronization directory.")
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
return
}
cachePath := "qa_data/outlookCalendar/calendar-sync.json"
backupPath := "qa_data/outlookCalendar/calendar-sync.json.bak"
state := chilkat.NewJsonObject()
state.SetStrict(true)
if fac.FileExists(cachePath) == true {
success = state.LoadFile(cachePath)
if success != true {
fmt.Println("Invalid checkpoint; recover the matching data and cursor from the private .bak file before continuing.")
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
state.DisposeJsonObject()
return
}
if (state.JsonTypeOf("resumeUrl") != 1) || (state.StringOfEquals("resumeUrl","",true) == true) {
fmt.Println("Expected a nonempty resumeUrl in the JSON.")
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
state.DisposeJsonObject()
return
}
if (state.JsonTypeOf("startDateTime") != 1) || (state.StringOfEquals("startDateTime","",true) == true) {
fmt.Println("Expected a nonempty startDateTime in the JSON.")
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
state.DisposeJsonObject()
return
}
if (state.JsonTypeOf("endDateTime") != 1) || (state.StringOfEquals("endDateTime","",true) == true) {
fmt.Println("Expected a nonempty endDateTime in the JSON.")
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
state.DisposeJsonObject()
return
}
if state.JsonTypeOf("items") != 3 {
fmt.Println("Expected an items object in the checkpoint.")
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
state.DisposeJsonObject()
return
}
} else {
windowTime := chilkat.NewCkDateTime()
success = windowTime.SetFromCurrentSystemTime()
if success != true {
fmt.Println("Could not get the current time.")
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
state.DisposeJsonObject()
windowTime.DisposeCkDateTime()
return
}
windowStart := windowTime.GetAsTimestamp(false)
success = windowTime.AddDays(30)
if success != true {
fmt.Println("Could not calculate the window end.")
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
state.DisposeJsonObject()
windowTime.DisposeCkDateTime()
return
}
windowEnd := windowTime.GetAsTimestamp(false)
endpoint := chilkat.NewStringBuilder()
endpoint.Append("https://graph.microsoft.com/v1.0/me/calendarView/delta?startDateTime=")
endpoint.Append(*http.UrlEncode(*windowStart))
endpoint.Append("&endDateTime=")
endpoint.Append(*http.UrlEncode(*windowEnd))
state.UpdateString("startDateTime",*windowStart)
state.UpdateString("endDateTime",*windowEnd)
state.UpdateString("resumeUrl",*endpoint.GetAsString())
state.UpdateNewObject("items")
}
hash := chilkat.NewCrypt2()
hash.SetHashAlgorithm("sha256")
hash.SetCharset("utf-8")
hash.SetEncodingMode("hex")
link := chilkat.NewStringBuilder()
itemPath := chilkat.NewStringBuilder()
seenLinks := chilkat.NewStringArray()
previous := chilkat.NewJsonObject()
previous.SetStrict(true)
pageCount := 0
for (pageCount < 100) {
url := state.StringOf("resumeUrl")
link.Clear()
link.Append(*url)
if link.StartsWith("https://graph.microsoft.com/v1.0/",true) != true {
fmt.Println("Unexpected continuation host or API version; no request sent.")
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
state.DisposeJsonObject()
windowTime.DisposeCkDateTime()
endpoint.DisposeStringBuilder()
hash.DisposeCrypt2()
link.DisposeStringBuilder()
itemPath.DisposeStringBuilder()
seenLinks.DisposeStringArray()
previous.DisposeJsonObject()
return
}
if seenLinks.Find(*url,0) >= 0 {
fmt.Println("Repeated continuation URL; stopping.")
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
state.DisposeJsonObject()
windowTime.DisposeCkDateTime()
endpoint.DisposeStringBuilder()
hash.DisposeCrypt2()
link.DisposeStringBuilder()
itemPath.DisposeStringBuilder()
seenLinks.DisposeStringArray()
previous.DisposeJsonObject()
return
}
seenLinks.Append(*url)
success = http.HttpNoBody("GET",*url,resp)
// A false result can still include an HTTP error response.
if (success != true) && (resp.StatusCode() == 0) {
fmt.Println("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.")
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
state.DisposeJsonObject()
windowTime.DisposeCkDateTime()
endpoint.DisposeStringBuilder()
hash.DisposeCrypt2()
link.DisposeStringBuilder()
itemPath.DisposeStringBuilder()
seenLinks.DisposeStringArray()
previous.DisposeJsonObject()
return
}
if resp.StatusCode() != 200 {
fmt.Println("Unexpected HTTP status: ", resp.StatusCode())
fmt.Println("Request ID: ", *resp.GetHeaderField("request-id"))
if resp.StatusCode() == 429 {
fmt.Println("Retry-After: ", *resp.GetHeaderField("Retry-After"))
}
if resp.StatusCode() == 401 {
fmt.Println("Refresh the Graph access token or authorize again.")
}
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
state.DisposeJsonObject()
windowTime.DisposeCkDateTime()
endpoint.DisposeStringBuilder()
hash.DisposeCrypt2()
link.DisposeStringBuilder()
itemPath.DisposeStringBuilder()
seenLinks.DisposeStringArray()
previous.DisposeJsonObject()
return
}
success = result.Load(resp.BodyStr())
if success != true {
fmt.Println("Expected a well-formed JSON response.")
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
state.DisposeJsonObject()
windowTime.DisposeCkDateTime()
endpoint.DisposeStringBuilder()
hash.DisposeCrypt2()
link.DisposeStringBuilder()
itemPath.DisposeStringBuilder()
seenLinks.DisposeStringArray()
previous.DisposeJsonObject()
return
}
if result.JsonTypeOf("value") != 4 {
fmt.Println("Expected a value array; checkpoint unchanged.")
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
state.DisposeJsonObject()
windowTime.DisposeCkDateTime()
endpoint.DisposeStringBuilder()
hash.DisposeCrypt2()
link.DisposeStringBuilder()
itemPath.DisposeStringBuilder()
seenLinks.DisposeStringArray()
previous.DisposeJsonObject()
return
}
// Exactly one continuation member must be a nonempty string.
nextType := result.JsonTypeOf("\"@odata.nextLink\"")
deltaType := result.JsonTypeOf("\"@odata.deltaLink\"")
finished := false
var resumeUrl *string = new(string)
if (nextType == 1) && (deltaType == -1) {
resumeUrl = result.StringOf("\"@odata.nextLink\"")
} else {
if (deltaType != 1) || (nextType != -1) {
fmt.Println("Invalid delta continuation; checkpoint unchanged.")
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
state.DisposeJsonObject()
windowTime.DisposeCkDateTime()
endpoint.DisposeStringBuilder()
hash.DisposeCrypt2()
link.DisposeStringBuilder()
itemPath.DisposeStringBuilder()
seenLinks.DisposeStringArray()
previous.DisposeJsonObject()
return
}
resumeUrl = result.StringOf("\"@odata.deltaLink\"")
finished = true
}
link.Clear()
link.Append(*resumeUrl)
if link.StartsWith("https://graph.microsoft.com/v1.0/",true) != true {
fmt.Println("Invalid continuation URL; checkpoint unchanged.")
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
state.DisposeJsonObject()
windowTime.DisposeCkDateTime()
endpoint.DisposeStringBuilder()
hash.DisposeCrypt2()
link.DisposeStringBuilder()
itemPath.DisposeStringBuilder()
seenLinks.DisposeStringArray()
previous.DisposeJsonObject()
return
}
success = previous.Load(*state.Emit())
if success != true {
fmt.Println("Could not snapshot the previous checkpoint.")
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
state.DisposeJsonObject()
windowTime.DisposeCkDateTime()
endpoint.DisposeStringBuilder()
hash.DisposeCrypt2()
link.DisposeStringBuilder()
itemPath.DisposeStringBuilder()
seenLinks.DisposeStringArray()
previous.DisposeJsonObject()
return
}
i := 0
for (i < result.SizeOfArray("value")) {
result.SetI(i)
if (result.JsonTypeOf("value[i].id") != 1) || (result.StringOfEquals("value[i].id","",true) == true) {
fmt.Println("Expected a nonempty value[i].id in the JSON.")
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
state.DisposeJsonObject()
windowTime.DisposeCkDateTime()
endpoint.DisposeStringBuilder()
hash.DisposeCrypt2()
link.DisposeStringBuilder()
itemPath.DisposeStringBuilder()
seenLinks.DisposeStringArray()
previous.DisposeJsonObject()
return
}
eventId := result.StringOf("value[i].id")
itemKey := hash.HashStringENC(*eventId)
if hash.LastMethodSuccess() != true {
fmt.Println("Could not form a local record key.")
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
state.DisposeJsonObject()
windowTime.DisposeCkDateTime()
endpoint.DisposeStringBuilder()
hash.DisposeCrypt2()
link.DisposeStringBuilder()
itemPath.DisposeStringBuilder()
seenLinks.DisposeStringArray()
previous.DisposeJsonObject()
return
}
// 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 {
state.UpdateNewObject(*itemPath.GetAsString())
}
itemPath.Append(".")
state.SetPathPrefix(itemPath.GetAsString())
state.UpdateString("id",*eventId)
if result.JsonTypeOf("value[i].@removed") == 3 {
// Hide records with removed=true from the local date-range view.
state.UpdateBool("removed",true)
fmt.Println("Removed from the local view: ", *eventId)
} else {
state.UpdateBool("removed",false)
if result.JsonTypeOf("value[i].subject") == 1 {
state.UpdateString("subject",*result.StringOf("value[i].subject"))
}
if result.JsonTypeOf("value[i].type") == 1 {
state.UpdateString("type",*result.StringOf("value[i].type"))
}
if result.JsonTypeOf("value[i].start.dateTime") == 1 {
state.UpdateString("start.dateTime",*result.StringOf("value[i].start.dateTime"))
}
if result.JsonTypeOf("value[i].start.timeZone") == 1 {
state.UpdateString("start.timeZone",*result.StringOf("value[i].start.timeZone"))
}
if result.JsonTypeOf("value[i].end.dateTime") == 1 {
state.UpdateString("end.dateTime",*result.StringOf("value[i].end.dateTime"))
}
if result.JsonTypeOf("value[i].end.timeZone") == 1 {
state.UpdateString("end.timeZone",*result.StringOf("value[i].end.timeZone"))
}
state.SetPathPrefix("")
fmt.Println("Updated local event: ", *eventId)
}
state.SetPathPrefix("")
i = i + 1
}
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 {
fmt.Println("Could not back up the previous checkpoint; no replacement attempted.")
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
state.DisposeJsonObject()
windowTime.DisposeCkDateTime()
endpoint.DisposeStringBuilder()
hash.DisposeCrypt2()
link.DisposeStringBuilder()
itemPath.DisposeStringBuilder()
seenLinks.DisposeStringArray()
previous.DisposeJsonObject()
return
}
success = state.WriteFile(cachePath)
if success != true {
fmt.Println("Checkpoint write failed. Restore the private .bak before continuing.")
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
state.DisposeJsonObject()
windowTime.DisposeCkDateTime()
endpoint.DisposeStringBuilder()
hash.DisposeCrypt2()
link.DisposeStringBuilder()
itemPath.DisposeStringBuilder()
seenLinks.DisposeStringArray()
previous.DisposeJsonObject()
return
}
pageCount = pageCount + 1
if finished == true {
fmt.Println("Synchronization round complete; saved the delta link for the next run.")
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
state.DisposeJsonObject()
windowTime.DisposeCkDateTime()
endpoint.DisposeStringBuilder()
hash.DisposeCrypt2()
link.DisposeStringBuilder()
itemPath.DisposeStringBuilder()
seenLinks.DisposeStringArray()
previous.DisposeJsonObject()
return
}
}
fmt.Println("Paused after 100 pages; the saved nextLink resumes on the next run.")
token.DisposeJsonObject()
http.DisposeHttp()
resp.DisposeHttpResponse()
result.DisposeJsonObject()
fac.DisposeFileAccess()
state.DisposeJsonObject()
windowTime.DisposeCkDateTime()
endpoint.DisposeStringBuilder()
hash.DisposeCrypt2()
link.DisposeStringBuilder()
itemPath.DisposeStringBuilder()
seenLinks.DisposeStringArray()
previous.DisposeJsonObject()