Microsoft Graph .NET Client Library

repository·main·Indexed 21 days ago

https://github.com/microsoftgraph/msgraph-sdk-dotnet

A specialized SDK for integrating the Microsoft Graph API into .NET applications. It provides a type-safe, fluent interface for interacting with Microsoft 365 services using the GraphServiceClient. The library includes components for authentication via IAuthenticationProvider, request builders that mirror the REST API syntax, and property bag model classes for resource data. Documentation covers getting started, handling large OneDrive file downloads in chunks, and migration paths from v1 through v5.

Tokens
281.7K
Snippets
665
Records
886
Agent score
69%

What's inside microsoftgraph-msgraph-sdk-dotnet

  1. What is federatedIdpMfaBehavior and how to use it

    main

    The federatedIdpMfaBehavior property determines whether Azure AD accepts Multi-Factor Authentication (MFA) performed by a federated identity provider (IdP) when a user accesses an application governed by a conditional access policy.

    Possible Values

    • acceptIfMfaDoneByFederatedIdp: Azure AD accepts MFA performed by the federated IdP. If the IdP did not perform MFA, Azure AD performs it.
    • enforceMfaByFederatedIdp: Azure AD accepts MFA performed by the federated IdP. If the IdP did not perform MFA, Azure AD redirects the request to the federated IdP to perform MFA.
    • rejectMfaByFederatedIdp: Azure AD always performs MFA and rejects MFA performed by the federated IdP.
    • unknownFutureValue: Reserved for future use.

    Important Migration Notes

    • federatedIdpMfaBehavior is an evolved version of the SupportsMfa property from the MSOnline v1 PowerShell cmdlet.
    • Switching between federatedIdpMfaBehavior and SupportsMfa is not supported.
    • Once federatedIdpMfaBehavior is set, Azure AD ignores the SupportsMfa setting.
    • If federatedIdpMfaBehavior is never set, Azure AD continues to honor the SupportsMfa setting.
    • If neither is set, Azure AD defaults to acceptIfMfaDoneByFederatedIdp behavior.
  2. Query device memberships with filters and search

    main

    You can customize the memberOf request using OData query parameters.

    Advanced Query Requirements

    To use $search, OData casting (e.g., casting to microsoft.graph.group), or specific $filter expressions, you must include the following:

    1. The ConsistencyLevel: eventual request header.
    2. The $count=true query parameter.

    Supported Parameters

    • $search: Can be used on displayName and description properties.
    • $filter: Used to restrict results (e.g., startswith).
    • $count: Returns the total number of items.
    • $orderBy: Sorts the results.
    • OData Cast: Allows you to target specific types, such as microsoft.graph.group.
  3. Track changes in a driveItem using delta

    main

    Use the delta function to track changes in a driveItem and its children over time. This is the only way to guarantee you have read all necessary data for a full local representation of a drive or folder.

    Sync Workflow

    1. Initial Sync: Call delta without any parameters. The service enumerates the hierarchy and returns pages of items.
    2. Pagination: If the response contains an @odata.nextLink, continue calling that URL until you no longer see it or receive an empty set of changes.
    3. Apply Changes: Once all pages are received, apply the changes to your local state. Deleted items are identified by the deleted facet; these should be removed from your local state.
    4. Future Syncs: To check for new changes later, call delta using the @odata.deltaLink provided in the final response of your previous sync.

    Handling Errors

    If the service returns an HTTP 410 Gone error (e.g., due to an expired token), it will provide a Location header with a new nextLink to start a fresh enumeration. Use the following logic based on the error code:

    • resyncChangesApplyDifferences: Replace local items with the server's version (including deletes) and upload any local changes the server doesn't know about.
    • resyncChangesUploadDifferences: Upload local items the service did not return and upload files that differ from the server version.

    Permissions Required

    Permission typePermissions
    Delegated (work/school)Files.Read, Files.ReadWrite, Files.Read.All, Files.ReadWrite.All, Sites.Read.All, Sites.ReadWrite.All
    Delegated (personal)Files.Read, Files.ReadWrite, Files.Read.All, Files.ReadWrite.All
    ApplicationFiles.Read.All, Files.ReadWrite.All, Sites.Read.All, Sites.ReadWrite.All
    GraphServiceClient graphClient = new GraphServiceClient( authProvider );
    
    // Initial request to establish local state
    var delta = await graphClient.Me.Drive.Root
    	.Delta()
    	.Request()
    	.GetAsync();
    
    // Subsequent request using a delta token
    var nextDelta = await graphClient.Me.Drive.Root
    	.Delta("PREVIOUS_DELTA_TOKEN")
    	.Request()
    	.GetAsync();
  4. Subscription limitations for chatMessage, conversationMember, and team/channel/chat

    main

    When working with subscriptions for these specific resource types, keep the following requirements in mind:

    chatMessage, conversationMember, and team/channel/chat

    • Resource Data & Encryption: If includeResourceData is set to true, encryption is required. The subscription creation will fail if an encryptionCertificate is not provided.
    • chatMessage Specifics: To receive systemEventMessage types for /teams/{id}/channels/{id}/messages or /chats/{id}/messages, you must use the Prefer: include-unknown-enum-members request header.
    • Licensing: Certain endpoints like /teams/getAllMessages, /chats/getAllMembers, and /appCatalogs/teamsApps/{id}/installedToChats have licensing and payment requirements. Some support model=A and model=B query parameters, while others only support model=B.

    driveItem (OneDrive)

    • Personal OneDrive: You can subscribe to the root folder or any subfolder.
    • OneDrive for Business: You can only subscribe to the root folder.
    • Restriction: You cannot subscribe to individual files; you must subscribe to a folder (the subscription will then cover the hierarchy).
  5. Include resource data in chatMessage, conversationMember, and team/channel/chat subscriptions

    main

    When creating subscriptions for chatMessage, conversationMember, or team, channel, and chat resources, you can opt to include the actual resource data in the notification by setting includeResourceData to true.

    Requirements for including resource data:

    • Encryption: You MUST specify an encryptionCertificate in the request body. Failure to provide a certificate will cause the subscription creation to fail.
    • chatMessage specific: To receive the systemEventMessage value for the messageType enum when subscribing to /teams/{id}/channels/{id}/messages or /chats/{id}/messages, you must include the Prefer: include-unknown-enum-members request header.
    • Teams Protected APIs: Before creating chatMessage subscriptions with application permissions, you may need to request access via Protected APIs in Microsoft Teams.
  6. How to authenticate with Microsoft Graph

    main

    The Microsoft Graph .NET Client Library does not include a default authentication implementation. To authenticate requests, you have several options:

    1. Use an Authentication Provider: Provide an instance of IAuthenticationProvider when initializing the GraphServiceClient.
    2. DelegateAuthenticationProvider: Use the built-in DelegateAuthenticationProvider class to authenticate each request manually.
    3. msgraph-sdk-dotnet-auth: Use the preliminary set of authentication providers available in the msgraph-sdk-dotnet-auth repository.
    4. MSAL: For Microsoft Identity (Azure AD) authentication, the recommended library is MSAL (Microsoft Authentication Library).
  7. Retrieve Stream properties like bannerLogo

    main

    The standard Get organizationalBranding method does not return Stream properties. To retrieve properties like bannerLogo, you must use the localization endpoint. You can specify the value of id as default or 0 in the request URL.

    // Example of retrieving a stream property via the localization endpoint
    var stream = await graphClient.Organization["{organization-id}"].Branding.Localizations["{organizationalBrandingLocalization-id}"].BannerLogo
    	.Request()
    	.GetAsync();
  8. Core components of the Microsoft Graph .NET Client Library

    main

    The Microsoft Graph .NET Client Library is composed of six major components that work together to facilitate communication with the Microsoft Graph service:

    1. GraphServiceClient: The main entry point for building and sending requests.
    2. IAuthenticationProvider: Handles authenticating requests before they are sent.
    3. HTTP provider + serializer: Manages the underlying HTTP transport and data serialization.
    4. Request builder objects: Objects used to construct requests following the REST API pattern.
    5. Request objects: Represent the specific requests being made.
    6. Property bag model classes: Classes used for serializing and deserializing resource data (e.g., a User class representing a user resource).

    The library is designed to be highly extensible, allowing you to replace individual components with custom implementations.

  9. Use advanced query parameters for transitive members

    main

    To use advanced features like $search, $filter, $orderby, or OData type casting (e.g., microsoft.graph.user) on the transitiveMembers endpoint, you must include the following:

    1. Request Header: ConsistencyLevel: eventual
    2. Query Parameter: $count=true

    Using these parameters allows you to query against an index that might have a slight delay in reflecting recent changes.

  10. Communications Call Notifications

    main

    The Microsoft Graph communications service sends various notifications to your registered callbackUri. Common notification types include:

    • Establishing: Sent when the call state is establishing.
    • Established: Sent when the call state is established.
    • Content Sharing Started: Sent when a content sharing session is created.
    • Content Sharing Ended: Sent when a content sharing session is deleted.

    Warning: establishing and established notifications may arrive out of order.

  11. Query group members with $search, $filter, and $count

    main

    You can customize the group members response using OData query parameters. When using $search, $filter, $orderby, or OData casting, you must include the ConsistencyLevel: eventual request header.

    Supported Parameters:

    • $filter: Filter members based on properties (e.g., startswith(displayName, 'a')).
    • $count: Returns the total number of items. Requires ConsistencyLevel: eventual.
    • $select: Select specific properties to return.
    • $search: Search on displayName and description. Requires ConsistencyLevel: eventual.
    • $expand: Expand related resources.
    • OData Cast: Cast the collection to a specific type (e.g., microsoft.graph.user) to filter by type.
    var queryOptions = new List<QueryOption>()
    {
    	new QueryOption("$count", "true"),
    	new QueryOption("$search", "\"displayName:Pr\"")
    };
    
    var user = await graphClient.Groups["{group-id}"].Members
    	.Request( queryOptions )
    	.Header("ConsistencyLevel","eventual")
    	.Select("displayName,id")
    	.OrderBy("displayName")
    	.GetAsync();