Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create calendar event using Microsoft Graph Client

I'm trying to figure out how to create a calendar event using the Microsoft Graph JavaScript Client.

I've managed to retrieve the necessary accessToken and can interact with the API (i.e. retrieve events, calendars, top 10 e-mails), but I'm not sure of how to use the API to create an event.

    client
      .api('/me/events')
      .header('X-AnchorMailbox', emailAddress)

Do I use post to send the event json object?

like image 389
Julio Costa Avatar asked Nov 03 '17 16:11

Julio Costa


2 Answers

I suggest reviewing the Read Medocumentation for details on how to use this library.

To answer your question, you need to create a an Event object. For example:

var event = {
    "subject": "Let's go for lunch",
    "body": {
        "contentType": "HTML",
        "content": "Does late morning work for you?"
    },
    "start": {
        "dateTime": "2017-04-15T12:00:00",
        "timeZone": "Pacific Standard Time"
    },
    "end": {
        "dateTime": "2017-04-15T14:00:00",
        "timeZone": "Pacific Standard Time"
    },
    "location": {
        "displayName": "Harry's Bar"
    },
    "attendees": [{
        "emailAddress": {
            "address": "[email protected]",
            "name": "Samantha Booth"
        },
        "type": "required"
    }]
}

You then need to .post this object to the /events endpoint:

client
    .api('/me/events')
    .post(event, (err, res) => {
        console.log(res)
    })
like image 137
Marc LaFleur Avatar answered Sep 30 '22 23:09

Marc LaFleur


I created an event in Outlook calendar using Microsoft Graph API for C#.Net MVC as below. I believe whoever will be reading this answer has already created an app at https://apps.dev.microsoft.com and have the credentials to be used in this.

Please follow this tutorial How to use Outlook REST APIs for the initial project and OAuth setup. This article also tells how to create an app as mentioned above.

Now for coding i did the following.

Create class that will hold the event properties.

public class ToOutlookCalendar
{
    public ToOutlookCalendar()
    {
        Attendees = new List<Attendee>();
    }
    [JsonProperty("subject")]
    public string Subject { get; set; }

    [JsonProperty("body")]
    public Body Body { get; set; }

    [JsonProperty("start")]
    public End Start { get; set; }

    [JsonProperty("end")]
    public End End { get; set; }

    [JsonProperty("attendees")]
    public List<Attendee> Attendees { get; set; }

    [JsonProperty("location")]
    public LocationName Location { get; set; }
}

public class Attendee
{
    [JsonProperty("emailAddress")]
    public EmailAddress EmailAddress { get; set; }

    [JsonProperty("type")]
    public string Type { get; set; }
}

public class EmailAddress
{
    [JsonProperty("address")]
    public string Address { get; set; }

    [JsonProperty("name")]
    public string Name { get; set; }
}

public class Body
{
    [JsonProperty("contentType")]
    public string ContentType { get; set; }

    [JsonProperty("content")]
    public string Content { get; set; }
}

public class LocationName
{
    [JsonProperty("displayName")]
    public string DisplayName { get; set; }
}

public class End
{
    [JsonProperty("dateTime")]
    public string DateTime { get; set; }

    [JsonProperty("timeZone")]
    public string TimeZone { get; set; }
}

In my controller (the controller which you would be using as mentioned in the above url for project setup) i created an action method for creating event as follows:

public async Task<ActionResult> CreateOutlookEvent()
    {
        string token = await GetAccessToken();  //this will be created in the project setup url above
        if (string.IsNullOrEmpty(token))
        {
            // If there's no token in the session, redirect to Home
            return Redirect("/");
        }
        using (HttpClient c = new HttpClient())
        {
            string url = "https://graph.microsoft.com/v1.0/me/events";

            //with your properties from above except for "Token"
            ToOutlookCalendar toOutlookCalendar = CreateObject();

            HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(toOutlookCalendar), Encoding.UTF8, "application/json");

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
            request.Content = httpContent;
            //Authentication token
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

            var response = await c.SendAsync(request);
            var responseString = await response.Content.ReadAsStringAsync();
        }
        return null;
    }

CreateObject method for creating dummy event object (pardon me for naming convention but this was done only for demo purposes)

public static ToOutlookCalendar CreateObject()
    {
        ToOutlookCalendar toOutlookCalendar = new ToOutlookCalendar
        {
            Subject = "Code test",
            Body = new Body
            {
                ContentType = "HTML",
                Content = "Testing outlook service"
            },
            Start = new End
            {
                DateTime = "2018-11-30T12:00:00",
                TimeZone = "Pacific Standard Time"
            },
            End = new End
            {
                DateTime = "2018-11-30T15:00:00",
                TimeZone = "Pacific Standard Time"
            },
            Location = new LocationName
            {
                DisplayName = "Harry's Bar"
            }
        };
        return toOutlookCalendar;
    }

And i was able to create an event in outlook calendar. Some of the parts of this answer are adapted from this THREAD.

Hope it helps someone.

like image 29
Harry .Naeem Avatar answered Oct 01 '22 00:10

Harry .Naeem