February 9th, 2023

Write simpler code with the new Microsoft Graph .NET SDK v5

Maisa Rissi
Product Manager

Using the Microsoft Graph .NET SDK, you can take advantage of a fluent API and models that support retry handling, secure redirects, batching requests, large file management, and many more capabilities. This allows you to focus on what really matters, your business.

Today, we’re announcing the release candidate of Microsoft Graph .NET SDK version 5.0 that includes features to enhance your development experience, described below.

Combine both v1.0 and beta APIs for testing and early adoption

Users should always rely on Microsoft Graph v1.0 when building their application. However, sometimes there is a need to use the Microsoft Graph beta endpoint for testing or early adoption before a feature is available in v1.0. The beta endpoint and the functionality there is still in preview status and can change. This makes the beta endpoints unreliable for production usage since it may break existing scenarios without notice.

So, thinking of that, you can now easily combine both production and preview in any application you might need, using v1.0 as much as possible and beta only where you truly need. You can now combine both v1.0 and beta libraries in one project. This approach offers the benefit of only using preview beta APIs when necessary and relying on stable v1.0 as much as possible.

https://gist.github.com/maisarissi/b3e811d959d091ed88b7f684ab9e1dd9

Get specialized objects with OData cast support

OpenAPI has a way to describe which property can be used as a discriminator on an object type to determine the true type of an object, adding support for polymorphism.

With the OData cast support, SDK users can easily access properties available on a specialized type rather than going through the AdditionalData. OData cast allows downcasting, the result to the right specialized type. This can be exemplified in the Microsoft Graph API by members of a group. It can be either a User, Application, Device, Group and more.

https://gist.github.com/maisarissi/92b6e6afcc821de6581d883403e7f470

Use more accurate and simplified fluent API and improve code readability

To ease the use of the SDK, the Microsoft Graph .NET v5 simplifies the fluent API to create requests to call Microsoft Graph API, improving the code readability thanks to method chaining and reduces the developer’s learning curve.

1.      Write less error-prone code with better intellisense

Users can now add headers and any query options to customize any request by using the new requestConfiguration modifier. With the new modifier, the accuracy of the intellisense in the SDK was also improved, so you see suggestions only for methods that are actually supported by the underlying API.

https://gist.github.com/maisarissi/47f316cd91d3042515d5a17cbc08d59b


2.      Count support available in the request builder

With a new Count functionality, SDK users can simplify extending Microsoft Graph API queries with the $count segment when supported by the API. This applies only for $count as URL segment. The $count as a query string parameter needs to use the new requestConfiguration modifier as exemplified above.

https://gist.github.com/maisarissi/6fd2eddc689eeb0137f53e07ae8d0172

3.      Avoid breaking changes by leveraging parameter objects

APIs are always evolving and adding new functionality. To do so, sometimes it’s necessary to change the parameters accepted by them so that users can leverage everything that an API has to offer. Users can now create a request body and pass it as part of the request method. With this feature, you won’t have to rewrite your code every time there is a change to the parameters of an OData action.

https://gist.github.com/maisarissi/49570879e4691217e528bf102dd6a69c

4.      Simplified method chaining

Thinking of improving both the learning curve to SDK users and discoverability of what is supported by the APIs, request methods have been renamed to reflect the actual HTTP method being used, so UpdateAsync has become PatchAsync and AddAsync has become PostAsync. In addition to that, the need to use Request() for every call is now in the past, improving the code readability by making it cleaner.

As an example, let’s look at a post request using v4. 

https://gist.github.com/maisarissi/4854ae1b7fffae63659e3c29bebfea03

Now, SDK users can just stick to the point and only have code that means something: 

https://gist.github.com/maisarissi/c26c4eb16edf5453cf295265a42372d7

Backing store

Microsoft Graph .NET SDK v5 now introduces the backing store which allows tracking any changes made to objects. Thanks to the backing store, users can update more efficiently modified objects by minimizing the amount of data sent to the API. This significantly improves the performance of your applications.

That also means null properties will no longer be ignored when they are actually set by the user. This unblocks scenarios like disabling recurrence on an event or removing a mobile phone from a user, when using the SDK.

https://gist.github.com/maisarissi/d662d4579ac5661216b869a1c6fbd403

Remove complexity when handling with collections

Often times, users need to retrieve information from Microsoft Graph. With the new version, the SDK removes complexity when handling with collections by matching the shape of the API response, allowing you to easily retrieve and create a list of objects from the result of the GET operation. And even provides direct access to other properties that may come back, such as @odata.nextLink.

https://gist.github.com/maisarissi/6cc084f4f30519445bf42122368f8a2a

However, some queries against Microsoft Graph return multiple pages of data either due to server-side paging or due to the use of the $top query parameter to specifically limit the page size in a request. For performance reasons or when more than one query request is required to retrieve all the results, Microsoft Graph returns an @odata.nextLink property in the response that contains a URL to the next page of results. The SDK provides a PageIterator class to absorb complexity and help with pagination.

https://gist.github.com/maisarissi/b7f2a5bde58923bad0439a6c770db149

Enhanced error handling

You can now have actionable information when something goes wrong with your requests with the new enhanced error handling. The SDK now throws specific instances of ODataError exceptions that rely on the metadata provided by the API to return valuable details rather than a generic ServiceException that was thrown before in any situation.

https://gist.github.com/maisarissi/0456cd4a781843f560eda0209b17bad6

Custom authentication flows facilitate token acquisition

Custom flows like DelegateAuthenticationProvider come now with additional configuration so users can focus on the token acquisition and not how the request is authenticated.  In most cases, users will remain as a similar experience from what was offered in previous version.

https://gist.github.com/maisarissi/3ddc2c8269e6e4a8f13838373fe7751e

Next steps

Check out this sample app using the Microsoft Graph .NET SDK v5 that you can run and try to build something. Or access this detailed document that outlines breaking changes, fixes and guides you through the migration that an SDK user might run while upgrading to v5. It also provides examples to implement the new features, helping you quickly take advantage of all the new capabilities.

Add the new SDK to your project by running the following command in the Package Manager Console:

Install-Package Microsoft.Graph -PreRelease

Try out the new version today!

Try out the new version and let us know what you think on GitHub! For questions about the Microsoft Graph API, go to Microsoft Q&A.

Get started with the Microsoft Graph API

Microsoft Graph is a single REST API that unifies data across many Microsoft services under one single endpoint, a powerful tool to build applications that work with data from Office 365 and other Microsoft services.

Learn more about Microsoft Graph SDKs

The SDK includes a set of tools, libraries, and documentation that make it easy to get started building applications that take advantage of the rich data and insights available through Microsoft Graph API.

Start saving time and removing complexity in your code today. Sign up for the Microsoft 365 Developer Program to get a free Microsoft 365 developer subscription and start using .NET to connect to Microsoft Graph. We also recommend that you join our Microsoft 365 Platform community calls and events and get involved with other developers who use Microsoft Graph and build solutions for Microsoft 365.

Here are some resources we have pulled together to help you get started.

  1. Explore our public documentation, where you can find how to install the SDK, authenticate, discover which API a cmdlet is calling and more.
  2. Use the Microsoft Graph Explorer, a tool that lets you make requests and see responses against the Microsoft Graph, and which displays corresponding snippets to requests you make.
  3. Visit the Microsoft Graph Dev Center.

Thank you!

We’d like to thank all the members of the community who have helped us make this release better by reporting issues in GitHub! Keep them coming!

Author

Maisa Rissi
Product Manager

5 comments

Discussion is closed. Login to edit/delete existing comments.

  • Oleg Deribas

    How does OData cast works in this example:
    <code>
    Would this automatically add filter so the query would return only objects of type User? Or it would try to cast everything to type user? I definitely hope for the first, but need to ask just because cast term is used.

    Read more
    • Philippe SignoretMicrosoft employee · Edited

      The resulting request will look like this:

      <code>

      Which will return the first page of direct user members of the group. Members of other types (e.g. group or servicePrincipal) will not be returned.

      This is described in the OData 4.0 spec at https://docs.oasis-open.org/odata/odata/v4.0/cs01/part2-url-conventions/odata-v4.0-cs01-part2-url-conventions.html#_Addressing_Derived_Types:

      Any resource path or path expression identifying a collection of entities or complex type instances can be appended with a path segment containing the qualified name of a type derived from the declared type of...

      Read more
      • Joe Lopez

        I have an API call that applies a filter to the users returned:

        GET https://graph.microsoft.com/v1.0/groups/{id}/members/microsoft.graph.user?$count=true&$filter=createdDateTime ge 2022-02-28T00:00:00Z

        How would that look using the new SDK v5?

      • Maisa RissiMicrosoft employee Author

        You will need to use the requestConfiguration to apply the query options you need as exemplified here.

        Something along the lines of:

        var usersInGroup = await graphServiceClient
            .Groups["group-id"]
            .Members
            .GraphUser
            .GetAsync(rc =>
            {
                rc.QueryParameters.Count = true;
                rc.QueryParameters.Filter = "createdDateTime ge 2022-02-28T00:00:00Z";
            }););
      • Joe Lopez · Edited

        Thank you, it was the “rc.QueryParameters.Count = true” part I was missing.

        Another issue we have is with not being able to create a user because their email is in another user’s proxy addresses. It’s currently a read-only collection and we’ve tried other ways without success. Will we ever be able to delete a proxy address using v5?