Integrate Microsoft Graph SDK
- Microsoft Graph API interacts through requests to Microsoft's cloud services. To simplify C# interactions, integrate the Microsoft Graph SDK. Use NuGet to install the SDK in your project.
- Open the NuGet Package Manager in your Visual Studio project and search for
Microsoft.Graph
to install the library.
Install-Package Microsoft.Graph
Authenticate with the Graph API
- Before sending requests, authenticate using Azure AD. This involves getting an access token and configuring your application for necessary permissions (like
Calendar.ReadWrite
).
- Use OAuth 2.0 authentication flow to get the access token. This involves registering your application in Azure AD and using client credentials or interactive user sign-in.
- Consider implementing an authentication provider using Microsoft's
InteractiveBrowserCredential
from the Azure.Identity
library for simple setups.
using Azure.Identity;
using Microsoft.Graph;
var clientSecretCredential = new ClientSecretCredential(
"<tenant-id>",
"<client-id>",
"<client-secret>"
);
GraphServiceClient graphClient = new GraphServiceClient(clientSecretCredential);
Create a Calendar Event
- Construct a new
Event
object specifying the details like subject, body, start time, end time, attendees, and location.
- Ensure to format the timezone and date-time correctly using ISO 8601 as followed by Microsoft Graph API.
var @event = new Event
{
Subject = "Meeting Invitation",
Body = new ItemBody
{
ContentType = BodyType.Html,
Content = "Please attend this meeting."
},
Start = new DateTimeTimeZone
{
DateTime = "2023-10-15T14:00:00",
TimeZone = "Pacific Standard Time"
},
End = new DateTimeTimeZone
{
DateTime = "2023-10-15T15:00:00",
TimeZone = "Pacific Standard Time"
},
Location = new Location
{
DisplayName = "Conference Room"
},
Attendees = new List<Attendee>
{
new Attendee
{
EmailAddress = new EmailAddress
{
Address = "user@example.com",
Name = "User Name"
},
Type = AttendeeType.Required
}
}
};
Send the Meeting Invite
- Use the
GraphServiceClient
instance to make a request to create the event in the user's calendar using the events
API.
- Specify the calendar, typically identified by the user's email or their unique ID.
- Handle exceptions and responses to ensure proper feedback and logging.
try
{
await graphClient.Users["<user-object-id>"].Events
.Request()
.AddAsync(@event);
Console.WriteLine("Meeting invite sent successfully.");
}
catch (ServiceException ex)
{
Console.WriteLine($"Error sending invite: {ex.Message}");
}
Manage Permissions
- Verify that your Azure AD application has all required Graph API permissions. At minimum,
Calendars.ReadWrite
permission is necessary to create and manage events.
- Depending on your application scenario, consider using both delegated and application permissions for broader access rights.
- Ensure that users consent to permissions if your app runs in a delegated permission mode.