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.

Testing and deploying an Office 365 add-in from network share

C-EdzGWUAAAEWCY

In this article, I will show you how you can load an Office 365 add-in from a network share for testing or live deployment.

If you are a developer who builds add-ins for Office 365, then you need to test those before deployment; and if you are developing for enterprise users then they need to access your add-ins after roll-out.

A network share (sharing your add-in from a network drive) is the easiest possible way for both of that. Read this interesting article where I show how to test and deploy Office 365 add-ins from a network share.

Prerequisites:

  • Either of:
    • Visual Studio 2015 or
    • Visual Studio 2017 (with Office Developer Tools)
    • Visual Studio Code (with Yeoman Office generator a.k.a. Yo Office!)
  • Office 365 add-in manifest (XML file)
  • A web server running your Office 365 add-in (web component)

Getting started:

If you have already created an Office 365 add-in, then you can skip this “Getting Started” section and jump directly to the next “Publish, Test & Deploy” section.

Create an Office 365 add-in using tools I have mentioned in prerequisites. Read below section for how to do that:

VS2015 office project

Give proper project name and click “Ok” button in above dialog.

Select “Task pane” from the next dialog:

VS2015 office task pane

Click next and select Excel from the next popup:

VS2015 office project finish

Click “Finish” and you are done!

  • Visual Studio Code with Yeoman Office Project Generator
    • Follow the instructions on Office Developer GitHub page here.

Publish, Test & Deploy

You can publish your Office 365 add-in web project on either IIS Server or on Azure.

For deploying web app on Azure, read another author’s article here.

For deploying web app on IIS Server, follow instructions here.

Or simply you can test it by pressing F5 from Visual Studio and let it run till you finish testing.

For showing you further instructions in this article, I have deployed my add-in web project on Azure.

All you need now is the URL on which your add-in web project is deployed. You need to configure it in the add-in manifest xml file.

Go to the solution explorer in VS 2017 and open the file location of the manifest file:

sol explorer

All you need is a copy of this manifest XML file. Copy it and paste it on any network share available for testing. I have shared it under “ExcelWebAddIn2Manifest” network share for my testing.

Open the manifest XML file in VS 2017 or any XML editor or simply Notepad, find “SourceLocation”:

source loc

You need to change the “DefaultValue” to the URL on which you deployed your add-in web app.

I have changed its value to point to my deployment URL:

defaultvalue

That’s the only change you need to make. Now let’s add this manifest file in Excel to see our add-in working.

Open Excel, create a new blank workbook. Go to File -> Options -> Trust Center -> Trust Center Settings:

trust center

Go to “Trusted Add-in Catalogs”, enter network share path in “Catalog URL”, then click “Add catalog”:

add catalog

Select “Show in Menu” checkbox, then click “OK”:

show in menu

Once you click OK button, you will be shown following message:

restart message

Click OK and close all dialogs, then close Excel and start it again. Create a new workbook.

Go to Insert ribbon then click “Store”:

store

Click “Shared Folder” link, and you will see your add-in. If not, then try clicking refresh and see:

shared folder

Select the add-in and click add button.

Excel will load add-in and show you message that it has loaded:

show task pane

Click on “Show Taskpane” and your add-in will be loaded:

add in loaded

Congratulations! Your Office 365 add-in is now ready to use. You can use the above steps for testing your add-in or while deploying in live environment too.

That’s it for this article. Happy learning!

 

 

Introduction to MS Graph API

MSGraph_Graphic.png

In this article, I will introduce you to the MS Graph API which is a powerful way to interact with Office 365 data.

Here are the objectives of this article:

  • What is MS Graph API?
  • How it came into picture?
  • What are its features, benefits and limitations?
  • MS Graph Explorer
  • MS Graph SDK

Let’s start with MS Graph API.

 

What is MS Graph API?

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.

 

How it came into picture?

Prior to MS Graph API, Microsoft had different APIs for it’s different Office 365 and cloud products. Outlook, OneDrive, OneNote, Yammer all had their different APIs to interact with them.

Consider the following steps involved while dealing with different Office 365 APIs in an application:

  • Find the URL/endpoint of the API
  • Authenticate / get access token
  • Get results from the API
  • Repeat for each service
  • Manage multiple tokens for each API

It made a developer’s life difficult if one had to connect to many different APIs in an application.

As a solution, Microsoft launched the MS Graph API which is also called “One endpoint to rule them all”.

 

Why should you learn MS Graph API?

Office 365 is undoubtedly most widely used office produce worldwide. Millions of people are using the commercial versions of Office 365 suite or one or another of its products like Outlook, OneNote, etc.

On an average, a user in any office will use 2-3 hours working on different Office suite product like Outlook, Excel, Project, etc. Millions of new emails, events, etc. are generated in Outlook and millions of files are stored on OneDrive.

If you want to access all this information stored in Office 365 or on Azure, then you need MS Graph API.

 

Advantages

  • Single well-known resource

MS Graph API is the easiest way to interact with Office 365 data. Using MS Graph API, you can get mostly everything from a single endpoint https://graph.microsoft.com.

  • Ease of development

It liberates a developer from calling different Office 365 APIs and doing multiple token management.

  • Logical navigation

The entities of Office 365 are accessible in a logical way thru MS Graph API. Look again at the picture posted at the top of this article. You will see that once you access a user, all other entities related to it – files, messages, notes, etc. – are then accessible in a logical manner.

You don’t have to remember how an entity will be accessed, it follows a logical manner of graph structure.

  • Platform flexibility

MS Graph API does not mandate you to learn a new programming language. It can work with many different languages/platforms and Microsoft has launched SDKs to work with different platforms. You can work with MS Graph API in Windows/Android/iOS platforms. You can read more on it on last section of this article “MS Graph SDK”

 

Features

  • MS Identity Stack

MS Graph API does not introduce any new authentication mechanism where users have to go to register and then remember one more user name and password.

Instead, MS Graph API uses the Microsoft identity stack (which is used by 85% of fortune 500) – means that your users can login using the same familiar Azure AD / Microsoft Office 365 login credentials in your application.

MS Graph API uses Open ID Connect for authentication and OAUTH 2.0 for access tokens.

  • Open Standards

MS Graph API is based on and it supports many open web standards making it flexible and highly interoperable. Some of these standards are: 

REST – heart of MS Graph API implementation, any device/technology able to make http call and able to interpret JSON can work with MS Graph API 

JSON – lightweight format for request and response data 

OAUTH – provides API access token management, MS Graph API supports OAUTH v2.0 

ODATA – MS Graph API supports open data protocol v4.0 which is also called “The best way to REST”. It uses URL query string operators to make simple, standard and readable expressions.

I have written some articles on using optional ODATA query parameters with MS Graph API which can be found here:

 

  • Webhooks

Using webhooks, MS Graph API can send you notification for any changes in entities for which you have subscribed to. Instead of keeping on querying MS Graph API to see if there are any changes, you can use webhooks mechanism to have notification sent to you in case of any action/event happening. For example, you can subscribe to get notified when a new message arrives. 

  • Intelligence & Insights

MS Graph API does not only do simple input and output operations on your organization’s Office 365 entities. Instead of that, MS Graph API also has intelligence inbuilt in it which can help you to find treading documents around a user, people frequently contacted, etc. It can also help you find the best meeting times in a team.

  • Custom data extensions

You can extend MS Graph API results with custom data i.e. you can add custom data to MS Graph without using any external data source. This is helpful when you want to store some custom data relevant to your application e.g. profile setting or favorite theme, etc.

There are two types of extensions: Open extensions which are flexible and allows you to store any untyped data; and Schema extensions where you can define your own complex strongly typed schema, which can be shared between your different applications.

  • Delta query

Using delta query, it become easier to track data changes in entities. Instead of getting list of all entities and comparing them one by one to identify any changes, just fire a call using delta query which will give you only the changes i.e. inserted, updated, deleted data since your last call. 

  • Batching

Using MS Graph API’s JSON Batching you can combine multiple requests in one HTTP call and optimize application performance. Instead of looping thru multiple calls in your application, you can fire all related / unrelated calls in one batch in one go.

 

Limitations

The most visible one is some of its features are still in beta, but MS Graph team keeps launching new features in live regularly.

For a list of all MS Graph API known issues, refer here.

 

MS Graph API Explorer

Graph Exp

MS Graph API Explorer is a great tool to get started with MS Graph API and learn first-hand how it works. Graph Explorer is a developer sandbox where you can fire actual Graph API call and see its result.

You can access MS Graph API Explorer here.

I have written some articles on how to use MS Graph Explorer which can be found here:

 

Microsoft Graph SDK

MS Graph team has done some great work in launching SDKs for different platforms which makes development with MS Graph API easy.

You don’t have to code everything from scratch, ready to start code is available in SDK.

The following SDKs are available:

SDKs.png

If you are a java developer, then recently Microsoft has launched Java SDK for MS Graph API in preview.

If you want to add MS Graph SDK in any of your C# application, then open Visual Studio and simply search for “Microsoft Graph” in NuGet package manager to get started:

Nuget MS Graph.PNG

That’s it for introduction to MS Graph API in this article. Wait for my next article where I will show how you can start programming in MS Graph API.

Till then following links will be useful to get started with MS Graph API: