MS Graph event creation 400 bad request.

Simon Stevens 1 Reputation point
2022-03-29T14:47:18.223+00:00

I am trying to get access to the someone's Office 365 calendar in order to sync with an event in my own system here are the calls:

  public async Task<ResultDto> SyncWithMSGraphAsync(int siteUserID, string addedBy, string msGraphBearerToken)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", msGraphBearerToken);
                HttpResponseMessage responseMessage = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me/calendars");
                string JsonString = await responseMessage.Content.ReadAsStringAsync();
                MicrosoftGraphCalandarsResponse MSGraphResponse = JsonConvert.DeserializeObject<MicrosoftGraphCalandarsResponse>(JsonString);
                MicrosoftGraphSyncCommandDto command = new MicrosoftGraphSyncCommandDto();
                foreach (MicrosoftGraphCalndarsDto calendar in MSGraphResponse.Value)
                {
                    if (calendar.isDefaultCalendar)
                    {
                        command.Id = calendar.Id;
                        command.Name = calendar.Name;
                        command.isDefaultCalendar = calendar.isDefaultCalendar;
                    }
                }

                bool result = await GetAvailabilities(msGraphBearerToken, siteUserID, command.Id);
                if (result)
                {
                    DbResultDto dbResultDto = await _dbClient.SyncToOutlookAsync(command, siteUserID, addedBy);

                    return dbResultDto.TransformToResultDto();
                }
                return ResultDto.Failure(new ErrorResultDto(ErrorTypes.BadRequest,
                         "Error_Label", "Cannot Sync With outlook365"));

            }

        }

        private async Task<bool> GetAvailabilities(string msBearerToken, int loggedInSiteUsersId, string calendarId)
        {
            GetAvailabilitySummariesForUserQuery query = new GetAvailabilitySummariesForUserQuery(loggedInSiteUsersId,
                              DateTime.Now,
                              DateTime.Now.AddYears(5),
                              "UTC");

            query.ConvertDatesToUTC(_dateTimeConverter);

            DbResultDto dbResult = await _dbClient.GetAvailabilitySummariesForUserAsync(query);

            // No entity exists, create using IEntitiesProvider
            if (dbResult.Status == null && dbResult.Details == null)
            {
                IEntity entityDetails = await _entitiesProvider.GetEntityDetailsAsync(query.User_SiteUsersId);
                query.WithAutoCreatedEntity(entityDetails.Name, entityDetails.EntityTypeCode);

                dbResult = await _dbClient.GetAvailabilitySummariesForUserAsync(query);
            }


            ObjectResultDto<IEnumerable<AvailabilitySummaryDbDto>> dbObjectResult
              = dbResult.TransformToObjectResultDto<IEnumerable<AvailabilitySummaryDbDto>>();

            if (dbObjectResult.Status == "1")
            {
                foreach(AvailabilitySummaryDbDto availabilitySummery in dbObjectResult.Details)
                {
                    if (availabilitySummery.Notes != "Created by Outlook")
                    {
                        using (HttpClient httpClient = new HttpClient())
                        {
                            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", msBearerToken);
                            var callJson = new
                            {
                                Subject = "Booking",
                                Body = new ItemBody
                                {
                                    ContentType = BodyType.Html,
                                    Content = "Available"
                                },
                                Start = new DateTimeTimeZone
                                {
                                    DateTime = availabilitySummery.StartDateUTC.ToString(),
                                    TimeZone = "Europe/London"
                                },
                                End = new DateTimeTimeZone
                                {
                                    DateTime = availabilitySummery.EndDateUTC.ToString(),
                                    TimeZone = "Europe/London"
                                }
                            };
                            string path = $"/me/calendars/{calendarId}/events";
                            path = "https://graph.microsoft.com/v1.0" + path;
                            HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(path, callJson);

                        }
                        return true;
                    }
                }

            }
            return false;
        }

Any ideas what I am doing wrong?

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
11,448 questions
0 comments No comments
{count} votes