Back

Step by Step Guide to Building a Microsoft Office 365 API Integration in C#

Aug 2, 20246 minute read

Introduction

Hey there, fellow developer! Ready to dive into the world of Microsoft Graph API? Buckle up, because we're about to embark on a journey to integrate Office 365 into your C# application using the Microsoft.Graph package. Trust me, it's easier than you might think!

Prerequisites

Before we jump in, make sure you've got these essentials:

  • Visual Studio (any recent version will do)
  • .NET Core SDK
  • A Microsoft 365 Developer account (if you don't have one, grab it here)

Got all that? Great! Let's get our hands dirty.

Setting up the project

First things first, fire up Visual Studio and create a new C# console application. Once that's done, let's add the Microsoft.Graph package to our project. Open up the Package Manager Console and run:

Install-Package Microsoft.Graph

Easy peasy, right?

Registering the application in Azure AD

Now, we need to tell Azure who we are. Head over to the Azure Portal and register your application. Don't worry, it's not as scary as it sounds:

  1. Navigate to Azure Active Directory
  2. Click on "App registrations" and then "New registration"
  3. Give your app a name and click "Register"

Once that's done, make a note of the client ID and tenant ID. You'll need these later!

Authentication

Alright, time for the fun part - authentication! We'll be using the Microsoft Authentication Library (MSAL) for this. Add the following NuGet package:

Install-Package Microsoft.Identity.Client

Now, let's acquire an access token:

var scopes = new[] { "https://graph.microsoft.com/.default" }; var clientId = "YOUR_CLIENT_ID"; var tenantId = "YOUR_TENANT_ID"; var app = ConfidentialClientApplicationBuilder .Create(clientId) .WithAuthority(AzureCloudInstance.AzurePublic, tenantId) .WithClientSecret("YOUR_CLIENT_SECRET") .Build(); var result = await app.AcquireTokenForClient(scopes).ExecuteAsync(); var accessToken = result.AccessToken;

Initializing GraphServiceClient

With our access token in hand, we can now create our GraphServiceClient:

var graphClient = new GraphServiceClient( new DelegateAuthenticationProvider( async (requestMessage) => { requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); }));

Basic Graph API operations

Now we're cooking! Let's try out some basic operations:

Retrieving user information

var user = await graphClient.Me.Request().GetAsync(); Console.WriteLine($"Hello, {user.DisplayName}!");

Listing emails

var messages = await graphClient.Me.Messages .Request() .Select(m => new { m.Subject, m.ReceivedDateTime }) .Top(10) .GetAsync(); foreach (var message in messages) { Console.WriteLine($"{message.ReceivedDateTime}: {message.Subject}"); }

Creating calendar events

var newEvent = new Event { Subject = "Team Lunch", Start = new DateTimeTimeZone { DateTime = "2023-06-15T12:00:00", TimeZone = "Pacific Standard Time" }, End = new DateTimeTimeZone { DateTime = "2023-06-15T13:00:00", TimeZone = "Pacific Standard Time" } }; await graphClient.Me.Events.Request().AddAsync(newEvent);

Error handling and best practices

Remember, things don't always go smoothly. Always wrap your API calls in try-catch blocks:

try { // Your API call here } catch (ServiceException ex) { Console.WriteLine($"Error making Graph API call: {ex.Message}"); }

Also, keep an eye on those rate limits. Microsoft Graph API has some pretty generous limits, but it's always good to be mindful of them.

Conclusion

And there you have it! You've just built a basic Microsoft Office 365 API integration using C# and the Microsoft.Graph package. Pretty cool, huh?

Remember, this is just scratching the surface. The Graph API is incredibly powerful and can do so much more. Why not try exploring more advanced scenarios like batch requests or change notifications next?

Keep coding, keep learning, and most importantly, have fun with it! The world of Microsoft Graph API is your oyster. Now go forth and build something awesome!