SharePoint Framework (SPFx): Using the new Microsoft Graph client from an application extension

Using the Microsoft Graph client from an Application Customizer Extension

In this post I will show you how to use the Microsoft Graph client from within an application extension. We will show the latest message from group conversations within an Office 365 group inside the header placeholder of it's SharePoint site. All these features are currently under preview. Documentation is available here: Release Notes Extensions Dev Preview Drop 1.

Start with a new project, using the Yeoman generator for SharePoint. Run the following from your command line tool:

cd c:\
md demo_graphextension
cd .\demo_graphextension\
yo @microsoft/sharepoint

Provide the wizard with the following details:

     _-----_
    |       |    .--------------------------.
    |--(o)--|    |      Welcome to the      |
   `---------´   |  SharePoint Client-side  |
    ( _´U`_ )    |    Solution Generator    |
    /___A___\    '--------------------------'
     |  ~  |
   __'.___.'__
 ´   `  |° ´ Y `

Let's create a new SharePoint solution.
? What is your solution name? demo-graphextension
? Which type of client-side component to create? Extension (Preview)
? Which type of client-side extension to create? Application Customizer (Preview)
? What is your Application Customizer (Preview) name? GroupConvNotifier
? What is your Application Customizer (Preview) description? ""

Let's first verify the extension actually works. Preview you know ;).

First run this command to make the debug files available on localhost:

gulp serve --nobrowser

To debug/test the extension we will have to use the modern UI in an actual SharePoint site. We will need the generated extension ID, so grab it from GroupConvNotifierApplicationCustomizer.manifest.json. Open one of your SharePoint Online sites and add the following to the url, replacing the id with the one you just copied:

?loadSPFX=true&debugManifestsFile=https://localhost:4321/temp/manifests.js&customActions={"6136b9d4-dd9e-45c2-81cc-f4ec789bb53c":{"location":"ClientSideExtension.ApplicationCustomizer"}}

Confirm the load of the debug scripts and verify you get the following result: 



Let's now start with the code for our extension.

Getting the data

We will start with a service that will allow us to grab the latest conversation data from the group we are currently in. Add a folder services to the src folder. In there, add a file MSGraphService.ts and add a class.

export default class MSGraphService {

}

The first thing we will need is the current group id. For this we will need the context from the application customizer. We will pass the context into the constructor. The type ApplicationCustomizerContext you can find if you look at the BaseApplicationCustomizer class your Extension inherits from.

import the BaseApplicationCustomizer type at the top of the MSGraphService.ts file

import { ApplicationCustomizerContext } from "@microsoft/sp-application-base";

Inside the class, create a private field for the group id and set it from the constructor.

private _groupId = null;

constructor(public context:ApplicationCustomizerContext){
    this._groupId = this.context.pageContext.legacyPageContext.groupId;
}

Now that we have the context and the group id, we can get some actual Graph data. To the context object, Microsoft has now added the graphHttpClient object, which we can use to query for group data and reports. This will be extended in the future. Before, we had to use nasty solutions with popup's and/or iframes to get Microsoft Graph data!!

First, let's create a data structure that will be able to store the objects comming from Graph. Add a new folder interfaces to the src folder. In the interfaces folder, create a file IThread.ts. We will add two interfaces: one for the thread object and one for it's posts.

export interface IThread{
    id:string;
    topic:string;
    lastUpdate:Date;
    posts:IPost[];
}

export interface IPost{
    id: string;
    from: string;
    content: string;
}

import the interfaces inside the MSGraphService.ts file

import { IThread } from "../interfaces/IThread";

If you want to verify the data structure first, go to the Microsoft Graph Explorer and test the following queries to get to the query we need:

https://graph.microsoft.com/v1.0/groups/
https://graph.microsoft.com/v1.0/groups('{groupid}')
https://graph.microsoft.com/v1.0/groups('{groupid}')/threads
https://graph.microsoft.com/v1.0/groups('{groupid}')/threads?$select=id,topic,lastDeliveredDateTime&$top=1
https://graph.microsoft.com/v1.0/groups('{groupid}')/threads?$select=id,topic,lastDeliveredDateTime&$top=1&$expand=posts($select=from,body,receivedDateTime)

Notice that it is not possible to only take the latest post in one query, because sort and top is not supported in expand just yet. To avoid two REST calls, I'm grabbing the data in one go and will get the last post from code.

Import the necessary types for the graph client first:

import { GraphHttpClient, GraphClientResponse } from "@microsoft/sp-http";

Implement a method getLatestThreadPost that will get the group's latest conversation thread and it's post data based on our Graph URI.

public getLatestThreadPost():Promise<IThread>{        
    return this.context.graphHttpClient
        .get(`v1.0/groups/${this._groupId}/threads?$select=id,topic,lastDeliveredDateTime&$top=1&$expand=posts($select=from,body,receivedDateTime)`, GraphHttpClient.configurations.v1)
        .then((response:GraphClientResponse) => response.json())
        .then((jsonData) => {
            let tData = jsonData.value[0];
            console.log("Got conversation info");
            console.log(tData);
            return {
                id:tData.id,
                topic:tData.topic,
                lastUpdate:tData.lastDeliveredDateTime,
                posts: tData.posts.map((post) => {
                    return {
                        id : post.id,
                        from : post.from.emailAddress.name,
                        content : post.body.content
                    };
                })
            };
        })
        .catch((error) => {
            console.log("something went wrong");
            console.log(error);
            return null;
        });
}

That's it for the service! Notice that we do not need to generate any access tokens. The authorization is done by the graphHttpClient in the background, so great for us lazy developers! :) For the sake of the demo, we are assuming we have at least one thread and one post, of course we could add some validation here to check this first.

Rendering the data

Now that we have our service ready, let's show the data in the header placeholder of our Office365 Group SharePoint site.

We would like to get the latest data before we actually render the extension. For this we can override the OnInit method of our extension base class. Notice that the OnInit is already overridden in the generated code, so let's modify it. Open GroupConvNotifierApplicationCustomizer.ts.

First, import the necessary types:

import MSGraphService from "../../services/MSGraphService";
import { IThread, IPost } from "../../interfaces/IThread";

Now add two private fields to store our service and the latest data:

private _graphService: MSGraphService;
private _latestThreadData: IThread;

Next, override the OnInit method with the following code:

@override
public onInit(): Promise<void> {
  this._graphService = new MSGraphService(this.context);
  return new Promise<void>((resolve, reject) => {
    this._graphService.getLatestThreadPost().then((postData) => {
      this._latestThreadData = postData;
      resolve();
    });
  });
}

Notice this method will wait for our promise to resolve. The extension will wait for the OnInit method before rendering, ensuring our data is loaded. If you want to test the data load, add the following line to the onRender method:

console.log(this._latestThreadData);

Test this by attaching the same query string to the url of your Office365 Group Site. The result, if you open up your console, should look like this: 


To render the data, we will write a method renderHeader inside the GroupConvNotifierApplicationCustomizer class. Add the PlaceHolder type as an import:

import {
  BaseApplicationCustomizer,
  Placeholder
} from '@microsoft/sp-application-base';

First, let's add a private field for the Header placeholder to the class:

private _headerPlaceholder: Placeholder;

Change the onRender method to the following:

@override
public onRender(): void {
  console.log(this._latestThreadData);
  this.renderHeader();
}

Implement the renderHeader method as follows:

private renderHeader(): void {
  console.log('Rendering header!');
  // Handling the header placeholder
  if (!this._headerPlaceholder) {
    this._headerPlaceholder = this.context.placeholders.tryAttach(
      'PageHeader',
      {
        onDispose: this._onDispose
      }
    );

    // The extension should not assume that the expected placeholder is available.
    if (!this._headerPlaceholder) {
      console.error('The expected placeholder (PageHeader) was not found.');
      return;
    }

    if (this._latestThreadData) {
      let lastPost: IPost = this._latestThreadData.posts[this._latestThreadData.posts.length - 1];

      if (this._headerPlaceholder.domElement) {
        this._headerPlaceholder.domElement.innerHTML = `
            <div class="${styles.app}">
              <div class="ms-bgColor-themeTertiary ms-fontColor-white ${styles.header}">
                <i class="ms-Icon ms-Icon--Info"></i>
                &nbsp;${this._latestThreadData.topic}
                &nbsp;<i class="ms-Icon ms-Icon--Contact"></i>
                &nbsp;${lastPost.from}
                &nbsp;<i class="ms-Icon ms-Icon--Message"></i>
                &nbsp;${this.parseContent(lastPost.content)}
              </div>
            </div>`;
      }
    }
  }
}

The onDispose is required when attaching to a placeholder, so implement it:

private _onDispose(): void {
  console.log('Disposed header.');
}

Notice also that for the content of the post, which is typically HTML, we use a method parseContent. This method will strip the HTML tags out of the text and limit the maximum length of the content to 200. Implement it like this:

private parseContent(content:string):string{
    let regex = /(<([^>]+)>)/ig;
    content = content.replace(regex, "");
    if(content.length > 200) content = content.slice(0,200);
    return content;
}

As a final step, we will have to implement the styling used in our extension!
Most of the classes used are Office-UI-Fabric css classes, but some are custom. For these, create a new file GroupConvNotifier.module.scss inside the groupConvNotifier folder and add the following content:

.app {
  .header {
    height:40px; 
    text-align:center; 
    line-height:2.5; 
    font-weight:bold;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

import the styles at the top of the file:

import styles from './GroupConvNotifier.module.scss';


That's it! Now test again and check out that magnificent chat message inside the header!