diff --git a/docs/graph/authentication/ProviderManager.md b/docs/graph/authentication/ProviderManager.md index 34ea2f7ad..5f2597548 100644 --- a/docs/graph/authentication/ProviderManager.md +++ b/docs/graph/authentication/ProviderManager.md @@ -11,15 +11,14 @@ dev_langs: The ProviderManager manages access to the globally configured [IProvider](./custom.md) instance and any state change events as users sign in and out. -> Available in the `CommunityToolkit.Authentication` package. - -> [!IMPORTANT] -> Windows Community Toolkit - Graph Controls and Helpers packages are in preview. To get started using WCT preview packages visit the [WCT Preview Packages wiki page](https://aka.ms/wct/wiki/previewpackages). +Available in the `CommunityToolkit.Authentication` package. ## Properties | Property | Type | Description | | -- | -- | -- | +| ClientName | string | (*Static*) Gets the name of the toolkit client to identify self in Graph calls. | +| Instance | ProviderManager | (*Static*) Get or set the instance of the globally configured IProvider. | | State | ProviderState | Gets the current authentication state of the provider. | ## Events diff --git a/docs/graph/authentication/custom.md b/docs/graph/authentication/custom.md index 8321aeb21..6273027b1 100644 --- a/docs/graph/authentication/custom.md +++ b/docs/graph/authentication/custom.md @@ -1,5 +1,5 @@ --- -title: IProvider +title: Custom authentication providers author: shweaver-MSFT description: IProvider interface defines the basic functions of an authentication provider in the Graph toolkit. keywords: uwp, wpf, netstandard, windows, community, toolkit, graph, login, authentication, provider, providers, identity @@ -7,18 +7,15 @@ dev_langs: - csharp --- -# Custom provider +# Custom authentication providers If you have existing authentication code in your application, you can create a custom provider to enable authentication and access to Microsoft Graph for the toolkit's Graph based controls and helpers. To bring your own authentication provider logic, start by extending `IProvider`. ## IProvider -`IProvider` is the base interface for creating authentication providers that work with the various controls and helpers in the toolkit. Handle authenticaiton with one of our premade `IProvider` implementations or create your own. +`IProvider` is the base interface for creating authentication providers that work with the various controls and helpers in the toolkit. Handle authentication with one of our premade `IProvider` implementations or create your own. -> Available in the `CommunityToolkit.Authentication` package. - -> [!IMPORTANT] -> Windows Community Toolkit - Graph Controls and Helpers packages are in preview. To get started using WCT preview packages visit the [WCT Preview Packages wiki page](https://aka.ms/wct/wiki/previewpackages). +Available in the `CommunityToolkit.Authentication` package. ```csharp using CommunityToolkit.Authentication; @@ -47,7 +44,7 @@ ProviderManager.Instance.GlobalProvider = customProvider; | Method | Arguments | Returns | Description | | -- | -- | -- | -- | | AuthenticateRequestAsync | HttpRequestMessage | Task | Authenticate an outgoing request. | -| GetTokenAsync | bool silentOnly = false, string[] scopes = null | Task<string> | Retrieve a token for the authenticated user. | +| GetTokenAsync | bool silentOnly = false | Task<string> | Retrieve a token for the authenticated user. | | SignInAsync | | Task | Sign in a user. | | SignOutAsync | | Task | Sign out the current user. | | TrySilentSignInAsync | | Task<bool> | Try signing in silently, without prompts. | diff --git a/docs/graph/authentication/msal.md b/docs/graph/authentication/msal.md index 2a6b7e2ba..59dcf7609 100644 --- a/docs/graph/authentication/msal.md +++ b/docs/graph/authentication/msal.md @@ -11,10 +11,7 @@ dev_langs: The MsalProvider is an [IProvider](./custom.md) implementation built on the official Microsoft Authentication Library (MSAL). It is NetStandard 2.0 so it works in both UWP and WPF apps. -> Available in the `CommunityToolkit.Authentication.Msal` package. - -> [!IMPORTANT] -> Windows Community Toolkit - Graph Controls and Helpers packages are in preview. To get started using WCT preview packages visit the [WCT Preview Packages wiki page](https://aka.ms/wct/wiki/previewpackages). +Available in the `CommunityToolkit.Authentication.Msal` package. ```csharp using CommunityToolkit.Authentication; diff --git a/docs/graph/authentication/overview.md b/docs/graph/authentication/overview.md index fdd09cf86..764afa434 100644 --- a/docs/graph/authentication/overview.md +++ b/docs/graph/authentication/overview.md @@ -9,9 +9,6 @@ dev_langs: # Authentication Providers Overview -> [!IMPORTANT] -> Windows Community Toolkit - Graph Controls and Helpers packages are in preview. To get started using WCT preview packages visit the [WCT Preview Packages wiki page](https://aka.ms/wct/wiki/previewpackages). - Authentication is always the first step to working with Microsoft Graph. The toolkit providers enable your application to authenticate with Microsoft Identity and access Microsoft Graph in only few lines of code. Each provider handles user authentication and acquiring access tokens to call Microsoft Graph APIs, so that you don't have to write this code yourself. You can use the providers on their own, without components, to quickly implement authentication for your app and make calls to Microsoft Graph via the Microsoft Graph .NET SDK. @@ -22,9 +19,9 @@ The toolkit includes the following providers: | Providers | Description | | -- | -- | -| [Msal](./msal.md) | Uses MSAL for .NET to sign in users and acquire tokens to use with Microsoft Graph in a NetStandard 2.0 application. | -| [Windows](./windows.md) | Uses native WebAccountManager (WAM) APIs to sign in users and acquire tokens to use with Microsoft Graph in a UWP application. | -| [Custom](./custom.md)Custom | Create a custom provider to enable authentication and access to Microsoft Graph with your application's existing authentication code. | +| [Msal](./msal.md) | Uses MSAL for .NET to sign in users and acquire tokens to use with Microsoft Graph in NetStandard 2.0 applications. | +| [Windows](./windows.md) | Uses native WebAccountManager (WAM) APIs to sign in users and acquire tokens to use with Microsoft Graph in UWP applications. | +| [Custom](./custom.md) | Create a custom provider to enable authentication and access to Microsoft Graph with your application's existing authentication code. | ## Initializing the GlobalProvider @@ -69,6 +66,8 @@ public enum ProviderState } ``` +## Respond to changes in the GlobalProvider state + In some scenarios, you will want to show certain functionality or perform an action only after a user has successfully signed in. You can access and check the provider state as shown in the following example: ```csharp @@ -79,7 +78,7 @@ if (ProviderManager.Instance.GlobalProvider?.State === ProviderState.SignedIn) { } ``` -You can also use the `ProviderUpdated` and `ProviderStateChanged` events to get notified whenever provider is set or changes state. +Use the `ProviderUpdated` and `ProviderStateChanged` events to get notified whenever provider is set or changes state. ```csharp using CommunityToolkit.Authentication; @@ -98,6 +97,43 @@ void OnProviderStateChanged(object sender, ProviderUpdatedEventArgs args) } ``` +### ProviderStateTrigger + +To respond to provider state changes from XAML, try out the `ProviderStateTrigger` state trigger. + +Available in the `CommunityToolkit.Graph.Uwp` package. + +```xml + + + + + + + + + + + + + + + + +``` + +### FrameworkElement.IsVisibleWhen + +The `FrameworkElement.IsVisibleWhen` attached property makes it easy to toggle visibility for any `FrameworkElement`. + +Available in the `CommunityToolkit.Graph.Uwp` package. + +```xml + + + +``` + ## Getting an access token Each provider exposes a function called `getTokenAsync` that can retrieve the current access token or retrieve a new access token for the provided scopes. The following example shows how to get a new access token or the currently signed in user: @@ -113,14 +149,14 @@ string token = await provider.GetTokenAsync(silentOnly: false); ## Call Microsoft Graph APIs -Once authenticated, you can now make API calls to Microsoft Graph using the Graph SDK or without. +Once authenticated, you can now make API calls to Microsoft Graph using the Graph SDK or without. See the [Extensions](../helpers/extensions.md) page for an example of how to authenticate an outbound request directly. ### Use the Graph SDK -Access APIs using the Graph SDK through a preconfigured `GraphServiceClient` available through an extension method on `IProvider` called, `GetClient()`. +Access APIs using the Graph SDK through a preconfigured `GraphServiceClient` available through an extension method on `IProvider` called `GetClient()` and `GetBetaClient()`. See [Microsoft Graph Extensions](../helpers/extensions.md) for more details. -This is the easiest way to get started because all of the Graph types are available and the `GraphServiceClient` offers a convenient way of building requests. +It's possible to authenticate and make all Graph requests manually, without the Graph SDK. This can reduce package size significantly. However, using the Graph SDK is certainly the easiest way to work with Graph in .NET because the `GraphServiceClient` offers a convenient way of building requests and includes all of the object types ready to use. Available in the `CommunityToolkit.Graph` package. @@ -133,50 +169,3 @@ GraphServiceClient graphClient = provider.GetClient(); var me = await graphClient.Me.Request().GetAsync(); ``` - -### Handle Graph requests manually - -Access APIs by managing requests to Microsoft Graph yourself. This is helpful for projects with existing systems for managing web requests, or for keeping package sizes minimal by excluding the Graph SDK. - -To make Graph API calls manually, use the `IProvider.AuthenticateRequestAsync(HttpRequestMessage)` method to authenticate an outgoing request. - -```csharp -using CommunityToolkit.Authentication; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -private async Task> GetDefaultTaskListAsync() -{ - return await GetResponseAsync>("https://graph.microsoft.com/v1.0/me/todo/lists/tasks/tasks"); -} - -private async Task GetResponseAsync(string requestUri) -{ - // Build the request - HttpRequestMessage getRequest = new HttpRequestMessage(HttpMethod.Get, requestUri); - - // Authenticate the request - await ProviderManager.Instance.GlobalProvider.AuthenticateRequestAsync(getRequest); - - var httpClient = new HttpClient(); - using (httpClient) - { - // Send the request - var response = await httpClient.SendAsync(getRequest); - - if (response.IsSuccessStatusCode) - { - // Handle the request response - var jsonResponse = await response.Content.ReadAsStringAsync(); - var jObject = JObject.Parse(jsonResponse); - if (jObject.ContainsKey("value")) - { - var result = JsonConvert.DeserializeObject(jObject["value"].ToString()); - return result; - } - } - } - - return default; -} -``` diff --git a/docs/graph/authentication/windows.md b/docs/graph/authentication/windows.md index 3510765cb..a706ecf5e 100644 --- a/docs/graph/authentication/windows.md +++ b/docs/graph/authentication/windows.md @@ -12,10 +12,7 @@ dev_langs: The WindowsProvider is an authentication provider for accessing locally configured accounts on Windows. It extends [IProvider](./custom.md) and uses the native Windows AccountManager (WAM) APIs and AccountsSettingsPane for sign in. -> Available in the `CommunityToolkit.Authentication.Uwp` package. - -> [!IMPORTANT] -> Windows Community Toolkit - Graph Controls and Helpers packages are in preview. To get started using WCT preview packages visit the [WCT Preview Packages wiki page](https://aka.ms/wct/wiki/previewpackages). +Available in the `CommunityToolkit.Authentication.Uwp` package. ## Prerequisite Windows Store Association in Visual Studio @@ -30,27 +27,25 @@ To get valid tokens and complete sign in, the app will need to be associated wit > [!NOTE] > You must have a Windows Developer account to use the WindowsProvider in your UWP app. You can [register a Microsoft developer account](https://developer.microsoft.com/store/register) if you don't already have one. - ## Syntax @@ -64,9 +59,8 @@ using CommunityToolkit.Authentication; ProviderManager.Instance.GlobalProvider = new WindowsProvider(new string[] { "User.Read", "Tasks.ReadWrite" }); ``` -The WindowsProvider can also be configured to disabled auto-signin or show custom content in the `AccountsSettingsPane`. -Additional configuration for account types will be available via the `WebAccountProviderConfig` object in the future. -Currently, only consumer MSA accounts are supported. +The WindowsProvider can also be configured to disable auto-login or show custom content in the `AccountsSettingsPane`. +Configuration for specifying supported account types (such as AAD) is available via the `WebAccountProviderConfig` object. ```CSharp using CommunityToolkit.Authentication; @@ -82,9 +76,11 @@ void OnSettingsCommandInvoked(IUICommand command) System.Diagnostics.Debug.WriteLine("AccountsSettingsPane command invoked: " + command.Id); } -// Configure which types accounts should be available to choose from. The default is MSA, but AAD will come in the future. -// ClientId is only required for approving admin level consent in AAD tenants. -var webAccountProviderConfig = new WebAccountProviderConfig(WebAccountProviderType.MSA, "YOUR_CLIENT_ID_HERE"); +// Configure which types of accounts should be available to choose from. The default is MSA, but AAD is also supported. +var webAccountProviderConfig = new WebAccountProviderConfig(WebAccountProviderType.Msa); + +// ClientId is only required for approving admin level consent in AAD tenants or for supporting advanced authentication scenarios like SSO. +//var webAccountProviderConfig = new WebAccountProviderConfig(WebAccountProviderType.Aad, "YOUR_CLIENT_ID_HERE"); // Configure details to present in the AccountsSettingsPane, such as custom header text and links. var accountsSettingsPaneConfig = new AccountsSettingsPaneConfig( diff --git a/docs/graph/controls/GraphPresenter.md b/docs/graph/controls/GraphPresenter.md new file mode 100644 index 000000000..aab0bb88a --- /dev/null +++ b/docs/graph/controls/GraphPresenter.md @@ -0,0 +1,93 @@ +--- +title: GraphPresenter XAML Control +author: shweaver +description: The GraphPresenter control enables adhoc visualization of any Graph API. +keywords: windows 10, uwp, windows community toolkit, uwp community toolkit, uwp toolkit, presenter, graphpresenter, graph +dev_langs: + - csharp +--- + +# (Experimental) GraphPresenter XAML Control + +The GraphPresenter is a flexible XAML control for visualizing Graph API data. Provide an `IBaseRequestBuilder` implementation and the GraphPresenter will automatically fetch the data from the proper Graph endpoint, ready for visualization. Because every Graph entity is different, this control has no default UI of it's own. It is up to the developer to decide how the data should be presented by setting the control's `ContentTemplate`. This control is great for prototyping and experimentation purposes, but we suggest creating your own user controls for production scenarios. + +Available in the `CommunityToolkit.Graph.Uwp` package. + +## Syntax + +### XAML + +```xml + + + + + + + + + + + + + + + + + +``` + +### Code-behind + +```csharp +public IBaseRequestBuilder RecentDriveItemsRequestBuilder { get; set; } + +public GraphPresenterSamplePage() +{ + InitializeComponent(); + + ProviderManager.Instance.ProviderStateChanged += (s, e) => UpdateRequestBuilder(); + UpdateRequestBuilder(); +} + +private void UpdateRequestBuilder() +{ + var provider = ProviderManager.Instance.GlobalProvider; + switch (provider?.State) + { + case ProviderState.SignedIn: + RecentDriveItemsRequestBuilder = provider.GetClient().Me.Drive.Recent(); + break; + + default: + RecentDriveItemsRequestBuilder = null; + break; + } +} +``` + +## Properties + +| Property | Type | Description | +| -- | -- | -- | +| RequestBuilder | IBaseRequestBuilder | Used to make a request to the graph. The results will be automatically populated to the `ContentPresenter.ContentTemplate` property. Use a `ContentPresenter.ContentTemplate` to change the presentation of the data. | +| ResponseType | Type | The type of item returned by the `RequestBuilder`. | +| IsCollection | bool | A value indicating whether the returned data from the `RequestBuilder` is a collection. | +| QueryOptions | List<QueryOption> | A list of `QueryOption` values to pass into the request built by the `RequestBuilder`. | +| OrderBy | string | A string to indicate a sorting order for the `RequestBuilder`. This is a helper to add this specific request option to the `QueryOptions`. + +## Requirements + +* **Namespace:** CommunityToolkit.Graph.Uwp.Controls +* **NuGet package:** [CommunityToolkit.Graph.Uwp](https://www.nuget.org/packages/CommunityToolkit.Graph.Uwp) + +## API + +* [GraphPresenter source code](https://github.com/windows-toolkit/Graph-Controls/tree/main/CommunityToolkit.Graph.Uwp/Controls/GraphPresenter) + +## Related Topics + +* [MGT Get Component](/graph/toolkit/components/get) diff --git a/docs/graph/controls/LoginButton.md b/docs/graph/controls/LoginButton.md index 7a04eb2ef..a58bfbe2e 100644 --- a/docs/graph/controls/LoginButton.md +++ b/docs/graph/controls/LoginButton.md @@ -7,17 +7,14 @@ dev_langs: - csharp --- -# (Preview) LoginButton XAML Control +# LoginButton XAML Control The LoginButton is both a button and flyout control to facilitate Microsoft identity platform authentication. It provides two states: * When the user is not signed in, the control is a simple button to initiate the sign in process. * When the user is signed in, the control displays the current signed in user name, profile image, and email. When clicked, a flyout is opened with a command to sign out. -> Available in the `CommunityToolkit.Graph.Uwp` package. - -> [!IMPORTANT] -> Windows Community Toolkit - Graph Controls and Helpers packages are in preview. To get started using WCT preview packages visit the [WCT Preview Packages wiki page](https://aka.ms/wct/wiki/previewpackages). +Available in the `CommunityToolkit.Graph.Uwp` package. ## Syntax @@ -50,10 +47,8 @@ The LoginButton is both a button and flyout control to facilitate Microsoft iden ## Requirements -| Device family | Universal, MinVersion or higher | -| -- | -- | -| Namespace | CommunityToolkit.Graph.Uwp.Controls | -| NuGet package | [CommunityToolkit.Graph.Uwp](https://www.nuget.org/packages/CommunityToolkit.Graph.Uwp) | +* **Namespace:** CommunityToolkit.Graph.Uwp.Controls +* **NuGet package:** [CommunityToolkit.Graph.Uwp](https://www.nuget.org/packages/CommunityToolkit.Graph.Uwp) ## API diff --git a/docs/graph/controls/PeoplePicker.md b/docs/graph/controls/PeoplePicker.md index dc0b15a98..10143cbdc 100644 --- a/docs/graph/controls/PeoplePicker.md +++ b/docs/graph/controls/PeoplePicker.md @@ -7,14 +7,11 @@ dev_langs: - csharp --- -# (Preview) PeoplePicker XAML Control +# PeoplePicker XAML Control The PeoplePicker searches for people and renders the list of results from Microsoft Graph. By default, the component will search across all people. -> Available in the `CommunityToolkit.Graph.Uwp` package. - -> [!IMPORTANT] -> Windows Community Toolkit - Graph Controls and Helpers packages are in preview. To get started using WCT preview packages visit the [WCT Preview Packages wiki page](https://aka.ms/wct/wiki/previewpackages). +Available in the `CommunityToolkit.Graph.Uwp` package. ## Syntax @@ -37,10 +34,8 @@ The PeoplePicker searches for people and renders the list of results from Micros ## Requirements -| Device family | Universal, MinVersion or higher | -| -- | -- | -| Namespace | CommunityToolkit.Graph.Uwp.Controls | -| NuGet package | [CommunityToolkit.Graph.Uwp](https://www.nuget.org/packages/CommunityToolkit.Graph.Uwp) | +* **Namespace:** CommunityToolkit.Graph.Uwp.Controls +* **NuGet package:** [CommunityToolkit.Graph.Uwp](https://www.nuget.org/packages/CommunityToolkit.Graph.Uwp) ## API diff --git a/docs/graph/controls/PersonView.md b/docs/graph/controls/PersonView.md index 91e41b20f..d89a2cb89 100644 --- a/docs/graph/controls/PersonView.md +++ b/docs/graph/controls/PersonView.md @@ -11,10 +11,7 @@ dev_langs: The PersonView control is used to display a person or contact by using their photo, name, and/or email address. -> Available in the `CommunityToolkit.Graph.Uwp` package. - -> [!IMPORTANT] -> Windows Community Toolkit - Graph Controls and Helpers packages are in preview. To get started using WCT preview packages visit the [WCT Preview Packages wiki page](https://aka.ms/wct/wiki/previewpackages). +Available in the `CommunityToolkit.Graph.Uwp` package. ## Syntax @@ -42,10 +39,8 @@ The PersonView control is used to display a person or contact by using their pho ## Requirements -| Device family | Universal, MinVersion or higher | -| -- | -- | -| Namespace | CommunityToolkit.Graph.Uwp.Controls | -| NuGet package | [CommunityToolkit.Graph.Uwp](https://www.nuget.org/packages/CommunityToolkit.Graph.Uwp) | +* **Namespace:** CommunityToolkit.Graph.Uwp.Controls +* **NuGet package:** [CommunityToolkit.Graph.Uwp](https://www.nuget.org/packages/CommunityToolkit.Graph.Uwp) ## API diff --git a/docs/graph/getting-started.md b/docs/graph/getting-started.md index 32ff15d3e..8d0aa6547 100644 --- a/docs/graph/getting-started.md +++ b/docs/graph/getting-started.md @@ -1,19 +1,16 @@ --- -title: Getting started with WCT Graph Helpers and Controls +title: Getting started with WCT Graph helpers and controls author: shweaver-MSFT -description: Get started using authentication providers and Graph powered helpers from the Windows Community Toolkit. +description: Get started using authentication providers and Graph powered controls and helpers from the Windows Community Toolkit. keywords: uwp, wpf, netstandard, windows, community, toolkit, graph, login, authentication, provider, providers, identity dev_langs: - csharp --- -# Getting Started +# Getting started To get started using Graph data in your application, you'll first need to enable authentication. -> [!IMPORTANT] -> These packages are in preview. To get started using WCT preview packages visit the [WCT Preview Packages wiki page](https://aka.ms/wct/wiki/previewpackages). - ## Set the global authentication provider ### Authenticate with MSAL @@ -37,7 +34,7 @@ Leverage the official Microsoft Authentication Library (MSAL) to enable authenti ProviderManager.Instance.GlobalProvider = new MsalProvider(clientId, scopes); ``` -> Note: You can use the `Scopes` property to preemptively request permissions from the user of your app for data your app needs to access from Microsoft Graph. +> Note: Use the `Scopes` property to preemptively request permissions from the user of your app for data your app needs to access from Microsoft Graph. ### Authenticate with WindowsProvider @@ -93,39 +90,3 @@ ProviderManager.Instance.ProviderStateChanged += (s, e) } } ``` - -### Use the Beta API - -You can use the `ProviderManager.Instance` to listen to changes in authentication status with the `ProviderUpdated` event or get direct access to the [.NET Graph Beta API](https://github.com/microsoftgraph/msgraph-beta-sdk-dotnet) through `ProviderManager.Instance.GlobalProvider.GetBetaClient()`, just be sure to check if the `GlobalProvider` has been set first and its `State` is `SignedIn`: - -```csharp -using CommunityToolkit.Authentication; -using CommunityToolkit.Graph.Extensions; - -public ImageSource GetMyPhoto() -{ - IProvider provider = ProviderManager.Instance.GlobalProvider; - - if (provider?.State == ProviderState.SignedIn) - { - // Get the beta client - GraphServiceClient betaGraphClient = provider.GetBetaClient(); - - try - { - // Make a request to the beta endpoint for the current user's photo. - var photoStream = await betaGraphClient.Me.Photo.Content.Request().GetAsync(); - - using var ras = photoStream.AsRandomAccessStream(); - var bitmap = new BitmapImage(); - await bitmap.SetSourceAsync(ras); - - return bitmap; - } - catch - { - return null; - } - } -} -``` diff --git a/docs/graph/helpers/extensions.md b/docs/graph/helpers/extensions.md index 9bb08f748..f245f668a 100644 --- a/docs/graph/helpers/extensions.md +++ b/docs/graph/helpers/extensions.md @@ -11,9 +11,6 @@ dev_langs: Use toolkit extensions to help you make calls to Graph APIs using the global authentication provider. Available in the `CommunityToolkit.Graph` package, `CommunityToolkit.Graph.Extensions` namespace. -> [!IMPORTANT] -> Windows Community Toolkit - Graph Controls and Helpers packages are in preview. To get started using WCT preview packages visit the [WCT Preview Packages wiki page](https://aka.ms/wct/wiki/previewpackages). - ## Call Microsoft Graph APIs Once authenticated, you can make API calls to Microsoft Graph using a preconfigured `GraphServiceClient` instance. Access to the client is enabled through an extension method on [IProvider](../authentication/custom.md) called, `GetClient()`. @@ -71,7 +68,7 @@ public ImageSource GetMyPhoto() } ``` -## Extension methods +## IProvider extension methods The following extension methods are available on `IProvider` via the `CommunityToolkit.Graph.Extensions` namespace. @@ -79,3 +76,59 @@ The following extension methods are available on `IProvider` via the `CommunityT | -- | -- | -- | -- | | GetClient | | GraphServiceClient | Retrieve pre-configured GraphServiceClient instance for making authenticated Graph calls, using the v1 endpoint. | | GetBetaClient | | GraphServiceClient | Retrieve pre-configured GraphServiceClient instance for making authenticated Graph calls, using the beta endpoint. | + +## Handle Graph requests manually + +Access APIs by managing requests to Microsoft Graph yourself. This is helpful for projects with existing systems for managing web requests, or for keeping package sizes minimal by excluding the Graph SDK. + +To make Graph API calls manually, use the `HttpRequestMessage.AuthenticateAsync()` extension method to authenticate any outgoing requests. + +```csharp +using CommunityToolkit.Authentication; +using CommunityToolkit.Authentication.Extensions; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +private async Task> GetDefaultTaskListAsync() +{ + return await GetResponseAsync>("https://graph.microsoft.com/v1.0/me/todo/lists/tasks/tasks"); +} + +private async Task GetResponseAsync(string requestUri) +{ + // Build the request + var getRequest = new HttpRequestMessage(HttpMethod.Get, requestUri); + + // Authenticate the request using an extension on HttpRequestMessage. + await getRequest.AuthenticateAsync(); + + var httpClient = new HttpClient(); + using (httpClient) + { + // Send the request + var response = await httpClient.SendAsync(getRequest); + + if (response.IsSuccessStatusCode) + { + // Handle the request response + var jsonResponse = await response.Content.ReadAsStringAsync(); + var jObject = JObject.Parse(jsonResponse); + if (jObject.ContainsKey("value")) + { + var result = JsonConvert.DeserializeObject(jObject["value"].ToString()); + return result; + } + } + } + + return default; +} +``` + +## HttpRequestMessage extension methods + +The extension methods are available on `HttpRequestMessage` via the `CommunityToolkit.Authenticaiton.Extensions` namespace. + +| Method | Arguments | Returns | Description | +| -- | -- | -- | -- | +| AuthenticateAsync | | HttpRequestMessage | Authenticate an http request using the current GlobalProvider instance. | diff --git a/docs/graph/helpers/roaming-settings.md b/docs/graph/helpers/roaming-settings.md new file mode 100644 index 000000000..a5250c857 --- /dev/null +++ b/docs/graph/helpers/roaming-settings.md @@ -0,0 +1,164 @@ +--- +title: Roaming settings +author: shweaver-MSFT +description: Roam user settings across experiences using WCT's Graph powered storage helpers. +keywords: uwp, wpf, netstandard, windows, community, toolkit, graph, roaming, settings, storage, files +dev_langs: + - csharp +--- + +# Roaming settings + +Store and roam user settings/files across experiences and devices using Microsoft Graph powered storage helpers. These Graph storage helpers implement the `Microsoft.Toolkit.Helpers.IFileStorageHelper` and `Microsoft.Toolkit.Helpers.ISettingsStorageHelper` interfaces and work well in conjunction with the `Microsoft.Toolkit.Uwp.Helpers.ApplicationDataStorageHelper` for migrating local data to roaming storage locations. + +## OneDriveStorageHelper + +The `OneDriveStorageHelper` is a storage helper for handling files and folders in a user's OneDrive AppSpecial folder. This helper is purposed for storing app specific values and does not support freely navigating the user's OneDrive root folder or other app's settings folders. + +Available in the `CommunityToolkit.Uwp.Graph` package. + +```csharp +var filePath = "TestFile.txt"; +var fileContents = "this is a test"; +var fileContents2 = "this is also a test"; +var storageHelper = await OneDriveStorageHelper.CreateForCurrentUserAsync(); + +// Create a file +await storageHelper.CreateFileAsync(filePath, fileContents); + +// Read a file +var readContents = await storageHelper.ReadFileAsync(filePath); +Assert.AreEqual(fileContents, readContents); + +// Update a file +await storageHelper.CreateFileAsync(filePath, fileContents2); +var readContents2 = await storageHelper.ReadFileAsync(filePath); +Assert.AreEqual(fileContents2, readContents2); + +// Delete a file +var itemDeleted = await storageHelper.TryDeleteItemAsync(filePath); +Assert.IsTrue(itemDeleted); +``` + +Sub-folders are also supported: + +```csharp +var folderName = "TestFolder"; +var subfolderName = "TestSubFolder"; +var subfolderPath = $"{folderName}/{subfolderName}"; +var fileName = "TestFile.txt"; +var filePath = $"{folderName}/{fileName}"; +var fileContents = "this is a test"; +var storageHelper = await OneDriveStorageHelper.CreateForCurrentUserAsync(); + +// Test preparation +await storageHelper.TryDeleteItemAsync(folderName); +await storageHelper.CreateFolderAsync(folderName); + +// Create a subfolder +await storageHelper.CreateFolderAsync(subfolderName, folderName); + +// Create a file in a folder +await storageHelper.CreateFileAsync(filePath, fileContents); + +// Read a file from a folder +var readContents = await storageHelper.ReadFileAsync(filePath); +Assert.AreEqual(fileContents, readContents); + +// List folder contents +var folderItems = await storageHelper.ReadFolderAsync(folderName); +var folderItemsList = folderItems.ToList(); +Assert.AreEqual(2, folderItemsList.Count()); +Assert.AreEqual(subfolderName, folderItemsList[0].Name); +Assert.AreEqual(DirectoryItemType.Folder, folderItemsList[0].ItemType); +Assert.AreEqual(fileName, folderItemsList[1].Name); +Assert.AreEqual(DirectoryItemType.File, folderItemsList[1].ItemType); + +// Delete a subfolder +var itemDeleted = await storageHelper.TryDeleteItemAsync(subfolderPath); +Assert.IsTrue(itemDeleted); +``` + +## UserExtensionStorageHelper + +The `UserExtensionStorageHelper` is a storage helper that leverages open extensions on the Graph User entity to store data. Use this helper for storing user specific settings as key-value-pairs. + +Available in the `CommunityToolkit.Uwp.Graph` package. + +```csharp +// Create a new storage helper for the current user. +var storageHelper = await UserExtensionStorageHelper.CreateForCurrentUserAsync("my-storage-extension-id"); + +// Save a value +storageHelper["PreferredTheme"] = "Dark"; + +// Sync with Graph to update the remote. +await storageHelper.Sync(); +``` + +### Syncing with Graph + +The `UserExtensionStorageHelper` uses synchronous methods to interop and does not automatically sync data back to Graph. Use the `Sync()` method to push changes up to Graph and retrieve any new settings. + +Common sync opportunities: + +1. On application startup, when ready to fetch values and hydrate the cache. +1. On application suspend/resume. +1. After changing one or more settings values. + +There is a known limitation with open extensions that does not allow deletion of a specific key. We suggest using a unique value to represent when a key has been deleted. To truly remove keys, the entire extension must be cleared and synced to delete the extension, then rehydrated with values and synced again. + +#### Sample 1. Set a default value + +```csharp +// Create a new storage helper for the current user. +var storageHelper = await UserExtensionStorageHelper.CreateForCurrentUserAsync("my-storage-extension-id"); + +// Individual key deletion is not supported by open extensions. +// As a workaround, save a unique value like "KEY_DELETED" on deleted keys to pseudo remove them. +storageHelper["PreferredTheme"] = "KEY_DELETED"; + +// Check for a preferred theme, if not set the default. +if (!storageHelper.TryRead("PreferredTheme", out string preferredTheme) || preferredTheme == "KEY_DELETED") +{ + // Set the default theme. + preferredTheme = "Light"; + + // Save a value to the storage helper cache. + // Changes must be explicitly synced. + storageHelper["preferredTheme"] = preferredTheme; + + // Sync with Graph push changes back up. + await storageHelper.Sync(); +} +``` + +#### Sample 2. Delete a key + +```csharp +// Create a new storage helper for the current user. +var storageHelper = await UserExtensionStorageHelper.CreateForCurrentUserAsync("my-storage-extension-id"); + +// Sync to hydrate. +await storageHelper.Sync(); + +// Get the cache and remove the target item. +Dictionary cache = storageHelper.Cache.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); +cache.Remove("PreferredTheme"); + +// Call clear to mark the extension ready for deletion/recreation +storageHelper.Clear(); + +// Reapply the cached values +foreach (var setting in cache) +{ + storageHelper[setting.Key] = setting.Value; +} + +// Sync deletion to Graph and preserve other settings values. +await storageHelper.Sync(); +``` + +## Related Topics + +* [Add custom data to users using open extensions](/graph/extensibility-open-users) diff --git a/docs/graph/overview.md b/docs/graph/overview.md index f7b788d62..1d65cd5a0 100644 --- a/docs/graph/overview.md +++ b/docs/graph/overview.md @@ -1,5 +1,5 @@ --- -title: Windows Community Toolkit - Graph Helpers and Controls +title: Windows Community Toolkit - Authentication and Graph author: shweaver-MSFT description: Authentication providers and Graph powered helpers that make it easy to work with Microsoft Graph APIs. keywords: uwp, wpf, netstandard, windows, community, toolkit, graph, login, authentication, provider, providers, identity @@ -7,24 +7,13 @@ dev_langs: - csharp --- -# Windows Community Toolkit - Graph Helpers and Controls +# Windows Community Toolkit - Authentication and Graph -The Graph helpers and controls are a sub-project of the [Windows Community Toolkit](https://aka.ms/wct) focused on [Microsoft Graph](https://developer.microsoft.com/en-us/graph/) and providing a set of Authentication providers and Graph powered Helpers/Controls that make it easy to work with Microsoft Graph APIs. +The authentication and Graph helpers and controls are a part of the [Windows Community Toolkit](https://aka.ms/wct), focused on enabling quick and easy Windows authentication and [Microsoft Graph](https://developer.microsoft.com/en-us/graph/) powered experiences. These controls and helpers make it easy to get users authenticated and start calling Microsoft Graph APIs! -Note: This new library replaces the `Microsoft.Toolkit.Uwp.UI.Controls.Graph` package; however, it is not backwards compatible nor does it provide all the same features at this time. +> Note: This new library replaces the `Microsoft.Toolkit.Uwp.UI.Controls.Graph` package; however, it is not backwards compatible nor does it provide all the same features at this time. -If you need similar controls for the Web, please use the [Microsoft Graph Toolkit](https://aka.ms/mgt). - -## What's new? - -We've overhauled our approach and introduced some big improvements: - -- The new WindowsProvider enables basic consumer login without AAD configuration 🎊 -- Authentication packages are now split per provider 🎉 -- Access to the GraphServiceClient now lives in a separate package. This means no dependency on the Graph SDK for simple auth scenarios and apps that perform Graph requests manually (sans SDK) 🥳 -- Removed Beta Graph SDK, but enabled access with V1 SDK types. This is so our controls and helpers can be based on the stable Graph endpoint, while also allowing for requests to the beta endpoint in some circumstances (Such as retrieving a user's photo) 🎈 - -For more info on our roadmap, check out the current [Release Plan](https://github.com/windows-toolkit/Graph-Controls/issues/81) +If you need similar controls for the web, check out the [Microsoft Graph Toolkit](https://aka.ms/mgt). ## Supported SDKs @@ -33,23 +22,27 @@ For more info on our roadmap, check out the current [Release Plan](https://githu | `CommunityToolkit.Authentication` | NetStandard 2.0 | | `CommunityToolkit.Authentication.Msal` | NetStandard 2.0 | | `CommunityToolkit.Authentication.Uwp` | UWP Windows 10 17134 | -| `CommunityTookit.Graph` | NetStandard 2.0 | +| `CommunityToolkit.Graph` | NetStandard 2.0 | | `CommunityToolkit.Graph.Uwp` | UWP Windows 10 17763 | -## Getting Started +## Getting started Check out the [Getting Started](./getting-started.md) guide for details on how to get authenticated and start calling Graph APIs. ## Learn More -### Authentication Providers +### Authentication providers Hook into a lightweight framework for authenticating users and responding to login state changes: [Authentication Providers Overview](./authentication/overview.md) -### Graph Helpers +### Extensions See [Microsoft Graph Extensions](./helpers/extensions.md) to learn how to get access to a preconfigured GraphServiceClient and make adhoc API calls using the Graph SDK. -### Graph Controls +### Roaming settings + +Roam settings across experiences with the Graph using [Graph powered storage helpers](./helpers/roaming-settings.md). Store simple settings with open extensions on the Graph User or try the `OneDriveStorageHelper` for roaming files via OneDrive. + +### XAML controls -Build Graph experiences with XAML controls and helpers made for UWP, such as [LoginButton](./controls/LoginButton.md) or [PersonView](./controls/PersonView.md). +Build Graph experiences with XAML controls made for UWP, such as [LoginButton](./controls/LoginButton.md) or [PersonView](./controls/PersonView.md). diff --git a/docs/toc.md b/docs/toc.md index 34a87e114..4621ec268 100644 --- a/docs/toc.md +++ b/docs/toc.md @@ -95,17 +95,17 @@ ### [Microsoft Graph Extensions](graph/helpers/extensions.md) - +### [Roaming Settings](graph/helpers/roaming-settings.md) ## Controls - +### [GraphPresenter (Experimental)](graph/controls/GraphPresenter.md) -### [LoginButton (Preview)](graph/controls/LoginButton.md) +### [LoginButton](graph/controls/LoginButton.md) -### [PersonView (Preview)](graph/controls/PersonView.md) +### [PeoplePicker](graph/controls/PeoplePicker.md) -### [PeoplePicker (Preview)](graph/controls/PeoplePicker.md) +### [PersonView](graph/controls/PersonView.md) # WinUI 3