Andrey
Andrey

Reputation: 21285

How to batch delete events in Office365 using C# Graph SDK

I have a method that deletes multiple events. Currently the code is as following:

    public async Task DeleteEvents(IEnumerable<string> eventExternalIds)
    {
        foreach(var eventExternalId in eventExternalIds)
        {
            await DeleteEvent(eventExternalId);
        }
    }

    public async Task DeleteEvent(string eventExternalId)
    {
        await GraphClient
            .Users[Username]
            .Calendars[CalendarName]
            .Events[eventExternalId]
            .Request()
            .DeleteAsync();
    }

I would imagine it won't perform well with any significant number of id's to delete. Is there a way to delete them all in a batch(es) instead of each individually?

Upvotes: 3

Views: 1688

Answers (1)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59328

msgraph-sdk-dotnet v1.15.0 or above

For msgraph-sdk-dotnet version 1.15.0 or above the support for Batch request has been introduced via BatchRequestContent class

Example

//1. construct a Batch request 
var batchRequestContent = new BatchRequestContent();
var step = 1;
foreach (var eventId in eventIds)
{
     var requestUrl = graphClient
           .Me
           .Events[eventId]
           .Request().RequestUrl;

     var request = new HttpRequestMessage(HttpMethod.Delete, requestUrl);
     var requestStep = new BatchRequestStep(step.ToString(), request, null);
     batchRequestContent.AddBatchRequestStep(requestStep);
     step++;
}


//2. Submit request
var batchRequest = new HttpRequestMessage(HttpMethod.Post, "https://graph.microsoft.com/v1.0/$batch");
batchRequest.Content = batchRequestContent;
await graphClient.AuthenticationProvider.AuthenticateRequestAsync(batchRequest);
var httpClient = new HttpClient();
var batchResponse = await httpClient.SendAsync(batchRequest);
//3. Process response
var batchResponseContent = new BatchResponseContent(batchResponse);
var responses = await batchResponseContent.GetResponsesAsync();
foreach (var response in responses)
{
     if (response.Value.IsSuccessStatusCode)
     {
         //...
     }                 
}

Issues

  • while targeting NetCore 2.1 or above or .NET Framework NullReferenceException exception might occur, to address this issue you could switch to 1.16.0-preview.1 (details)

Limitations

Note: A batch cannot hold more that 20 requests

msgraph-sdk-dotnet v1.14.0 or older

For previous versions, the following example demonstrates how to implement a support for Batch request:

var batchRequest = new BatchRequest();
foreach (var eventId in eventIds)
{
   var request = graphClient.Me.Events[eventId].Request();
   batchRequest.AddQuery(request,HttpMethod.Delete);
}
var responses = await graphClient.SendBatchAsync(batchRequest);

where BatchRequest is a custom class which adds support for JSON Batching

Upvotes: 6

Related Questions