Write Your First Program Using Microsoft Graph SDK

In this article, I will explain how you can write your first program to interact with MS Graph API using MS Graph SDK in Visual Studio.

Office development

In this article, I will explain how you can write your first program to interact with MS Graph API using MS Graph SDK in Visual Studio.

Microsoft Graph API is a powerful way to interact with Office 365 data. MS Graph API gives you a single REST API endpoint which you can call to interact with “almost anything” in Office 365.

Read my article here to know more about MS Graph API.

If you want to follow the steps mentioned here, then there are some prerequisites which you must have, otherwise, you can continue reading.

Prerequisites

  • Visual Studio 2017
    Don’t have VS 2017? Download free “Visual Studio Community 2017” here.

    Read my article on how to install VS2017 here.
  • Office 365 subscription
    Don’t have Office 365 subscription? Read my article here about how to get one-year free Office 365 developer subscription.

    Even if you have an Office 365 account from your employer, I strongly suggest not to use it for development purposes.
  • Microsoft Graph SDK
    MS Graph SDK is a class library with ready-to-use code for interacting with MS Graph API. It’s freely available as a NuGet package and can be easily added to your project from Visual Studio NuGet package manager.

    Read more about MS Graph SDK in my article here.  Let’s get started.

Open Visual Studio. I am using VS 2017 community edition in this article.

Office development

 

Click on “Create new project” on the start page:

Office development

 

Select “Console App”, give proper project name, click Ok to create a new project:

Office development

 

Configure your Application

Once you have created a new project, you need to configure it so that authentication using a Microsoft account (your Office 365 developer account) can be done in your application and you can receive a token required to access data using MS Graph API. For that, you need to go to Microsoft App Registration Portal.

Please note these steps of registering your application are explained in detail in my articles here and here.

Open Microsoft App Registration Portal located at https://apps.dev.microsoft.com and log in with your Office 365 developer account.

Click on “Add an app” button on top right,

Office development

Enter application name and click “Create”

Office development

Alternatively, you can also click on “Let us help you get started” checkbox and the wizard will guide you step by step.

A new application is created for you, please note its application id which we will need in the next steps:

Office development

Under the platforms, click “Add Platform” button:

Office development

Select “Native Application”:

Office development

Why do we use “Native Application”?

Because we are writing code for a console application which is going to run on Windows OS. If it was a web application, then you would select “Web” and similarly “Web API” for an API.

You don’t need to make any more changes in MS App Registration Portal. Click on “Save” button at the bottom of the page.

Back to VS 2017 now. We need to configure our application with the application id we just created.

Open the App.config file. Add a new key “clientId” under appSettings, paste the application id from MS App Registration Portal in value section:

Office development 

Add MS Graph SDK to project

Simply search for “Microsoft Graph” in package manager and add “Microsoft.Graph” and “Microsoft.Graph.Core” packages.

Also add “Microsoft.Identity.Client” package as it’s required for authentication code.

Need more detailed steps? Read “Adding MS Graph SDK to your C# application” section of my article on MS Graph SDK here.

Write code

In the following section, I will explain to you how to write a simple code which calls MS Graph API to fetch logged in user’s details.

I will also explain code required to authenticate the user using Microsoft account.

The first piece of code you need to write is to authenticate a user and get access token.

  1. static async Task < string > GetTokenAsync(PublicClientApplication clientApp) {  
  2.         //need to pass scope of activity to get token  
  3.         string[] Scopes = {“  
  4.             User.Read "};  
  5.             string token = null;  
  6.             AuthenticationResult authResult = await clientApp.AcquireTokenAsync(Scopes);  
  7.             token = authResult.AccessToken;  
  8.             return token;  
  9.         }  

Note here the most important code is clientApp.AcquireTokenAsync(Scopes) which will redirect the user to a Microsoft login page, show consent for permission(s) required by your application for given Scopes.

Then you need to write code to get MS Graph client to deal with MS Graph API

  1. PublicClientApplication clientApp = new PublicClientApplication(ConfigurationManager.AppSettings["clientId"].ToString());  
  2. GraphServiceClient graphClient = new GraphServiceClient("https://graph.microsoft.com/v1.0"new DelegateAuthenticationProvider(async (requestMessage) => {  
  3.     requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", await GetTokenAsync(clientApp));  
  4. }));  

The above code will get access token and pass it to Graph API client. Now you have a client, simply make a call to MS Graph API

  1. var currentUser = await graphClient.Me.Request().GetAsync();  
  2. Console.WriteLine(currentUser.DisplayName);  

Don’t forget to add the following using directives at the top of the class:

  1. using Microsoft.Graph;  
  2. using Microsoft.Identity.Client;  
  3. using System;  
  4. using System.Configuration;  
  5. using System.Net.Http.Headers;  
  6. using System.Threading.Tasks;  

The whole code looks like this:

Office development

I have attached the whole project with this article. You can download it and view/run. Please note that this code is not suitable to be used in production application.

Run application

Now you are ready to run the application. Press F5.

You will be shown a dialog to enter your Microsoft account and password,

Office development

Note that we did not write any code to show this popup. It is handled by Microsoft Identity package; your application will never get username and password.

Once you enter correct Microsoft account details or your Office 365 developer account username and password, then you will be shown permission which the application requires, and it asks for your consent,

Office development

Remember in the above code, I have written "User.Read" in “Scopes”? That’s why the user is shown that this application wants to “View your basic profile”. Click “Accept” to continue.

Hurray! You will be shown the logged-in user’s display name!

Office development

That’s it for this article. The purpose of this article was to make you aware how you can write a simple program to connect to Office 365 using MS Graph API and fetch some data.

For more detailed code and some samples, I suggest you visit MS Graph API samples page on GitHub here. Please note that some repositories are good to be used in your production application as well.

For more on MS Graph API, read my articles here.