Build seamless automations to boost productivity with Microsoft Graph, Azure Event Hubs and Functions

Every day millions of people spend their precious time in productivity tools. What if you use data and intelligence behind the Microsoft applications (Microsoft Teams, Outlook, and many other Office apps) to build seemsless automations and custom apps to boost productivity? In this post, we’ll build a seamsless onboarding experience to new employees joining a company with the power of Microsoft Graph.

📝 What We’ll Cover

  • ✨ The power of Microsoft Graph
  • 🖇️ How do Microsoft Graph and Event Hubs work together?
  • ⚒️ Exercise: Setup Azure Event Hubs and Key Vault
  • 🪡 Exercise: Subscribe to users resource to receive change notifications by using Azure Functions
  • ♾️ Exercise: Create Onboarding Function
  • 🚀 Debug your onboarding experience
  • 📚 Resources

Following pre-requisites are recommended:

✨ The power of Microsoft Graph

Microsoft Graph is the gateway to data and intelligence in Microsoft 365 platform. Microsoft Graph exploses Rest APIs and client libraries to access data across Microsoft 365 core services such as Calendar, Teams, To Do, Outlook, People, Planner, OneDrive, OneNote and more.

Microsoft Graph Overview

You can build custom experiences by using Microsoft Graph such as automating the onboarding process for new employees. When new employees are created in the Azure Active Directory, they will be automatically added in the Onboarding team on Microsoft Teams.

Solutions Architecture

🖇️ How do Microsoft Graph and Event Hubs work together?

Microsoft Graph uses webhook mechanism to track changes in resources and deliver change notifications to the clients. As an example to the Microsoft Graph Change Notifications, you can receive change notifications when:

  • a new task is added in the to-do list
  • a user changes the presence status from busy to available
  • an event is deleted/cancelled from the calendar

If you’d like to track a large set of resources in a high frequency, you can use Azure Events Hubs instead of traditional webhooks to receive change notifications. Azure Event Hubs is a popular real-time events ingestion and distribution service built for scale.

Microsoft Graph Change Notifications can be also received by using Azure Event Grid that is currently available for Microsoft Partners. Please review the documentation for more information: Partner Events overview for customers – Azure Event Grid

⚒️ Exercise: Setup Azure Event Hubs and Key Vault

To get Microsoft Graph Change Notifications delivered to Azure Event Hubs, we’ll have to setup Azure Event Hubs and Azure Key Vault. We’ll use Azure Key Vault to access to Event Hubs connection string.

1️⃣ Create Azure Event Hubs

  1. Go to Azure Portal and select Create a resource, type Event Hubs and select click Create.
  2. Fill in the Event Hubs namespace creation details, and then click Create.
  3. Go to the newly created Event Hubs namespace page, select Event Hubs tab from the left pane and + Event Hub:
    • Name your Event Hub as Event Hub
    • Click Create.
  4. Click the name of the Event Hub, and then select Shared access policies and + Add to add a new policy:
    • Give a name to the policy
    • Check Send and Listen
    • Click Create.
  5. After the policy has been created, click the name of the policy to open the details panel, and then copy the Connection string-primary key value. Write it down; you’ll need it for the next step.
  6. Go to Consumer groups tab in the left pane and select + Consumer group, give a name for your consumer group as onboarding and select Create.

2️⃣ Create Azure Key Vault

  1. Go to Azure Portal and select Create a resource, type Key Vault and select Create.
  2. Fill in the Key Vault creation details, and then click Review + Create.
  3. Go to newly created Key Vault and select Secrets tab from the left pane and click + Generate/Import:
    • Give a name to the secret
    • For the value, paste in the connection string you generated at the Event Hubs step
    • Click Create
    • Copy the name of the secret.
  4. Select Access Policies from the left pane and + Add Access Policy:
    • For Secret permissions, select Get
    • For Principal, select Microsoft Graph Change Tracking
    • Click Add.
  5. Select Overview tab from the left pane and copy the Vault URI.

🪡 Exercise: Subscribe to users resource to receive change notifications by using Azure Functions

To start receiving Microsoft Graph Change Notifications, we’ll need to create subscription to the resource that we’d like to track. We’ll use Azure Functions to create subscription.

To create subscription for Microsoft Graph Change Notifications, we’ll need to make a http post request to https://graph.microsoft.com/v1.0/subscriptions. Microsoft Graph requires Azure Active Directory authentication make API calls. First, we’ll need to register an app to Azure Active Directory, and then we will make the Microsoft Graph Subscription API call with Azure Functions.

1️⃣ Create an app in Azure Active Directory

  1. In the Azure Portal, go to Azure Active Directory and select App registrations from the left pane and select + New registration. Fill in the details for the new App registration form as below:
    • Name: Graph Subscription Auth
    • Supported account types: Accounts in any organizational directory (Any Azure AD directory – Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox)
    • Select Register.
  2. Go to newly registered app in Azure Active Directory, select API permissions:
    • Select + Add a permission and Microsoft Graph
    • Select Application permissions and add User.Read.All and TeamMember.ReadWrite.All.
    • Select Grant admin consent for the organization
  3. Select Certificates & secrets tab from the left pane, select + New client secret:
    • Choose desired expiry duration
    • Select Add
    • Copy the value of the secret.
  4. Go to Overview from the left pane, copy Application (client) ID and Directory (tenant) ID.

2️⃣ Create subscription with Azure Functions

  1. Open Visual Studio Code, open the pallete by clicking CTRL + SHIFT + P on Windows or CMD + SHIFT + P on Mac, search for "create function" and choose Azure Functions: Create Function:

    • A window will pop-up with a message "you must have a project open to create function", select Create new project. Create a new folder and select the folder for your project
    • Select JavaScript as a project language
    • Select Timer Trigger as a template for your project’s first function.
    • Name your Timer Trigger as SubscriptionFunction and press enter.
    • Specify schedule as 0 */61 * * * * and press enter
    • Select Open in current window and press enter.
  2. Select Terminal from the menu bar on top and select New Terminal. Run the following commands in the terminal to install the dependencies:

    npm install @azure/identity @microsoft/microsoft-graph-client isomorphic-fetch readline-sync
    
  3. Create a folder under the project and name as Shared.

  4. Create a new file inside the Shared folder, name as dateTimeFormat.js, copy the entire code in dateTimeFormat.js inside your file to define the expiration date of the subscription.

  5. Create a new file inside the Shared folder, name as Graph.js. Add the following authentication code snippet inside the Graph.js:

    const expiry = require('./dateTimeFormat');
    require('isomorphic-fetch');
    const azure = require('@azure/identity');
    const graph = require('@microsoft/microsoft-graph-client');
    const authProviders = require('@microsoft/microsoft-graph-client/authProviders/azureTokenCredentials');
    let _clientSecretCredential = undefined;
    let _appClient = undefined;
    let _expiry = undefined;
    
    function ensureGraphForAppOnlyAuth() {
    if (!_clientSecretCredential) {
        _clientSecretCredential = new azure.ClientSecretCredential(
        '<YOUR-AAD-APP-TENANT-ID>',
        '<YOUR-AAD-APP-CLIENT-ID>',
        '<YOUR-AAD-APP-CLIENT-SECRET>'
        );
    }
    
    if (!_appClient) {
        const authProvider = new authProviders.TokenCredentialAuthenticationProvider(
        _clientSecretCredential, {
            scopes: [ 'https://graph.microsoft.com/.default' ]
        });
    
        _appClient = graph.Client.initWithMiddleware({
        authProvider: authProvider
        });
    }
    }
    

    Replace <YOUR-AAD-APP-TENANT-ID>, <YOUR-AAD-APP-CLIENT-ID> and <YOUR-AAD-APP-CLIENT-SECRET> with the registered app details in the previous step

  6. Add the following function inside Graph.js to make a REST API request to Microsoft Graph /subscriptions endpoint and create a subscription to track new users:

    async function postSubscriptionAsync() {
    ensureGraphForAppOnlyAuth();
    if(!_expiry){
        _expiry = await expiry.getDateTimeAsync();
        }
        const subscription = {
            changeType: 'created, updated',
            notificationUrl: 'EventHub:https://<YOUR-VAULT-URI>/secrets/<YOUR-KEY-VAULT-SECRET-NAME>?tenantId=<YOUR-TENANT-ID>',
            resource: 'users',
            expirationDateTime: _expiry,
            clientState: 'secretClientValue',
            };
        
        return _appClient?.api('/subscriptions')
            .post(subscription);
    }
    module.exports.postSubscriptionAsync = postSubscriptionAsync;
    

    In notificationUrl, make sure to replace <YOUR-VAULT-URI> with the vault uri, <YOUR-KEY-VAULT-SECRET-NAME> with the secret name and <YOUR-TENANT-ID> with the tenant id that you copied from the Key Vault.

  7. Go to SubscriptionFunction > index.js and copy the following references on top of the page:

    require('isomorphic-fetch');
    const graph = require('../Shared/graph');
    
  8. In the index.js, copy the following code snippet inside the function to trigger the subscription every 61 minutes:

        const subscription = await graph.postSubscriptionAsync();
    
  9. Go to local.settings.json, replace the existing code with the code snippet below:

    {
    "IsEncrypted": false,
    "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "node"
    },
    "watchDirectories": [ "Shared" ]
    }
    
  10. For the testing purposes only, go to SubscriptionFunction > function.json and add the following parameter inside the binding:

    "runOnStartup": true
    

    Make sure to remove this parameter for the production.

  11. Run the Microsoft Azure Storage Emulator and run the following command on the Visual Studio Code terminal to test your function:

    func host start
    

When subscription function runs successfully, it will create a subscription for users resource. Azure Event Hubs will receive notifications whenever there is a new user created in Azure Active Directory.

♾️ Exercise: Create Onboarding Function

We’ll create a second function in the project to receive change notifications from Event Hubs when there is a new user created in the Azure Active Directory and add new user in Onboarding team on Microsoft Teams.

  1. Open the patlete on Visual Studio by clicking CTRL + SHIFT + P on Windows or CMD + SHIFT + P on Mac, search for "create function" and choose Azure Functions: Create Function:

    • Select Azure Event Hub trigger as a template for your function
    • Name your Event Hub trigger as OnboardingFunction and press enter
    • Select + Create new local app setting
    • Select your Event Hub settings that you created in the previous steps:
      • Azure subscription
      • Event Hub Namespace
      • Event Hub
      • Event Hub policy
      • Consumer group
    • Press enter.
  2. Go to Shared > Graph.js, add the following parameter on top of the page:

    let _memberId = undefined;
    
  3. Inside Graph.js, copy the following code to automatically add the new user to the Onboarding team on Microsoft Teams:

    async function postTeamsMemberAsync(memberId) {
        ensureGraphForAppOnlyAuth();
        _memberId = memberId;
        const user = 'https://graph.microsoft.com/v1.0/users(\'' + _memberId +'\')';
        const conversationMember = {
            '@odata.type': '#microsoft.graph.aadUserConversationMember',
            roles: ['owner'],
            'user@odata.bind': user
        };
        
        return _appClient?.api('/teams/<YOUR-ONBOARDING-TEAM-ID>/members')
            .post(conversationMember);       
    }
    module.exports.postTeamsMemberAsync = postTeamsMemberAsync;
    

    Make sure to replace <YOUR-ONBOARDING-TEAM-ID> with the team id that you’d like to add your users as a member. You can login to Microsoft Graph Explorer and run my joined teams sample query to view available team ids.

  4. Go to OnboardingFunction > index.js and copy the following references on top of the page:

    const graph = require('../Shared/graph');
    
  5. In the index.js, and replace the code inside the function with the following code snippet:

     eventHubMessages.forEach(async (message, index) => {
        var jsonMessage = JSON.parse(message);
        
        for (let i in jsonMessage.value) {
            var resourceData = jsonMessage.value[i].resourceData;
            const newMemberId = resourceData.id;
            await graph.postTeamsMemberAsync(newMemberId);
        }
    });
    

🚀 Debug your onboarding experience

To debug our onboarding experience, we’ll need run our functions locally and create a new user in Azure Active Directory to see if the new user is added automatically in Microsoft Teams Onboarding team.

  1. Open the terminal in Visual Studio Code and run your functions with the following command:

    func host start
    

    Make sure that Microsoft Azure Storage Emulator is running in the background.

  2. Go to Azure Portal and select Azure Active Directory from the left pane and go to Users. Select + New user and Create new user. Fill in the details as below:

    • User name: JaneDoe
    • Name: Jane Doe

Add new user in Azure Active Directory

  1. When you added Jane Doe as a new user, it should trigger the OnboardingFunction to run.

Once the OnboardingFunction runs successfully, you should be able to see Jane Doe as a member of the Onboarding team on Microsoft Teams! 🥳 New member in the onboarding team

Source code for this solution can be found in the following GitHub Repository: Onboarding-Functions

📚 Resources

Get your To-Do tasks every morning on Microsoft Teams using Azure Logic Apps

I am super excited since Microsoft Graph To Do APIs are introduced at Microsoft Build 2020. We finally have APIs available in public preview on the beta endpoint of Graph.

Just a brief introduction, Microsoft To Do and Planner are the essence of tasks in Microsoft 365. To-Do helps you create a list for anything, from work assignments to school projects to groceries. It is a great tool for your personal use. On the other hand, Planner is the best place to collaborate as a team and keep your team tasks. Tasks come from everywhere, you can keep track of deadlines by adding reminders, due dates, and notes.

Wouldn’t it be nice to receive your list of assigned tasks every morning on Microsoft Teams?

Today, we will build a flow using Azure Logic Apps to automate Microsoft Teams Flow bot for sending To-Do tasks every morning at 9 AM. Here is the steps we will follow:

Logic Apps Flow

Microsoft Graph To-Do APIs in Graph Explorer

To be able to review Microsoft Graph To-Do API queries and responses with your own data, go to Microsoft Graph Explorer and login with your account from the top left corner by clicking Sign in to Graph Explorer.

Then, search for “to do” under Sample queries and select Get my to do task list. This will run the query https://graph.microsoft.com/beta/me/todo/lists and will get all the task lists as a response. Copy one of your preferred task list Id from the response.

To-Do in Graph Explorer

Let’s try to get all the tasks under your preferred task list. Change the query with the following: https://graph.microsoft.com/beta/me/todo/lists/{taskListId}/tasks. Make sure the request is GET and hit Run query. You should be able to see all tasks under the selected list as a response.

Copy this query and save somewhere, we will use this later while creating a custom connector.

To-Do in Graph Explorer

Register your app in Azure Active Directory

Go to Azure Active Directory in Azure Portal. Select App Registrations and choose New registation.

Azure Active Directory App Registration

Enter To-do-flow-app in the Name field. In the Supported account types section, select Accounts in any organizational directory and personal Microsoft accounts. Leave Redirect URI blank and choose Register to continue.

Azure Active Directory App Registration

Go to API permissions from the left hand side menu and select add a permission. Choose Microsoft Graph and Delegated Permissions. Select Task.ReadWrite and click Add permission button.

Azure Active Directory App Registration

Go to Certificates & secrets from the left hand side menu and select New client secret under the Client secrets. Choose expiry time and Add.

Azure Active Directory App Registration

Copy the secret you created and Application Id under the Overview page. Save them somewhere, we will use them while creating a custom connector.

Build Azure Logic Apps Custom Connector to consume To-Do APIs in a flow

Go to Azure Portal and create Logic Apps Custom Connector.

Logic Apps Custom Connector

On the connector configuration, fill the fields as follows:

  • Subscription: Select an Azure subscription
  • Resource Group: Create new resource group
  • Custom connector name: give a name for your custom connector
  • Select the location: Region
  • Location: Select the preferred location

Choose Review + create button to continue.

Logic Apps Custom Connector

When your custom connector is successfully created, select Edit to configure your connector.

Logic Apps Custom Connector

On the connector configuration General page, fill in the fields as follows.

  • Scheme: HTTPS
  • Host: graph.microsoft.com
  • Base URL: /

Choose Security button to continue.

Logic Apps Custom Connector

On the Security page, fill in the fields as follows.

  • Choose what authentication is implemented by your API: OAuth 2.0
  • Identity Provider: Azure Active Directory
  • Client id: the application ID you created in the previous exercise
  • Client secret: the key you created in the previous exercise
  • Login url: https://login.windows.net
  • Tenant ID: common
  • Resource URL: https://graph.microsoft.com (no trailing /)
  • Scope: Leave blank

Choose Definition button to continue.

Logic Apps Custom Connector

On the Definition page, select New Action and fill in the fields as follows.

  • Summary: Get To-Do Tasks
  • Description: Get To-Do Tasks
  • Operation ID: ToDo
  • Visibility: important

Create Request by selecting Import from Sample and fill in the fields as follows.

Select Import.

Logic Apps Custom Connector

Choose Create Connector on the top-right. After the connector has been created, copy the generated Redirect URL from Security page.

Logic Apps Custom Connector

Go back to Azure Active Directory registered app, go to Authentication tab and select Add platform, choose Web.

Logic Apps Custom Connector

Paste the Redirect URI you copied from the custom connector under the Redirect URIs. Select Access tokens and Id tokens. Click Configure to continue.

Logic Apps Custom Connector

Create Logic Apps flow to automate receiving To-Do tasks

Go to Azure Portal and create Logic App.

Logic Apps Flow

On the configuration page, fill the fields as follows:

  • Subscription: Select an Azure subscription
  • Resource Group: Create new resource group
  • Custom connector name: give a name for your logic app
  • Select the location: Region
  • Location: Select the preferred location

Choose Review + create button to continue.

Logic Apps Flow

When your Logic app is successfully created, go to your Logic app and choose Logic app designer. Select Recurrence as a trigger.

Logic Apps Flow

Configure the recurrence as follows:

  • Interval: 1
  • Frequecy: Day
  • Timezone: Select the timezone you prefer
  • Start time: YYYY-MM-DDTHH:MM:SSZ
  • At these hours: 9
Logic Apps Flow

Click plus button, go to Custom and choose To-Do Connector as a next step and select Get To-Do Tasks as an action.

Logic Apps Flow

Sign in with the same account you practiced To-Do APIs in the Graph Explorer.

Logic Apps Flow

Run the flow and see if you successfully get to-do tasks by using your Get To-Do Tasks. Copy the outputs body, we will use it in the next step.

Logic Apps Flow Results

Add Parse JSON as a next step. Place Get To-Do Tasks body under the Context. Select generate schema, paste the response body you are receiving from the Get To-Do Tasks and save.

Logic Apps Flow

Add Initialize variable as a next step. Fill the field as follows:

  • Name: Tasks
  • Type: Array
  • Value: leave blank

Add For each as a next step and fill the fields as follows:

  • Output from previous steps: value from the Parse JSON step

Add Compose in For each and fill the fields as follows:

  • Inputs: title from the Parse JSON step

Add Append to array variable in For each, and fill the fields as follows:

  • Name: Tasks
  • Value: Outputs from the Compose step.
Logic Apps Flow

Run the flow and see if To-Do Json response is successfully parsed and all task titles are added in the Tasks array.

Logic Apps Flow Results
Logic Apps Flow Results

As a next step after For each, add Post a choice of options as the Flow bot to a user and fill the fields as follows:

  • Options: Tasks from the Variables step
  • Headline: Good morning!
  • Receipent: The same account you consumed the custom connector
  • Message: Here is your tasks, have a great day! :)
  • IsAlert: Yes
Logic Apps Flow

Run the flow and see check Microsoft Teams for the related account if Flow bot is sending a message. Select one of the tasks to see the results in the Logic app flow.

Note: If you didn't add Flow in your Microsoft Teams yet, here is the steps to enable Flow in your Teams account: https://cda.ms/1BB

Teams Flow Bot Results
Logic Apps Flow Results

Finally, after user selected any of the tasks to see more details, we will post another card to share more details about the selected option.

Add For each after Post a choice of options as the Flow bot to a user and fill the fields as follows:

  • Output from previous steps: value from Parse JSON step

Add Condition in For each and fill the fields as follows:

  • Condition: And
  • Choose a value: SelectedOption from the Post a choice of options as the Flow bot to a user step
  • Operation: equal to
  • Choose a value: title from Parse JSON step
    • If true: Add Post message as a Flow bot to a user in true
      • Headline: title from Parse JSON step
      • Receipent: The same account you consumed the custom connector
      • Message: importancestatuscreatedDateTime from ParseJSON step
      • IsAlert: Yes
    • If false: leave blank
Logic Apps Flow

Here is the complete flow. Run the entire flow for testing.

Logic Apps Flow

And, the following is going to be the results after selecting one of the tasks to see the details:

Teams Flow Bot Results
Logic Apps Flow Results

Our flow is completed! You can find the source code below:

Authentication in Teams tabs using Microsoft Graph Toolkit

If you are looking for ways to build easy authentication for Microsoft Teams custom tab developmentMicrosoft Graph Toolkit Login component provides a button and flyout control to facilitate Microsoft identity platform authentication with couple of lines of code.

How to build a tab with straightforward authentication flow?

  1. Enable Microsoft Teams Toolkit extension for Visual Studio Code
  2. Build Microsoft Teams tab
  3. Implement Microsoft Graph Toolkit:
  4. Setup ngrok for tunneling
  5. Register your app in Azure Active Directory
  6. Import your app manifest to Microsoft Teams App Studio for testing

Enable Microsoft Teams Toolkit extension for Visual Studio Code

Install Microsoft Teams Toolkit from the Extensions tab on the left side bar in Visual Studio Code. For more information, Microsoft Teams Toolkit: Setup and Overview.

Microsoft Teams Toolkit Extension for Visual Studio Code

Build Microsoft Teams tab

  • Select Microsoft Teams icon on the left side bar in Visual Studio Code and Sign in.
Microsoft Teams Toolkit Extension for Visual Studio Code
  • Select Create a new Teams app,
    • Give a name for the app
    • Choose Tab for the capability
    • Select Next
Microsoft Teams Toolkit Extension for Visual Studio Code
  • Select Personal tab
  • Select Finish
Microsoft Teams Toolkit Extension for Visual Studio Code
  • Open Terminal and run:
    npm install
    npm start

Implement Microsoft Graph Toolkit

Add a new file under src folder and name it as Auth.js.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './components/App';
import { Provider, themes } from '@fluentui/react-northstar' //https://fluentsite.z22.web.core.windows.net/quick-start

ReactDOM.render(
    <Provider theme={themes.teams}>
        <App />
    </Provider>, document.getElementById('auth')
);

Add a new file under public folder and name as auth.htmlCTRL+SPACE for adding HTML Sample. Add below code in <body></body>

<div id="auth"></div>
<script src="https://unpkg.com/@microsoft/teams-js/dist/MicrosoftTeams.min.js" crossorigin="anonymous"></script>
<script src="https://unpkg.com/@microsoft/mgt/dist/bundle/mgt-loader.js"></script>
<script>
  mgt.TeamsProvider.handleAuth();
</script>

Add below code in index.html <body></body>

 <script src="https://unpkg.com/@microsoft/teams-js/dist/MicrosoftTeams.min.js" crossorigin="anonymous"></script>
 <script src="https://unpkg.com/@microsoft/mgt/dist/bundle/mgt-loader.js"></script>
 <mgt-teams-provider client-id="YOUR-CLIENT-ID" auth-popup-url="YOUR-NGROK-URL/auth.html"></mgt-teams-provider> 
 <mgt-login></mgt-login>
 <mgt-agenda></mgt-agenda>

Setup ngrok for tunneling

npm start

  • Go to ngrok website and login.
  • Complete the setup and installation guide.
  • Save Authtoken in the default configuration file C:\Users\[user name]\.ngrok:

ngrok authtoken <YOUR_AUTHTOKEN>

ngrok http https://localhost:3000

Ngrok Setup
Ngrok Setup
Ngrok Setup
  • Go to your project public > index.html, replace YOUR-NGROK-URL with ngrok url https://xxxxxxxxxxxx.ngrok.io in mgt-teams-provider > auth-popup-url.
Ngrok Setup

Register your app in Azure Active Directory

  • Go to Azure Portal, then Azure Active Directory > App Registration and select New Registration.
Ngrok Setup
  • Fill the details to register an app:
    • give a name to your application
    • select Accounts in any organizational directory as an access level
    • place auth-popup-url as the redirect url https://xxxxxxxxxxxx.ngrok.io/auth.html
    • select Register
Ngrok Setup
  • Go to Authentication tab and enable Implicit grant by selecting Access tokens and ID tokens
Ngrok Setup
  • Go to API permissions tab, select Add a permission > Microsoft Graph > Delegated permissions and add Calendar.ReadCalendar.ReadWrite.
  • Then, select Grant admin consent.
Ngrok Setup
  • Go to Overview tab and copy Application (client) ID
  • Then go to your project public > index.html, replace YOUR-CLIENT-ID with Application (client) ID in mgt-teams-provider > auth-popup-url.
Ngrok Setup
Ngrok Setup

Import your app manifest to Microsoft Teams App Studio for testing

  • Go to Microsoft Teams, open App Studio > Manifest Editor and select Import an existing app.
Ngrok Setup
  • Select Development.zip under your project folder > .publish.
Ngrok Setup
  • Scroll down and select Test and distribute, then click Install and Add your app.
Ngrok Setup
Ngrok Setup
  • Click on Sign in for the authentication and give consent to AAD registered app you created.
Ngrok Setup
  • Your profile information e-mailname and calendar should appear in your tab after the successful authentication.
Ngrok Setup
Solution repository is available here: https://github.com/aycabas/TeamsApp

Microsoft Graph Toolkit: gather together your Office 365 in one app

Hey there! Today, we will work on an ASP.NET Core MVC web app with the power of Microsoft Graph Toolkit. Our purpose is to enable:

  • Microsoft identity platform authentication
  • the agenda from Outlook Calendar
  • the tasks from Planner
  • e-mails from Outlook

If you never heard of Microsoft Graph Toolkit before, it is a powerful collection of reusable web components that enables accessing Microsoft 365 data with just couple lines of code! Believe it or not, Microsoft identity platform authentication can be implemented in seconds.

This web app will be a quick scenario to try out Microsoft Graph Toolkit!

You can get the source code from here .


Create ASP.NET Core MVC web app in Visual Studio Code

  • Open the Terminal in Visual Studio Code (Ctrl+Shift+`)
  • Then, create a new folder for the project
PS C:\Users\user> cd Desktop
PS C:\Users\user\Desktop> mkdir GraphToolkitNetCore
  • Create ASP.NET Core MVC app
PS C:\Users\user\Desktop> dotnet new mvc
PS C:\Users\user\Desktop> cd GraphToolkitNetCore
  • The app is created successfully! Now, click on “Open Folder” to open your project folder.
  • Press F5 to run the project
  • Our project is working fine. Before we start building our app with Microsoft Graph Toolkit, let’s go to Properties > launchSettings.json and set http://localhost:8080to applicationUrl

Register an app in Azure Active Directory

  • First thing first, go to Azure Portal
  • Under Azure Active Directory, go to App Registration and click on New Registration
  • Give a name to your app
  • Choose the access level
  • Choose Web and place http://localhost:8080 as a Redirect URI
  • Go to Authentication tab
  • Then, check Access tokens and ID tokens
  • Finally, go to Overview tab
  • Copy Application (client) ID to a notepad, we will need it later

Setup Index.cshtml

  • Go to Index.cshtml and add a row and three columns inside the row
<div class="row" id="content">
    
    <div class="column" id="one"></div>
    <div class="column" id="two"></div>
    <div class="column" id="three"></div>
    
</div>
  • Copy below additional css to site.css under wwwroot>site.scs
/* Main content */
#content, html, body {
  height: 98%;
}
#one {
  float: left;
  width: 33%;
  background:transparent;
  height:500px;
  overflow: hidden;
}
#one:hover {
  overflow-y: auto;
}
#two {
  float: middle;
  width: 33%;
  background: transparent;
  height: 500px;
  overflow: hidden;
}
#two:hover {
  overflow-y: auto;
}
#three {
  float: left;
  width: 33%;
  background: transparent;
  height: 500px;
  overflow: hidden;
}
#three:hover {
  overflow-y: auto;
}
/*Email*/
.email {
  box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3);
  padding: 10px;
  margin: 8px 4px;
  font-family: Segoe UI, Frutiger, Frutiger Linotype, Dejavu Sans, Helvetica Neue, Arial, sans-serif;
}
.email:hover {
  box-shadow: 0 3px 14px rgba(0, 0, 0, 0.3);
  padding: 10px;
  margin: 8px 4px;
}
.email h3 {
  font-size: 12px;
  margin-top: 4px;
}
.email h4 {
  font-size: 10px;
  margin-top: 0px;
  margin-bottom: 0px;
}
.email mgt-person {
  --font-size: 10px;
  --avatar-size-s: 12px;
}
.email .preview {
  font-size: 13px;
  text-overflow: ellipsis;
  word-wrap: break-word;
  overflow: hidden;
  max-height: 2.8em;
  line-height: 1.4em;
}
a.navbar-brand {
  white-space: normal;
  text-align: center;
  word-break: break-all;
}

Let’s start working with Microsoft Graph Toolkit

Login

  • Go to Home>Index.cshtml
  • Implement MSAL provider in Index.cshtml
  • Make sure it is placed under the welcome message
<script src="https://unpkg.com/@@microsoft/mgt/dist/bundle/mgt-loader.js"></script>
<mgt-msal-provider client-id="[Client-id]"></mgt-msal-provider>
<mgt-login></mgt-login>
  • Paste Application (client) ID that you copied earlier from Azure Active Directory
  • Press F5 to run your application
  • Click on sign in button and login with your account
  • Accept to permission request
  • When the authentication is completed, you should see your details in the page

Get E-mails

  • Use mgt-get to get user’s e-mails. Implement below code as column 1 in Index.cshtml
       
<mgt-get resource="/me/messages" version="beta" scopes="mail.read" max-pages="1">
     <template>
        <div class="email" data-for="email in value">
            <h4><mgt-person person-query="{{email.sender.emailAddress.address}}" show-name person-card="hover"></mgt-person></h4>
             <h3>{{ email.subject }}</h3>
             <div data-if="email.bodyPreview" class="preview" innerHtml>{{email.bodyPreview}}</div>
             <div data-else class="preview">email body is empty</div>
        </div>
      </template>
      <template data-type="loading">loading</template>
      <template data-type="error">{{ this }} </template>
</mgt-get>  
  • Press F5 to run the app, you should be able to see the emails

Agenda

  • Use mgt-agenda to get a user or group calendar. Implement below code as column 2 in Index.cshtml
<mgt-agenda group-by-day></mgt-agenda>
  • Then, press F5 to run the app. You should be able to see the agenda on the right side of the e-mails

Tasks

  • Use mgt-tasks to get a user or group calendar. Implement below code as column 3 in Index.cshtml
<mgt-tasks></mgt-tasks>
  • Press F5 to run the app, you should be able to see the tasks on the right side of the agenda

Final version of Index.cshtml will look like below:

@{
    ViewData["Title"] = "Home Page";
}
<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <script src="https://unpkg.com/@@microsoft/mgt/dist/bundle/mgt-loader.js"></script>
    <mgt-msal-provider client-id="[Client-id]"></mgt-msal-provider>
    <mgt-login></mgt-login>
</div>
<div class="row" id="content">
     
    <div class="column" id="one">  
        <mgt-get resource="/me/messages" version="beta" scopes="mail.read" max-pages="1">
            <template>
                <div class="email" data-for="email in value">
                    <h4><mgt-person person-query="{{email.sender.emailAddress.address}}" show-name person-card="hover"></mgt-person></h4>
                        <h3>{{ email.subject }}</h3>
                        <div data-if="email.bodyPreview" class="preview" innerHtml>{{email.bodyPreview}}</div>
                        <div data-else class="preview">email body is empty</div>
                </div>
            </template>
            <template data-type="loading">loading</template>
            <template data-type="error">{{ this }} </template>
        </mgt-get>   
    </div>
    <div class="column" id="two">
        <mgt-agenda group-by-day></mgt-agenda>
    </div>
    <div class="column" id="three">
        <mgt-tasks></mgt-tasks>
    </div>
     
</div>

Our app is ready! As a result, we have our e-mails, agenda and tasks in one place. I hope you enjoyed using Microsoft Graph Toolkit. You can get the source code from here.

Let me know about your experience or if you have any feedback!

If you are interested in learning more about Microsoft Graph, check out the related posts.