Hey there, fellow developer! Ready to dive into the world of Microsoft Graph API? If you're looking to supercharge your C# applications with access to Microsoft 365 data, you're in the right place. We'll be using the Microsoft.Graph package to make our lives easier, so buckle up and let's get started!
Before we jump in, make sure you've got these essentials:
Got all that? Great! Let's move on to the fun stuff.
First things first, let's create a new C# project. Fire up your IDE and create a new console application. Now, let's add some Graph goodness to our project:
dotnet add package Microsoft.Graph
Easy peasy, right?
Alright, time to tackle authentication. We'll be using MSAL.NET to handle this for us. Add the Microsoft.Identity.Client package to your project:
dotnet add package Microsoft.Identity.Client
Now, let's acquire an access token:
var scopes = new[] { "User.Read" }; var clientId = "YOUR_CLIENT_ID"; var tenantId = "YOUR_TENANT_ID"; var app = PublicClientApplicationBuilder .Create(clientId) .WithAuthority(AzureCloudInstance.AzurePublic, tenantId) .WithRedirectUri("http://localhost") .Build(); var result = await app.AcquireTokenInteractive(scopes).ExecuteAsync(); var accessToken = result.AccessToken;
With our access token in hand, let's create a GraphServiceClient:
var graphClient = new GraphServiceClient( new DelegateAuthenticationProvider( async (requestMessage) => { requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); }));
Now for the good stuff - let's make some API calls!
var user = await graphClient.Me.Request().GetAsync(); Console.WriteLine($"Hello, {user.DisplayName}!");
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);
var messages = await graphClient.Me.Messages .Request() .Top(10) .GetAsync(); while (messages.NextPageRequest != null) { messages = await messages.NextPageRequest.GetAsync(); // Process messages }
The Graph API is vast, but here are some common endpoints you might find useful:
var users = await graphClient.Users.Request().GetAsync();
var groups = await graphClient.Groups.Request().GetAsync();
var events = await graphClient.Me.Calendar.Events.Request().GetAsync();
var driveItems = await graphClient.Me.Drive.Root.Children.Request().GetAsync();
Always implement retry logic for transient errors:
var retryHandler = new RetryHandler(new HttpClientHandler(), 3); var httpClient = new HttpClient(retryHandler); var graphClient = new GraphServiceClient(httpClient, ...);
And don't forget to handle common errors gracefully:
try { // Your Graph API call here } catch (ServiceException ex) { if (ex.StatusCode == HttpStatusCode.TooManyRequests) { // Handle throttling } // Handle other exceptions }
And there you have it! You're now equipped to integrate Microsoft Graph API into your C# applications. Remember, this is just scratching the surface - there's so much more you can do with Graph API.
Keep exploring, keep coding, and most importantly, have fun! If you want to dive deeper, check out the official Microsoft Graph documentation and sample repos on GitHub. Happy coding!