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.

What is Microsoft Graph SDK?

This article is a quick overview of MS Graph SDK. Using MS Graph SDK, you can easily write code which calls MS Graph APIs to interact with Office 365 data.

What is MS Graph API?

First, let’s see what MS Graph API is. The official MS documentation defines MS Graph API as:

“You can use the Microsoft Graph API to interact with the data of millions of users in the Microsoft cloud. Use Microsoft Graph to build apps for organizations and consumers that connect to a wealth of resources, relationships, and intelligence, all through a single endpoint: https://graph.microsoft.com”

In a nutshell, MS Graph API gives you a single REST API endpoint which you can call to interact with “almost anything” in Office 365.

To know more about MS Graph API, read my article here.

 What is MS Graph SDK?

Microsoft Graph Software Development Kit is “Microsoft Graph Client Library which allows you to call Office 365, Azure AD and other Microsoft services through a single unified developer experience.”

Using MS Graph SDK, you can quickly integrate MS Graph API in your application, so that you don’t have to write everything to deal with MS Graph API from scratch.

It provides ready-made classes and methods to be used while making Graph API calls. Please note that using MS Graph SDK is not “mandatory” if you want to code your application for MS Graph API. It just makes coding quick and easy.

What’s its availability?

MS Graph SDK is available for most leading development platforms e.g. ASP.Net, Xamarin, Android, iOS, JS, Angular, and many more. Day by day more platforms are being added.

This is the latest availability as of today:

Live availability:

Beta/Preview availability:

No SDK, only code samples available:

Keep watching the official Microsoft page here which mentions MS Graph SDK’s latest availability:

23 SDK

MS Graph SDK for .NET is available as “Microsoft.Graph” and “Microsoft.Graph.Core” NuGet packages:

24 nuget packages

Adding MS Graph SDK to your C# application

Let’s add MS Graph SDK for .NET i.e. MS Graph NuGet packages to a C# application.

Quickly create a new C# application (either console app or web app) in Visual Studio 2015/2017.

Right click project in Solution Explorer and click “Manage NuGet packages”:

10 NuGet

Go to “Browse” and type “Microsoft Graph”, press Enter key:

11 MS Graph package

Select “Microsoft.Graph” package from the result and click “Install” button on right side:

12 MS Graph package 2

It will show you “License Acceptance” dialog:

13 accept license

Note here that it will also install “Microsoft.Graph.Core” package, among others, as one of its dependencies. Click on “I Accept” button.

Output window will show success message once installation is finished.

14 success output

You have successfully added MS Graph SDK packages to your application.

You can make sure that by two ways.

Go to Solution Explorer and select “packages.config” file:

15 packages

See that “Microsoft.Graph” and “Microsoft.Graph.Core” packages are visible in config file:

16 packages file

Also, if you expand “References” in Solution Explorer then you will see Microsoft Graph references:

17 references

You will also need to install “Microsoft.Identity.Client” package as it’s required for authentication code because users are authenticated against Microsoft account.

18 Ms identity

Don’t forget to select “Include prerelease” checkbox!

That’s it! You have now successfully added MS Graph SDK and you are ready to start your coding.

To know how to write code to fetch Office 365 data using MS Graph SDK, read my article “Write your first program using Microsoft Graph SDK” here.