Build seamless automations to boost productivity with Microsoft Graph, Event Hubs and Logic Apps

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 Logic Apps
  • ♾️ Exercise: Create Onboarding workflow in the Logic Apps
  • 🚀 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.

Overview of Microsoft Graph

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.

Solution 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 Logic Apps

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 Logic Apps 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 Logic Apps.

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 Flow 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 Directory.Read.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 Logic Apps

  1. Go to Azure Portal and select Create a resource, type Logic apps and select click Create.

  2. Fill in the Logic Apps creation details, and then click Create.

  3. Go to the newly created Logic Apps page, select Workflows tab from the left pane and select + Add:

    • Give a name to the new workflow as graph-subscription-flow
    • Select Stateful as a state type
    • Click Create.
  4. Go to graph-subscription-flow, and then select Designer tab.

  5. In the Choose an operation section, search for Schedule and select Recurrence as a trigger. Fill in the parameters as below:

    • Interval: 61
    • Frequency: Minute
    • Time zone: Select your own time zone
    • Start time: Set a start time
  6. Select + button in the flow and select add an action. Search for HTTP and select HTTP as an action. Fill in the parameters as below:

    {
    "changeType": "created, updated",
    "clientState": "secretClientValue",
    "expirationDateTime": "@{addHours(utcNow(), 1)}",
    "notificationUrl": "EventHub:https://<YOUR-VAULT-URI>/secrets/<YOUR-KEY-VAULT-SECRET-NAME>?tenantId=<YOUR-TENANT-ID>",
    "resource": "users"
    }
    

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

    In resource, define the resource type you’d like to track changes. For our example, we will track changes for users resource.

    • Authentication:
      • Authentication type: Active Directory OAuth
      • Authority: https://login.microsoft.com
      • Tenant: Directory (tenant) ID copied from AAD app
      • Audience: https://graph.microsoft.com
      • Client ID: Application (client) ID copied from AAD app
      • Credential Type: Secret
      • Secret: value of the secret copied from AAD app
  7. Select Save and run your workflow from the Overview tab.

Check your subscription in Graph Explorer: If you’d like to make sure that your subscription is created successfully by Logic Apps, you can go to Graph Explorer, login with your Microsoft 365 account and make GET request to https://graph.microsoft.com/v1.0/subscriptions. Your subscription should appear in the response after it’s created successfully.

Subscription workflow success

After subscription is created successfully by Logic Apps, Azure Event Hubs will receive notifications whenever there is a new user created in Azure Active Directory.

♾️ Exercise: Create Onboarding workflow in the Logic Apps

We’ll create a second workflow in the Logic Apps 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. Go to the Logic Apps you created in the previous steps, select Workflows tab and create a new workflow by selecting + Add:

    • Give a name to the new workflow as teams-onboarding-flow
    • Select Stateful as a state type
    • Click Create.
  2. Go to teams-onboarding-flow, and then select Designer tab.

  3. In the Choose an operation section, search for Event Hub, select When events are available in Event Hub as a trigger. Setup Event Hub connection as below:

    • Create Connection:
      • Connection name: Connection
      • Authentication Type: Connection String
      • Connection String: Go to Event Hubs > Shared Access Policies > RootManageSharedAccessKey and copy Connection string–primary key
      • Select Create.
    • Parameters:
      • Event Hub Name: Event Hub
      • Consumer Group Name: onboarding
  4. Select + in the flow and add an action, search for Control and add For each as an action. Fill in For each action as below:

    • Select output from previous steps: Events
  5. Inside For each, select + in the flow and add an action, search for Data operations and select Parse JSON. Fill in Parse JSON action as below:

  6. Select + in the flow and add an action, search for Control and add For each as an action. Fill in For each action as below:

    • Select output from previous steps: value
    1. Inside For each, select + in the flow and add an action, search for Microsoft Teams and select Add a member to a team. Login with your Microsoft 365 account to create a connection and fill in Add a member to a team action as below:
    • Team: Create an Onboarding team on Microsoft Teams and select
    • A user AAD ID for the user to add to a team: id
  7. Select Save.

🚀 Debug your onboarding experience

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

  1. 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

    new user in Azure Active Directory

  2. When you added Jane Doe as a new user, it should trigger the teams-onboarding-flow to run. teams onboarding flow success

  3. Once the teams-onboarding-flow runs successfully, you should be able to see Jane Doe as a member of the Onboarding team on Microsoft Teams! 🥳 new member in Onboarding team on Microsoft Teams

📚 Resources

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

Let people try your query in Microsoft Graph Explorer

Microsoft Graph Explorer is a wonderful learning space for the ones who are looking for testing Microsoft Graph APIs and reviewing the responses quickly. It provides the simple authentication where you can login, then see the response preview with your own tenant data. The best part of Microsoft Graph Explorer is its user-friendly design that makes it practical and easy to understand how to benefit the most out of it. Even better, it continues evolving with new releases all the time!

Today, we will explore one of the most practical features of Graph Explorer: “Share Query“. Let’s say that you are working with advanced queries ($filter, $search, $orderby etc.) in the Graph Explorer. After getting the required results, you would like to let people try your current query. We can easily do that in 2 steps:

  • Step 1: Click on Share button on the right side of the Response preview section.
  • Step 2: Copy your query and share with other people.
  • Result: Others can paste this shared link to any browser, then they will be directed to your pre-populated query in Microsoft Graph Explorer. They can click on Run Query button to see the response preview.

Here is a sample query, feel free to copy and paste it in any browser to see the results in the Graph Explorer:

https://developer.microsoft.com/en-us/graph/graph-explorer?request=groups?$filter=startswith(displayName,’all’)&method=GET&version=v1.0&GraphUrl=https://graph.microsoft.com&requestBody=IiI=

Feel free to ask you questions and share your experience in the comment window.

Cheers.

Microsoft Teams Toolkit: Setup and Overview

Recently, an amazing Visual Studio Code extension Microsoft Teams Toolkit has been released for developers who are willing to build apps for Microsoft Teams. It is easier and faster to build bots, tabs or messaging extensions with Microsoft Teams Toolkit that provides developers to create, debug and deploy Teams apps directly from Visual Studio Code.

Microsoft Teams Toolkit Extension

If you are interested in building apps for Microsoft Teams, simply you can go to Visual Studio Code Extensions tab, and install Microsoft Teams Toolkit extension.

After a successful installation of Microsoft Teams Toolkit extension, Microsoft Teams icon will appear in the activity bar.

When you click on Microsoft Teams icon in the activity bar, you can direct to Open Microsoft Teams Toolkit for getting a guidance and documentation about setting up your environment, building an app or publishing your app to Microsoft Teams. Each step redirects to the related official documentation.

To create a new Teams app, click on Create a new Teams app, give a name to your project and choose the capability you wish to create.

Microsoft Teams Toolkit provides Tabs, Bots and Messaging Extensions as types of Teams apps.

After creating any type of Teams app, our project is ready for development, debugging and publishing. ( .publish folder will be generated automatically under the project folder and manifest.json will be available for testing on Microsoft Teams App Studio. )

In addition to creating Teams apps from scratch, we can also import a current app package and edit app package from Visual Studio Code.

Microsoft Teams Toolkit is a very practical extension that helps us avoiding multiple manual steps while building applications for Microsoft Teams. Next, we will be exploring how to build Teams apps and run it on Microsoft Teams.

Feel free to share your thoughts about Microsoft Teams Toolkit extension in the comment window.

Cheers!