Skip to content

Commit

Permalink
Updates documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
andrueastman committed Mar 23, 2022
1 parent e1e0aeb commit 2695bbf
Show file tree
Hide file tree
Showing 7 changed files with 196 additions and 152 deletions.
19 changes: 12 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
Integrate the [Microsoft Graph API](https://graph.microsoft.io) into your .NET
project!

The Microsoft Graph .NET Client Library targets .NetStandard 2.0 and .Net Framework 4.6.1.
The Microsoft Graph .NET Client Library targets .NetStandard 2.1

## Installation via NuGet

Expand All @@ -27,8 +27,6 @@ The Microsoft Graph .NET Client Library supports the use of TokenCredential clas

You can read more about available Credential classes [here](https://docs.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme#key-concepts) and examples on how to quickly setup TokenCredential instances can be found [here](docs/tokencredentials.md).

For more information on `DelegateAuthenticationProvider`, see the [library overview](docs/overview.md).

The recommended library for authenticating against Microsoft Identity (Azure AD) is [MSAL](https://github.com/AzureAD/microsoft-authentication-library-for-dotnet).

For an example of authenticating a UWP app using the V2 Authentication Endpoint, see the [Microsoft Graph UWP Connect Library](https://github.com/OfficeDev/Microsoft-Graph-UWP-Connect-Library).
Expand All @@ -51,20 +49,20 @@ of the Microsoft Graph API's RESTful syntax.
For example, to retrieve a user's default drive:

```csharp
var drive = await graphClient.Me.Drive.Request().GetAsync();
var drive = await graphClient.Me.Drive.GetAsync();
```

`GetAsync` will return a `Drive` object on success and throw a
`ServiceException` on error.
`ApiException` on error.

To get the current user's root folder of their default drive:

```csharp
var rootItem = await graphClient.Me.Drive.Root.Request().GetAsync();
var rootItem = await graphClient.Me.Drive.Root.GetAsync();
```

`GetAsync` will return a `DriveItem` object on success and throw a
`ServiceException` on error.
`ApiException` on error.

For a general overview of how the SDK is designed, see [overview](docs/overview.md).

Expand Down Expand Up @@ -112,6 +110,13 @@ Between 3.x and 4.x there were some major breaking changes:

View the upgrade guide [here](docs/upgrade-to-v4.md).


### Upgrading to v5

Between 4.x and 5.x there were several major breaking changes as the SDK now uses Kiota for code generation.

View the upgrade guide [here](docs/upgrade-to-v5.md).

## Issues

To view or log issues, see [issues](https://github.com/microsoftgraph/msgraph-sdk-dotnet/issues).
Expand Down
20 changes: 8 additions & 12 deletions docs/collections.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,17 @@ To retrieve a collection, like the list of groups in the service, you call `GetA
```csharp
await graphServiceClient
.Groups
.Request()
.GetAsync();
```

`GetAsync` returns an `ICollectionPage<T>` implementation on success and throws a `ServiceException` on error. For the groups collection, the type returned is `IGraphServiceGroupsCollectionPage`, which inherits `ICollectionPage<Item>`.
`GetAsync` returns an `IParsable` implementation on success and throws a `ServiceException` on error.

`IGraphServiceGroupsCollectionPage` contains three properties:
The `IParsable` instance returned will typically contain two properties:

|Name |Description |
|--------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------|
|**CurrentPage** |An `IList<Item>`. |
|**NextPageRequest** |An `IGraphServiceGroupsCollectionRequest` used to get to the next page of items, if another page exists. This value will be null if there is not a next page.|
|**Value** |An `List<Item>`. |
|**NextLink** |A `string` representing the url used to get to the next page of items, if another page exists. This value will be null if there is not a next page.|
|**AdditionalData** |An `IDictionary<string, object>` to any additional values returned by the service. In this case, none. |

## Adding to a collection
Expand All @@ -38,12 +37,11 @@ var groupToCreate = new Group
};

var newGroup = await graphServiceClient
.Groups
.Request()
.AddAsync(groupToCreate);
.Groups
.PostAsync(groupToCreate);
```

`AddAsync` returns the created group on success and throws a `ServiceException` on error.
`AddAsync` returns the created group on success and throws a `ApiException` on error.

## Expanding a collection

Expand All @@ -55,7 +53,5 @@ var children = await graphServiceClient
.Drive
.Items[itemId]
.Children
.Request()
.Expand("thumbnails")
.GetAsync();
.GetAsync((q) => q.Expand = new string[] { "thumbnails" });
```
39 changes: 1 addition & 38 deletions docs/headers.md
Original file line number Diff line number Diff line change
@@ -1,53 +1,16 @@
# Headers in the Microsoft Graph .NET Client Library


The .NET Client Library allows you to add your own custom request headers and inspect the response headers that come back from the Graph service.

## Adding request headers

Custom headers can be added by creating a new option collection and adding it to the request object:

```csharp
List<Option> options = new List<Option>();
options.Add(new HeaderOption("Etag", etag));
options.Add(new HeaderOption("If-Match", etag));
options.Add(new QueryOption("$filter", filterQuery));

var newObject = graphServiceClient
.Object
.Request(options)
.Patch(updatedObject);
```

You can also pass headers in individually if you only need to include one header:

```csharp
var newObject = graphServiceClient
.Object
.Request(new HeaderOption("Etag", etag))
.Patch(updatedObject);
```

## Reading response headers

HTTP response data is available in the `AdditionalData` property bag of the response object. You can access both the `statusCode` of the response and the `responseHeaders` to get more information, such as the request ID, Content-Type, and other data that may be relevant to you that is not part of the object model inherently.

To work with the response headers, you can deserialize the data using the client's serializer to make it easy to parse through the header dictionary:

```csharp
var user = await graphServiceClient....getAsync();

var statusCode = user.AdditionalData["statusCode"];
var responseHeaders = user.AdditionalData["responseHeaders"];

// Deserialize headers to dictionary for easy access to values
var responseHeaderCollection = graphClient
.HttpProvider
.Serializer
.DeserializeObject<Dictionary<string, List<string>>>(responseHeaders.ToString());

var requestId = responseHeaderCollection["request-id"][0];
.PatchAsync(h: h => { h.Add("Etag", "etag"); h.Add("If-Match", "ifmatch"); );
```


*Currently, requests that have a return type of `void` or `Stream` do not return response headers and cannot be inspected.*
98 changes: 4 additions & 94 deletions docs/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,28 +20,13 @@ To begin making requests with the library, you will need to initialize a **Graph

| Parameter | Required? | Default Value |
|:-----------------------------------------------|:---------------|:-------------------------------------------------|
|`string` baseUrl | No | https://graph.microsoft.com/currentServiceVersion|
|`IAuthenticationProvider` authenticationProvider| Yes | n/a |
|`IHttpProvider` httpProvider | No | `new HttpProvider(new Serializer())` |

## IAuthenticationProvider

The authentication provider is responsible for authenticating requests before sending them to the service. The Microsoft Graph .NET Client Library doesn't implement any authentication by default. Instead, you will need to retrieve access tokens for the service via the authentication library of your choice or by coding against one of the authentication endpoints directly. Please [read here](https://developer.microsoft.com/en-us/graph/docs/concepts/auth_overview) for more details about authenticating the Microsoft Graph service.

### DelegateAuthenticationProvider

The `DelegateAuthenticationProvider` is an implementation of `IAuthenticationProvider` that accepts a delegate to call during `AuthenticateRequestAsync`. This is the simplest way to append a retrieved access token to a request message:

``` csharp
var graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) => {
requestMessage
.Headers
.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

return Task.CompletedTask;
}));
```

You can also read about authentication with Kiota generated clients [here](https://github.com/microsoft/kiota/blob/main/docs/extending/authentication.md#authentication-with-kiota-clients)

## Resource model

Expand Down Expand Up @@ -72,28 +57,16 @@ The [Microsoft Graph service documentation](https://graph.microsoft.io/en-us/doc

### 2. Request calls

After you build the request you call the `Request` method on the request builder. This will construct the request object needed to make calls against the service.

For /me/calendar you call:

``` csharp
var calendarRequest = graphServiceClient
.Me
.Calendar
.Request();
```

All request builders have a `Request` method that can generate a request object. Request objects may have different methods on them depending on the type of request. To get /me/calendar you call:
To get /me/calendar you call:

``` csharp
var calendar = await graphServiceClient
.Me
.Calendar
.Request()
.GetAsync();
```

Any errors while building or sending a request will bubble up as a `ServiceException`. See [errors](/docs/errors.md) for more information on errors.
Any errors while building or sending a request will bubble up as an `ApiException`. See [errors](/docs/errors.md) for more information on errors.

## Query options

Expand All @@ -103,76 +76,13 @@ If you only want to retrieve certain properties of a resource you can select the
var user = await graphServiceClient
.Me
.Request()
.Select("id")
.GetAsync();
.GetAsync(q: q => q.Select = new string[] { "id"});
```

All properties other than `Id` will be null on the returned user object.

Expand, Skip, Top, OrderBy, and Filter are also supported via the client library when supported by the Microsoft Graph service for the request type.

## Custom query options

If you need to include more specific behavior during a request that is not supported by the library, you can create a custom queryOptions List that you can add when calling ```Request```:

``` chsarp
List<QueryOption> options = new List<QueryOption>
{
new QueryOption("$search", "lunch")
};
var messages = await client.Me.Messages.Request(options).GetAsync();
```



## Collections

Please see [collections](/docs/collections.md) for details on collections and paging.

## Send HTTP requests with the .Net Microsoft Graph client library

Sometimes, the functionality that you want to use isn't a part of the .NET client library. In this case, you can still use the client library to make your life easier. The client library can authenticate your requests and provide you the serializers. Here's an example of using the client library to create a OneNote page and deserialize the response object.

``` csharp

public async Task OneNoteAddPageHtml()
{
// Get a page of OneNote sections.
IOnenoteSectionsCollectionPage sectionPage = await graphClient.Me.Onenote.Sections.Request().GetAsync();

// Get a handle to the first section.
string sectionId = sectionPage[0].Id;

// Get the request URL for adding a page.
string requestUrl = graphClient.Me.Onenote.Sections[sectionId].Pages.Request().RequestUrl;

string htmlBody = @"<!DOCTYPE html><html><head><title>OneNoteAddPageHtml created this</title></head>
<body>Generated with love</body></html> ";

// Create the request message and add the content.
HttpRequestMessage hrm = new HttpRequestMessage(HttpMethod.Post, requestUrl);
hrm.Content = new StringContent(htmlBody, System.Text.Encoding.UTF8, "text/html");

// Authenticate (add access token) our HttpRequestMessage
await graphClient.AuthenticationProvider.AuthenticateRequestAsync(hrm);

// Send the request and get the response.
HttpResponseMessage response = await graphClient.HttpProvider.SendAsync(hrm);

// Get the OneNote page that we created.
if (response.IsSuccessStatusCode)
{
// Deserialize into OneNotePage object.
var content = await response.Content.ReadAsStringAsync();
OnenotePage page = graphClient.HttpProvider.Serializer.DeserializeObject<OnenotePage>(content);
}
else
throw new ServiceException(
new Error
{
Code = response.StatusCode.ToString(),
Message = await response.Content.ReadAsStringAsync()
});
}

```
Loading

0 comments on commit 2695bbf

Please sign in to comment.