Thursday, February 27, 2020

Get started with Microsoft Graph

Get started with Microsoft Graph
https://developer.microsoft.com/en-us/graph/get-started

Step 1: App registrations in Azure Active Directory
Strep 2: C# code to read User Events

Step 1:
go to http://portal.azure.com/ click on 'Azure Active Directory'

click on 'App registration' -> 'New registration' to register new app.

provide required details in app registration page.

from below screen copy client id, tenant id to use in code.

go to 'app permission' -> 'add a permissions' -> 'Microsoft Graph' -> 'Application Permission' -> select below permissions:

Calendars.Read
Calendars.ReadWrite
User.Read
User.Read.All




click on 'Grant admin consent for ' -> click on OK 



Click on 'Certification & Secrets' -> 'New client secret' -> provide required details -> click on 'Add' button. 

make sure copy below secret now itself to use in code, later it is not visible. 

Step 2: Code

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace graph
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        private const string TenantId = "19d5137a-bf36-xxx";
        private string graphAccessUrl = "https://login.microsoftonline.com/" + TenantId + "/oauth2/v2.0/token";
        private string clientId = "f548e759-fe41-xxx";
        private string clientSecret = "e.e:7E=[QioQfFhTxxx";
        private string grant_type = "client_credentials";
        private string scope = "https://graph.microsoft.com/.default";
        private string graphUrl_event = "https://graph.microsoft.com/v1.0/users/sreekanth@sreekanth07.onmicrosoft.com/events?startdatetime=2020-02-28T10:47:27.2680000&enddatetime=2020-02-29T10:47:27.2680000&$select=subject,body,bodyPreview,organizer,attendees,start,end,location,showAs";
        private string graphUrl_createEvent = "https://graph.microsoft.com/v1.0/users/sreekanth@sreekanth07.onmicrosoft.com/events";
        private string accessToken = string.Empty;
        private JObject events = null;

        protected async void Page_Load(object sender, EventArgs e)
        {
            accessToken = await GetAppOnlyAccessTokekn();
            events = await GetEvents(accessToken);
            string strEvent = await CreateEvent(accessToken);
        }
        private async Task<string> GetAppOnlyAccessTokekn()
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(graphAccessUrl);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

                    List<KeyValuePair<string, string>> values = new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>("grant_type", grant_type),
                        new KeyValuePair<string, string>("client_id", clientId),
                        new KeyValuePair<string, string>("client_secret", clientSecret),
                        new KeyValuePair<string, string>("scope", scope)
                    };

                    try
                    {
                        HttpContent httpContent = new FormUrlEncodedContent(values);
                        HttpResponseMessage response = await client.PostAsync(new Uri(graphAccessUrl), httpContent);
                        if (response.IsSuccessStatusCode)
                        {
                            string responseString = await response.Content.ReadAsStringAsync();
                            Data reponseObj = JsonConvert.DeserializeObject<Data>(responseString);
                            return reponseObj.access_token;
                        }
                        else
                        {
                            return null;
                        }
                    }
                    catch (Exception)
                    {
                        return null;
                    }
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
        public async Task<JObject> GetEvents(string accessToken)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(graphUrl_event);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                    try
                    {
                        HttpResponseMessage response = await client.GetAsync(new Uri(graphUrl_event));
                        if (response.IsSuccessStatusCode)
                        {
                            string responseJSON = await response.Content.ReadAsStringAsync();
                            JObject jObj = JObject.Parse(responseJSON);

                            return jObj;
                        }
                        else
                        {
                            return null;
                        }
                    }
                    catch (Exception)
                    {
                        return null;
                    }
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
        public async Task<string> CreateEvent(string accessToken)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(graphUrl_createEvent);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                    try
                    {
                        string body = "{\"subject\":\"My event 123\",\"start\":{\"dateTime\":\"2020-02-28T10:47:27.268Z\",\"timeZone\":\"UTC\"},\"end\":{\"dateTime\":\"2020-02-29T10:47:27.268Z\",\"timeZone\":\"UTC\"},\"location\":{\"displayName\":\"Harry's Bar\"},\"attendees\":[{\"emailAddress\":{\"address\":\"user1@sreekanth07.onmicrosoft.com\",\"name\":\"user 1\"},\"type\":\"required\"},{\"emailAddress\":{\"address\":\"user2@sreekanth07.onmicrosoft.com\",\"name\":\"user 2\"},\"type\":\"required\"},{\"emailAddress\":{\"address\":\"user3@sreekanth07.onmicrosoft.com\",\"name\":\"user 3\"},\"type\":\"required\"}]}";

                        List<KeyValuePair<string, string>> values = new List<KeyValuePair<string, string>>
                        {
                            new KeyValuePair<string, string>("application/json", body)
                        };

                        HttpContent httpContent = new StringContent(body, Encoding.UTF32, "application/json");
                        HttpResponseMessage response = await client.PostAsync(new Uri(graphUrl_createEvent), httpContent);

                        if (response.IsSuccessStatusCode)
                        {
                            string responseJSON = await response.Content.ReadAsStringAsync();
                            return responseJSON;
                        }
                        else
                        {
                            return null;
                        }
                    }
                    catch (Exception)
                    {
                        return null;
                    }
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
    public class Data
    {
        public string token_type { get; set; }
        public string expires_in { get; set; }
        public string ext_expires_in { get; set; }
        public string access_token { get; set; }

    }
}

No comments:

Post a Comment