In this lab, you will walk through building a web user interface with Office UI Fabric components and invoking Office 365 pickers for interacting with data from the Microsoft Graph.
- Exercise 1: Using Office 365 Pickers
- Exercise 2: Using Office UI Fabric Cards
- Exercise 3: Render an Adaptive Card with data from Microsoft Graph
- Office 365 tenancy
- If you do not have one, you obtain one (for free) by signing up to the Office 365 Developer Program.
- Visual Studio 2017
- .NET Core 2.2 SDK
- NodeJS
- Long Term Support (LTS) version
Configure Visual Studio to use the NodeJS version you installed instead of the version included in the Visual Studio install:
- Select Tools > Options.
- Expand Projects and Solutions > Web Package Management.
- Select on External Web Tools.
- Select the entry $(PATH).
- Select the up arrow to make this entry first in the list.
Install NPM task runner
In this exercise, you will extend an ASP.NET Core application to use pickers provided by Office 365 services.
To enable an application to call the Microsoft Graph, an application registration is required. This lab uses the Azure Active Directory v2.0 endpoint.
-
Open a browser and navigate to the Azure Active Directory admin center (https://aad.portal.azure.com). Login using a personal account (aka: Microsoft Account) or Work or School Account.
-
Select Azure Active Directory in the left-hand navigation, then select App registrations under Manage.
-
Select New registration. On the Register an application page, set the values as follows.
- Set Name to Graph Smart UI Lab.
- Set Supported account types to Accounts in any organizational directory and personal Microsoft accounts.
- Under Redirect URI, set the first drop-down to Web and set the value to https://localhost:44395/signin-oidc.
-
Save your settings by selecting Register.
-
On the Graph Smart UI Lab page, copy the value of the Application (client) ID and the Directory (tenant) ID and save them, you will need them in the next steps.
-
Select Authentication under Manage. In the Redirect URIs section, add 2 more redirect URIs with the following values:
- Type: Web, Redirect URI: https://localhost:44395/OneDriveFilePickerCallback.html
- Type: Web, Redirect URI: https://localhost:44395/Account/AADTenantConnected
-
In the Advanced settings section, locate Implicit grant and enable Access tokens and ID tokens, then choose Save.
-
Select Certificates & secrets under Manage. Select the New client secret button. Enter a value in Description and select one of the options for Expires and choose Add.
-
Copy the client secret value before you leave this page. You will need it in the next step.
Important: This client secret is never shown again, so make sure you copy it now.
-
Select API permissions under Manage. Choose Add a permission.
-
Select Microsoft Graph, then Delegated permissions.
-
In the Select permissions section, scroll down and select the following permissions:
- Directory.Read.All
- Group.Read.All
-
Select Add permissions.
-
Open the starter application. The started application is a Visual Studio solution that can be found at LabFiles\StarterProject\GraphUI.sln.
-
Open the appSettings.json file.
-
Update the following properties, specifying the values from the app registration process.
"Domain": "[yourdomain.onmicrosoft.com]", "TenantId": "[your-tenant-id]", "ClientId": "[your-client-id]", "ClientSecret": "[your-client-secret]",
-
Verify in the project properties, debug settings that SSL is enabled and that the url matches the one that you entered as part of the redirect url in the app registration. The url should also match the BaseUrl specified in the appSettings.json file.
"BaseUrl": "https://localhost:44395"
-
Press F5 to run the application.
-
When prompted, log in with your Work or School account and grant consent to the application.
-
The application will load the Permission Required page. Reading Groups from the tenant requires administrative consent, and must be performed via a specific endpoint. Select the Connect your tenant link.
-
Log in with an account that has administrative privileges in the tenant.
-
On the administrative consent dialog, select Accept.
-
The app will then display the Home page.
-
Stop debugging
OneDrive provides File pickers for Android and JavaScript. This lab uses the JavaScript version. Additional information is available on the reference page.
The File picker requires a control for the user to invoke the picker, and a callback page to receive the requested information from OneDrive. Create the callback page by performing these steps:
-
In Solution Explorer, right-click on the wwwroot folder and choose Add > New Item...
-
Select the HTML Page template. Name file OneDriveFilePickerCallback.html.
-
Replace the contents of the file the following statements:
<!DOCTYPE html> <html lang="en"> <script type="text/javascript" src="https://js.live.net/v7.2/OneDrive.js"></script> </html>
-
Save and close the file.
-
Open the file Views\Picker\Index.cshtml
-
Notice that line 16 contains a button with a JavaScript handler for the
onClick()event. -
At the bottom of the page, approx line 33, is a Razor section named scripts. Add the following tag inside the scripts section to load the File picker control.
<script type="text/javascript" src="https://js.live.net/v7.2/OneDrive.js"></script>
-
Add the following code after the OneDrive.js script tag. (The code is available in the LabFiles\Pickers\OneDriveFilePicker.js file):
<script type="text/javascript"> function launchOneDrivePicker() { var ClientID = "@Options.Value.ClientId"; var odOptions = { clientId: ClientID, action: "query", multiSelect: false, advanced: { queryParameters: "select=id,name,size,file,folder,photo,@@microsoft.graph.downloadUrl", redirectUri: '@Options.Value.BaseUrl/OneDriveFilePickerCallback.html' }, success: function (files) { var data = files; var fileName = data.value[0]["name"]; var filePath = data.value[0]["@@microsoft.graph.downloadUrl"]; document.getElementById('selectedFileName').innerHTML = '<strong>' + fileName + '</strong>'; document.getElementById('selectedFileUrl').innerText = filePath.substr(0, filePath.indexOf('tempauth') + 15) + '...'; }, cancel: function () { /* cancel handler */ }, error: function (e) { /* error handler */ alert(e); } }; OneDrive.open(odOptions); } </script>
-
Run the application by pressing F5.
-
Select on the Pickers link in the left-side navigation.
-
Select the Select from OneDrive button.
-
The File picker has a set of permissions that it requires. The app registration performed in this lab does not include those permissions, so you will need to log in and grant consent to your OneDrive for Business library.
-
After consenting, the File picker renders in dialog window.
-
Select a file and select Open.
-
The File picker will close the dialog and call the
successcallback, passing the requested information. -
Close the browser to stop the debugging session.
Office UI Fabric provides a People Picker component written in React. For detailed information about the components, refer to the Office UI Fabric documentation. The starter project in the lab is pre-configured to use React, following the principles of the create-react-app utility. In the lab, you will extend the application to use the sample people picker from Office UI Fabric.
-
In Solution Explorer, right-select on the Components folder and choose Add > New Item...
-
Select the TypeScript JSX File template. Name file PeoplePickerExampleData.tsx.
-
Replace the contents of the template with the code from the file LabFiles\Pickers\PeoplePickerExampleData.tsx.
-
In Solution Explorer, right-select on the Components folder and choose Add > New Item...
-
Select the TypeScript JSX File template. Name file PeoplePicker.tsx.
-
Replace the contents of the template with the code from the file LabFiles\Pickers\PeoplePicker.tsx.
-
Open the file Views\Picker\Index.cshtml.
-
Notice around line 25 contains a
<div>with the idreact-peoplePicker. This is the location in the page in which the control will be rendered. -
Inside the scripts section, add the following line right before the
</script>tag:App.RenderPeoplePicker();
-
The
RenderPeoplePicker()method is defined in the Components\boot.tsx file. It needs to be updated now:-
Un-comment the following
importstatement at the top of the file for the PeoplePicker://import { PeoplePicker } from './PeoplePicker'; -
Add the following code to the
RenderPeoplePicker()method:
ReactDOM.render( <PeoplePicker></PeoplePicker>, document.getElementById('react-peoplePicker') );
Note: The webpack configuration specifies that the TypeScript in the project is injected into pages as a library object named
App. -
-
Run the application by pressing F5.
-
Select on the Pickers link in the left-side navigation.
-
Notice the People Picker section is now working and displaying a people picker:
-
Close the browser to stop the debugging session.
This exercise will add various cards from Office UI Fabric to the application. The application reads Group information and should be run as the tenant administrator.
The application has a banner at the top of each page. In this step, add a Persona card to the banner showing the current logged-in user. The complete Banner class can be found in the file LabFiles\Cards\Banner.tsx file.
-
In Visual Studio, open the file Components\banner.tsx.
-
At the top of the file, add the following import statement:
import { Persona, PersonaInitialsColor, IPersonaStyles, IPersonaStyleProps, PersonaSize } from 'office-ui-fabric-react/lib/Persona';
-
In the banner.tsx file, locate the
Bannerclass. The class has a constructor and a method namedrender(). Add the following as a new method in theBannerclass.private getPersonaStyles(props: IPersonaStyleProps): Partial<IPersonaStyles> { return { root: { color: ColorClassNames.white, float: "right" }, textContent: { color: ColorClassNames.white }, primaryText: { color: ColorClassNames.white }, secondaryText: { color: ColorClassNames.white } }; }
-
The name and picture of the current user are written to the page in the _Layouts.cshtml file. Add the following to banner.tsx to create a Persona component with that information. This statement should be the first line of the
render()method, replacing the existing definition of the persona variable.const persona = (this.props.name) ? ( <Persona size={PersonaSize.size40} primaryText={this.props.name} secondaryText={this.props.email} imageUrl={this.props.imageUrl} getStyles={this.getPersonaStyles} /> ) : ( <span> </span> );
-
Save all files and press F5 to run the project. After login, the home page will show the current user at the top right of the screen.
The application has a page to display all Office 365 groups in the tenant. Selecting a group opens a Panel with the group title.
-
With the project still running, select the Groups link in the left-hand navigation. From the list of Groups, select on a group to open the details pane.
In this step, add information about recent group activity using DocumentCards. The complete set of cards for the Group page can be found in the LabFiles\Cards\GroupDetails.tsx file.
-
In Visual Studio, open the file Components\GroupDetails.tsx.
-
At the top of the file, add the following imports:
import { DocumentCard, DocumentCardActions, DocumentCardActivity, DocumentCardLocation, DocumentCardPreview, DocumentCardTitle, DocumentCardLogo, DocumentCardStatus, IDocumentCardPreviewProps, IDocumentCardLogoProps, DocumentCardType, IDocumentCardPreviewImage } from 'office-ui-fabric-react/lib/DocumentCard'; import { ImageFit } from 'office-ui-fabric-react/lib/Image'; import { Icon, IconType, IIconProps } from 'office-ui-fabric-react/lib/Icon'; import { initializeFileTypeIcons, getFileTypeIconProps, FileIconType } from '@uifabric/file-type-icons'; import { GlobalSettings } from 'office-ui-fabric-react/lib/Utilities'; import GroupList = require("./GroupList"); import Conversation = GroupList.Conversation; initializeFileTypeIcons();
-
In the
GroupDetailsclass, create the following method to render the most-recent conversation using a DocumentCard.private getMailboxActivity(latestConversation: Conversation, mailboxWebUrl: string): JSX.Element { let mailboxActivity = null; if (latestConversation) { let activityMessage = `Sent ${latestConversation.lastDelivered}`; let people = []; for (var i = 0; i < latestConversation.uniqueSenders.length; i++) { people.push({ name: latestConversation.uniqueSenders[i] }); } mailboxActivity = ( <DocumentCard> <DocumentCardLogo logoIcon='OutlookLogo' /> <DocumentCardTitle title='Latest Conversation' shouldTruncate={true} /> <DocumentCardTitle title={latestConversation.topic} shouldTruncate={true} showAsSecondaryTitle={true} /> <DocumentCardActivity activity={activityMessage} people={people} /> <DocumentCardLocation location='View Inbox' locationHref={mailboxWebUrl} ariaLabel='Group inbox' /> </DocumentCard> ); } return mailboxActivity; }
-
In the
render()method of theGroupDetailsclass, replace thereturnstatement with the following:return ( <div> <h2>{this.props.group.name}</h2> { this.getMailboxActivity(this.props.group.latestConversation, this.props.group.mailboxWebUrl) } </div> );
-
Save the file.
-
Refresh the Groups page and select on a group. The detail panel will include details about the latest conversation.
-
Return to Visual Studio. In the
GroupDetailsclass, create the following method to render the most-recently updated documents in the Group library.private getLibraryActivity(driveRecentItems: DriveItem[]): JSX.Element { if (driveRecentItems == null || driveRecentItems.length == 0) { return null; } let libraryActivity: JSX.Element = null; let globalSettings = (window as any).__globalSettings__; let recentDocs: IDocumentCardPreviewProps = { getOverflowDocumentCountText: (overflowCount: number) => `+${overflowCount} more`, previewImages: [ ] }; let documentCardDocTitle: JSX.Element = null; if (driveRecentItems.length == 1) { const doc = driveRecentItems[0]; let iconProps: IIconProps = this.getIconProps((doc.fileType)); let previewImage: IDocumentCardPreviewImage = { name: doc.title, url: doc.webUrl, previewImageSrc: doc.thumbnailUrl, iconSrc: globalSettings.icons[iconProps.iconName].code.props.src // hack for file-type-icons }; recentDocs.previewImages.push(previewImage); documentCardDocTitle = <DocumentCardTitle title={doc.title} shouldTruncate={true} />; } else { let docs = this.props.group.driveRecentItems; for (var i = 0; i < docs.length; i++) { let iconProps: IIconProps = {}; switch (docs[i].fileType) { case "folder": iconProps = getFileTypeIconProps({ type: FileIconType.folder, size: 16 }); break; default: iconProps = getFileTypeIconProps({ extension: docs[i].fileType, size: 16 }); break; } let previewImage: IDocumentCardPreviewImage = { name: docs[i].title, url: docs[i].webUrl, iconSrc: globalSettings.icons[iconProps.iconName].code.props.src // hack for file-type-icons }; recentDocs.previewImages.push(previewImage); } } libraryActivity = ( <DocumentCard> <DocumentCardLogo logoIcon='OneDrive' /> <DocumentCardTitle title='Latest Documents' /> <DocumentCardPreview previewImages={recentDocs.previewImages} getOverflowDocumentCountText={recentDocs.getOverflowDocumentCountText} /> {documentCardDocTitle} <DocumentCardLocation location='View Library' locationHref={this.props.group.driveWebUrl} /> </DocumentCard> ); return libraryActivity; } private getIconProps(fileSuffix: string): IIconProps { let iconProps: IIconProps = {}; switch (fileSuffix) { case "folder": iconProps = getFileTypeIconProps({ type: FileIconType.folder, size: 16 }); break; default: iconProps = getFileTypeIconProps({ extension: fileSuffix, size: 16 }); break; } return iconProps; }
-
Replace the
render()method with the following.public render() { const group = this.props.group; const libraryActivity: JSX.Element = this.getLibraryActivity(this.props.group.driveRecentItems); const mailboxActivity: JSX.Element = this.getMailboxActivity(this.props.group.latestConversation, this.props.group.mailboxWebUrl); const activity = (libraryActivity || mailboxActivity) ? ( <div> <h2>Group Activity</h2> {libraryActivity} <br /> {mailboxActivity} </div> ) : (null); return ( <div> <h2>{group.name}</h2> { activity } </div> ); }
-
Save the file.
-
Refresh the Groups page and select on a group. The detail panel will include details about the latest documents in the group library (if any).
This exercise will use an Adaptive Card to render Group information.
-
If the Visual Studio debugger is running, stop it.
-
Open the file Controllers\GroupDataController.cs.
-
Locate the
CreateGroupCard()method. It is currently a stub returning an empty card. -
Replace the contents of the
CreateGroupCardmethod with the following. (The fullCreateGroupCard()method is in the file LabFiles\Cards\Groups\CreateGroupCard.cs.).private AdaptiveCard CreateGroupCard(Models.GroupModel group) { AdaptiveCard groupCard = new AdaptiveCard("1.0") { Type = "AdaptiveCard" }; AdaptiveContainer infoContainer = new AdaptiveContainer(); AdaptiveColumnSet infoColSet = new AdaptiveColumnSet(); bool noPic = String.IsNullOrEmpty(group.Thumbnail); if (!noPic) { AdaptiveColumn picCol = new AdaptiveColumn() {Width = AdaptiveColumnWidth.Auto}; picCol.Items.Add(new AdaptiveImage() { Url = new Uri(group.Thumbnail), Size = AdaptiveImageSize.Small, Style = AdaptiveImageStyle.Default }); infoColSet.Columns.Add(picCol); } AdaptiveColumn txtCol = new AdaptiveColumn() {Width = AdaptiveColumnWidth.Stretch}; var titleBlock = new AdaptiveTextBlock() {Text = NullSafeString(group.Name), Weight = AdaptiveTextWeight.Bolder}; if (noPic) { titleBlock.Size = AdaptiveTextSize.Large; } txtCol.Items.Add(titleBlock); txtCol.Items.Add(new AdaptiveTextBlock() { Text = NullSafeString(group.Description), Spacing = AdaptiveSpacing.None, IsSubtle = true }); infoColSet.Columns.Add(txtCol); infoContainer.Items.Add(infoColSet); groupCard.Body.Add(infoContainer); AdaptiveContainer factContainer = new AdaptiveContainer(); AdaptiveFactSet factSet = new AdaptiveFactSet(); if (!String.IsNullOrEmpty(group.Classification)) { factSet.Facts.Add(new AdaptiveFact() { Title = "Classification", Value = group.Classification }); } if (!String.IsNullOrEmpty(group.Visibility)) { factSet.Facts.Add(new AdaptiveFact() { Title = "Visibility", Value = group.Visibility }); } if (!String.IsNullOrEmpty(group.GroupType)) { factSet.Facts.Add(new AdaptiveFact() { Title = "Type", Value = NullSafeString(group.GroupType) }); } if (group.CreatedDateTime.HasValue) { factSet.Facts.Add(new AdaptiveFact() { Title = "Created", Value = $"{{{{DATE({group.CreatedDateTime.Value.UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ssZ")},SHORT)}}}}" }); } if (!String.IsNullOrEmpty(group.Policy) && group.RenewedDateTime.HasValue) { factSet.Facts.Add(new AdaptiveFact() { Title = "Policy", Value = NullSafeString(group.Policy) }); factSet.Facts.Add(new AdaptiveFact() { Title = "Renewed", Value = $"{{{{DATE({group.RenewedDateTime.Value.UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ssZ")},SHORT)}}}}" }); } factContainer.Items.Add(factSet); groupCard.Body.Add(factContainer); return groupCard; }
-
In Solution Explorer, right-select on the Components folder and choose Add > New Item...
-
Select the SCSS Style Sheet (SASS) template. Name file GroupCard.scss.
-
Replace the contents of the template with the code from the file LabFiles\Cards\Groups\GroupCard.scss.
-
In Solution Explorer, right-select on the Components folder and choose Add > New Item...
-
Select the TypeScript JSX File template. Name file GroupCard.tsx.
-
Replace the contents of the template with the following. (The complete code for the
GroupCardclass is in the file LabFiles\Cards\Groups\GroupCard.tsx.)import * as React from 'react'; import * as AdaptiveCards from "adaptivecards"; import { IGroupDetailsProps } from './GroupDetails'; import './GroupCard.scss'; export class GroupCard extends React.Component<IGroupDetailsProps, any> { constructor(props: IGroupDetailsProps) { super(props); } render() { let card = ""; if (this.props.group.infoCard) { card = this.renderAdaptiveCard(this.props.group.infoCard); } return <div className="groupCard" dangerouslySetInnerHTML={{ __html: card }} > </div> } private renderAdaptiveCard(card: any) { // Create an AdaptiveCard instance var adaptiveCard = new AdaptiveCards.AdaptiveCard(); // Set its hostConfig property unless you want to use the default Host Config // Host Config defines the style and behavior of a card adaptiveCard.hostConfig = new AdaptiveCards.HostConfig({ fontFamily: "Segoe UI, Helvetica Neue, sans-serif" }); // Parse the card payload adaptiveCard.parse(card); // Render the card to an HTML element: var renderedCard = adaptiveCard.render(); return renderedCard.innerHTML; } }
-
Open the file Components\GroupDetails.tsx
-
At the top of the file, add the following import statement.
import { GroupCard } from './GroupCard';
-
In the
rendermethod, locate thereturnstatement. Modify the return statement to include the GroupCard.return ( <div> <h2>Group Information</h2> <DocumentCard> <GroupCard group={this.props.group} /> </DocumentCard> {activity} </div> );
-
Save all files.
-
Press F5 to run the application. Navigate to the Groups page and select on a group. The detail panel will include details about group in addition to the activity.
















