Write your first program using Microsoft Graph SDK


Download source code associated with this article here- MSGraphSDKConsoleApp.


 

In this article, I will explain you 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 how to install VS2017 here.

  • Office 365 subscription

Don’t have Office 365 subscription? Read my article here about how to get 1-year free Office 365 developer subscription.

Even if you have Office 365 account from your employer, I strongly suggest not to use it for development purpose.

  • 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 for this article:

1 VS 2017

Click on “Create new project” in start page:

2 Create project

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

3 Console

Configure your Application

Once you have created a new project, you need to configure it so that authentication using 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 login with your Office 365 developer account.

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

4 add an app

Enter application name and click “Create”:

5 create app

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 it’s application id which we will need in next steps:

6 app id

Under the platforms, click “Add Platform” button:

7 platform

Select “Native Application”:

8 Native platform


Why 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:

9 clientid

 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 you how to write simple code which calls MS Graph API to fetch logged in user’s details.

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

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

static async Task<string> GetTokenAsync(PublicClientApplication clientApp)

{

//need to pass scope of activity to get token

string [] Scopes = {“User.Read"};

string token = null;

AuthenticationResult authResult = await clientApp.AcquireTokenAsync(Scopes);

token = authResult.AccessToken;           

return token;

}

Note here the most important code is clientApp.AcquireTokenAsync(Scopes) which will redirect user to 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:

PublicClientApplication clientApp = new PublicClientApplication(ConfigurationManager.AppSettings["clientId"].ToString());

GraphServiceClient graphClient = new GraphServiceClient(

"https://graph.microsoft.com/v1.0",

new DelegateAuthenticationProvider(

async (requestMessage) =>

{

requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", await GetTokenAsync(clientApp));

}));

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

var currentUser = await graphClient.Me.Request().GetAsync();

Console.WriteLine(currentUser.DisplayName);

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

using Microsoft.Graph;

using Microsoft.Identity.Client;

using System;

using System.Configuration;

using System.Net.Http.Headers;

using System.Threading.Tasks;

The whole code looks like this:

22 code

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:

19 sign in

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

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

20 consent

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

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

21 result

That’s it for this article. The purpose of this article was to make you aware how you can write simple most 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.

One thought on “Write your first program using Microsoft Graph SDK”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s