I need to use the Microsoft Graph API to get free/busy schedules from the calendar with a .NET Core Windows service. According to Microsoft's own documentation I should use the following:
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var schedules = new List<String>()
{
"[email protected]",
"[email protected]"
};
var startTime = new DateTimeTimeZone
{
DateTime = "2019-03-15T09:00:00",
TimeZone = "Pacific Standard Time"
};
var endTime = new DateTimeTimeZone
{
DateTime = "2019-03-15T18:00:00",
TimeZone = "Pacific Standard Time"
};
var availabilityViewInterval = 60;
await graphClient.Me.Calendar
.GetSchedule(schedules,endTime,startTime,availabilityViewInterval)
.Request()
.Header("Prefer","outlook.timezone=\"Pacific Standard Time\"")
.PostAsync();
I have registered a new application using the Azure portal and given it the permission Calendars.Read.
My C# code:
try
{
IConfidentialClientApplication clientApplication = ConfidentialClientApplicationBuilder
.Create(_clientId)
.WithTenantId(_tenantId)
.WithClientSecret(_clientSecret)
.Build();
var authProvider = new ClientCredentialProvider(clientApplication);
var graphClient = new GraphServiceClient(authProvider);
var schedules = new List<string>
{
"[email protected]" // not actual mail used in my application
};
var startTime = new DateTimeTimeZone
{
DateTime = "2020-04-18T00:00:00",
TimeZone = "Europe/Paris"
};
var endTime = new DateTimeTimeZone
{
DateTime = "2020-04-25T23:59:59",
TimeZone = "Europe/Paris"
};
ICalendarGetScheduleCollectionPage scheduleList = await graphClient.Me.Calendar
.GetSchedule(schedules, endTime, startTime, 60)
.Request()
.PostAsync().ConfigureAwait(false);
Console.WriteLine("scheduleList.Count: " + scheduleList.ToList().Count);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
When I run my application I get the following exception:
Code: BadRequest
Message: Current authenticated context is not valid for this request. This occurs when a request is made to an endpoint that requires user sign-in. For example, /me requires a signed-in user. Acquire a token on behalf of a user to make requests to these endpoints. Use the OAuth 2.0 authorization code flow for mobile and native apps and the OAuth 2.0 implicit flow for single-page web apps.