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

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.

Microsoft documentation

Chilkat Lazarus Pascal Downloads

Lazarus Pascal
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.CkDateTime,
  Chilkat.Crypt2,
  Chilkat.HttpResponse,
  Chilkat.FileAccess,
  Chilkat.JsonObject,
  Chilkat.StringBuilder,
  Chilkat.StringArray,
  Chilkat.Http;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  token: TJsonObject;
  http: THttp;
  resp: THttpResponse;
  result: TJsonObject;
  fac: TFileAccess;
  cachePath: string;
  backupPath: string;
  state: TJsonObject;
  windowTime: TCkDateTime;
  windowStart: string;
  windowEnd: string;
  endpoint: TStringBuilder;
  hash: TCrypt2;
  link: TStringBuilder;
  itemPath: TStringBuilder;
  seenLinks: TStringArray;
  previous: TJsonObject;
  pageCount: Integer;
  url: string;
  nextType: Integer;
  deltaType: Integer;
  finished: Boolean;
  resumeUrl: string;
  i: Integer;
  eventId: string;
  itemKey: string;

begin
  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 := TJsonObject.Create;
  token.Strict := True;
  success := token.LoadFile('qa_data/tokens/outlookCalendar.json');
  if (success <> True) then
    begin
      WriteLn('Could not read the private calendar token cache.');
      Exit;
    end;
  if ((token.JsonTypeOf('access_token') <> 1) or (token.StringOfEquals('access_token','',True) = True)) then
    begin
      WriteLn('Expected a nonempty access_token in the JSON.');
      Exit;
    end;
  http := THttp.Create;
  http.AuthToken := token.StringOf('access_token');
  http.RequireSslCertVerify := True;
  http.FollowRedirects := False;
  http.ConnectTimeout := 20;
  http.ReadTimeout := 30;
  http.SetRequestHeader('Accept','application/json');
  resp := THttpResponse.Create;
  result := TJsonObject.Create;
  result.Strict := True;
  http.SetRequestHeader('Prefer','outlook.timezone="UTC", IdType="ImmutableId", odata.maxpagesize=50');
  fac := TFileAccess.Create;
  success := fac.DirEnsureExists('qa_data/outlookCalendar');
  if (success <> True) then
    begin
      WriteLn('Could not create the private synchronization directory.');
      Exit;
    end;
  cachePath := 'qa_data/outlookCalendar/calendar-sync.json';
  backupPath := 'qa_data/outlookCalendar/calendar-sync.json.bak';
  state := TJsonObject.Create;
  state.Strict := True;
  if (fac.FileExists(cachePath) = True) then
    begin
      success := state.LoadFile(cachePath);
      if (success <> True) then
        begin
          WriteLn('Invalid checkpoint; recover the matching data and cursor from the private .bak file before continuing.');
          Exit;
        end;
      if ((state.JsonTypeOf('resumeUrl') <> 1) or (state.StringOfEquals('resumeUrl','',True) = True)) then
        begin
          WriteLn('Expected a nonempty resumeUrl in the JSON.');
          Exit;
        end;
      if ((state.JsonTypeOf('startDateTime') <> 1) or (state.StringOfEquals('startDateTime','',True) = True)) then
        begin
          WriteLn('Expected a nonempty startDateTime in the JSON.');
          Exit;
        end;
      if ((state.JsonTypeOf('endDateTime') <> 1) or (state.StringOfEquals('endDateTime','',True) = True)) then
        begin
          WriteLn('Expected a nonempty endDateTime in the JSON.');
          Exit;
        end;
      if (state.JsonTypeOf('items') <> 3) then
        begin
          WriteLn('Expected an items object in the checkpoint.');
          Exit;
        end;
    end
  else
    begin
      windowTime := TCkDateTime.Create;
      success := windowTime.SetFromCurrentSystemTime();
      if (success <> True) then
        begin
          WriteLn('Could not get the current time.');
          Exit;
        end;
      windowStart := windowTime.GetAsTimestamp(False);
      success := windowTime.AddDays(30);
      if (success <> True) then
        begin
          WriteLn('Could not calculate the window end.');
          Exit;
        end;
      windowEnd := windowTime.GetAsTimestamp(False);
      endpoint := TStringBuilder.Create;
      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');
    end;
  hash := TCrypt2.Create;
  hash.HashAlgorithm := 'sha256';
  hash.Charset := 'utf-8';
  hash.EncodingMode := 'hex';
  link := TStringBuilder.Create;
  itemPath := TStringBuilder.Create;
  seenLinks := TStringArray.Create;
  previous := TJsonObject.Create;
  previous.Strict := True;
  pageCount := 0;
  while (pageCount < 100) do
    begin
      url := state.StringOf('resumeUrl');
      link.Clear();
      link.Append(url);
      if (link.StartsWith('https://graph.microsoft.com/v1.0/',True) <> True) then
        begin
          WriteLn('Unexpected continuation host or API version; no request sent.');
          Exit;
        end;
      if (seenLinks.Find(url,0) >= 0) then
        begin
          WriteLn('Repeated continuation URL; stopping.');
          Exit;
        end;
      seenLinks.Append(url);
      success := http.HttpNoBody('GET',url,resp);
      //  A false result can still include an HTTP error response.
      if ((success <> True) and (resp.StatusCode = 0)) then
        begin
          WriteLn('No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.');
          Exit;
        end;
      if (resp.StatusCode <> 200) then
        begin
          WriteLn('Unexpected HTTP status: ' + resp.StatusCode);
          WriteLn('Request ID: ' + resp.GetHeaderField('request-id'));
          if (resp.StatusCode = 429) then
            begin
              WriteLn('Retry-After: ' + resp.GetHeaderField('Retry-After'));
            end;
          if (resp.StatusCode = 401) then
            begin
              WriteLn('Refresh the Graph access token or authorize again.');
            end;
          Exit;
        end;
      success := result.Load(resp.BodyStr);
      if (success <> True) then
        begin
          WriteLn('Expected a well-formed JSON response.');
          Exit;
        end;
      if (result.JsonTypeOf('value') <> 4) then
        begin
          WriteLn('Expected a value array; checkpoint unchanged.');
          Exit;
        end;
      //  Exactly one continuation member must be a nonempty string.
      nextType := result.JsonTypeOf('"@odata.nextLink"');
      deltaType := result.JsonTypeOf('"@odata.deltaLink"');
      finished := False;

      if ((nextType = 1) and (deltaType = -1)) then
        begin
          resumeUrl := result.StringOf('"@odata.nextLink"');
        end
      else
        begin
          if ((deltaType <> 1) or (nextType <> -1)) then
            begin
              WriteLn('Invalid delta continuation; checkpoint unchanged.');
              Exit;
            end;
          resumeUrl := result.StringOf('"@odata.deltaLink"');
          finished := True;
        end;
      link.Clear();
      link.Append(resumeUrl);
      if (link.StartsWith('https://graph.microsoft.com/v1.0/',True) <> True) then
        begin
          WriteLn('Invalid continuation URL; checkpoint unchanged.');
          Exit;
        end;
      success := previous.Load(state.Emit());
      if (success <> True) then
        begin
          WriteLn('Could not snapshot the previous checkpoint.');
          Exit;
        end;
      i := 0;
      while (i < result.SizeOfArray('value')) do
        begin
          result.I := i;
          if ((result.JsonTypeOf('value[i].id') <> 1) or (result.StringOfEquals('value[i].id','',True) = True)) then
            begin
              WriteLn('Expected a nonempty value[i].id in the JSON.');
              Exit;
            end;
          eventId := result.StringOf('value[i].id');
          itemKey := hash.HashStringENC(eventId);
          if (hash.LastMethodSuccess <> True) then
            begin
              WriteLn('Could not form a local record key.');
              Exit;
            end;
          //  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
            begin
              state.UpdateNewObject(itemPath.GetAsString());
            end;
          itemPath.Append('.');
          state.PathPrefix := itemPath.GetAsString();
          state.UpdateString('id',eventId);
          if (result.JsonTypeOf('value[i].@removed') = 3) then
            begin
              //  Hide records with removed=true from the local date-range view.
              state.UpdateBool('removed',True);
              WriteLn('Removed from the local view: ' + eventId);
            end
          else
            begin
              state.UpdateBool('removed',False);
              if (result.JsonTypeOf('value[i].subject') = 1) then
                begin
                  state.UpdateString('subject',result.StringOf('value[i].subject'));
                end;
              if (result.JsonTypeOf('value[i].type') = 1) then
                begin
                  state.UpdateString('type',result.StringOf('value[i].type'));
                end;
              if (result.JsonTypeOf('value[i].start.dateTime') = 1) then
                begin
                  state.UpdateString('start.dateTime',result.StringOf('value[i].start.dateTime'));
                end;
              if (result.JsonTypeOf('value[i].start.timeZone') = 1) then
                begin
                  state.UpdateString('start.timeZone',result.StringOf('value[i].start.timeZone'));
                end;
              if (result.JsonTypeOf('value[i].end.dateTime') = 1) then
                begin
                  state.UpdateString('end.dateTime',result.StringOf('value[i].end.dateTime'));
                end;
              if (result.JsonTypeOf('value[i].end.timeZone') = 1) then
                begin
                  state.UpdateString('end.timeZone',result.StringOf('value[i].end.timeZone'));
                end;
              state.PathPrefix := '';
              WriteLn('Updated local event: ' + eventId);
            end;
          state.PathPrefix := '';
          i := i + 1;
        end;

      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
        begin
          WriteLn('Could not back up the previous checkpoint; no replacement attempted.');
          Exit;
        end;
      success := state.WriteFile(cachePath);
      if (success <> True) then
        begin
          WriteLn('Checkpoint write failed. Restore the private .bak before continuing.');
          Exit;
        end;
      pageCount := pageCount + 1;
      if (finished = True) then
        begin
          WriteLn('Synchronization round complete; saved the delta link for the next run.');
          Exit;
        end;
    end;

  WriteLn('Paused after 100 pages; the saved nextLink resumes on the next run.');


  token.Free;
  http.Free;
  resp.Free;
  result.Free;
  fac.Free;
  state.Free;
      windowTime.Free;
      endpoint.Free;
  hash.Free;
  link.Free;
  itemPath.Free;
  seenLinks.Free;
  previous.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.