Build and run your Microsoft Teams app in 10 minutes with the Teams Toolkit for VS Code

Yu

Did you know that Microsoft Teams supports custom developed apps? More and more developers are building unique and custom apps in Teams to support a wide range of scenarios – from simple task management apps to complex virtual healthcare apps. To make the development experience frictionless, we are dedicated to providing you the tools and resources to help you build Teams apps faster and simpler. The Teams Toolkit for Visual Studio Code is one of the many tools that make building these apps easier and we’ll show you today exactly how to get started using it.

The scenario: Creating a Todo List app

In this blog, we’ll cover how to build and deploy a web-based collaborating Todo List app. This will demonstrate how easy it is to build a Teams app using the Teams Toolkit. The Todo List app enables teams to manage a shared to-do list and can be added to a channel for every team member to use. Each member can create items (with track history) and the item can be marked as done or deleted by other members upon completion. The Todo List app has a frontend interface hosting on Azure storage and a backend hosting on Azure Functions to respond to changes. It uses simple authentication offered by Teams Toolkit to get the user profile and know who is making changes and synchronizes data in Azure SQL Database. Now, let’s show you how to build this by going through the steps below and see how you go from zero to wonderful in about 10 minutes!

Setting up Teams Toolkit for Teams App development

Please make sure you install the VS Code first.

If you have VS Code installed, search `Teams Toolkit` from Extension View and select install, or  install the Teams Toolkit from marketplace.

Image showing the search and retrieval of Teams Toolkit in Visual Studio Code

Download and install the latest v14 LTS release Node.js.

Create Todo List App

Open the Teams Toolkit. From the left Tree View, in project section, click ‘Create New Project’. Select ‘Start from a Sample’ -> ‘Todo List with backend on Azure’.

GIF showing a developer creating a new project in the Teams Toolkit

Run and Preview

Now that you have the source code of the project, you can deploy and run the app to have a preview. From the left Tree View, in project section, click ‘Provision in the cloud’.

Image showing the left Tree view within VS Code with user clicking ‘Provision in the Cloud’

The Teams Toolkit will create the required cloud resources for you. In this sample, it creates an Azure web app to hosting your web pages (Tabs in Teams) for Todo app frontend interfaces, an Azure Functions instance to host backend service, and an Azure SQL as your database. This may require you to log in to your Azure account and select an Azure subscription you would like to use for this sample app, as the Todo List app will be deployed to Azure resources and stores data on Azure. You will need an Azure subscription in which you have rights to provision cloud resources like Azure Function and Azure SQL and specify your SQL admin name and password before provision starts. Then the Toolkit can create the SQL DB accordingly. You can monitor the progress by the dialog in the bottom right corner:

Image of the ‘Launch Remote’ button in Teams Toolkit

Once the provision is finished, you will get a prompt dialog in the bottom right corner of VS Code indicating the success of the provision. Then you can try to deploy the app by clicking ‘Deploy to the cloud’ from the left Tree View. The Teams Toolkit will copy your code to the cloud resources created by previous provision step, so that your code can run in the cloud. Both steps will take about 2-3 mins if it’s the first run and you will see a completion message in the bottom right.

Once deployment is done, you have a backend service running in the cloud in Azure Functions, and a frontend hosting and a database created for your sample app. One last step to run your app is creating the database schema for data storage. Open the `.fx/env.default.json` file and get the database name in `databaseName` parameter. Once you have the name, you can go to the Azure portal to run the following scripts which creates DB schema for you (More instructions about running Azure SQL scripts can be found here).

CREATE TABLE Todo

(   

id INT IDENTITY PRIMARY KEY,   

description NVARCHAR(128) NOT NULL,   

objectId NVARCHAR(36),   

channelOrChatId NVARCHAR(128),   

isCompleted TinyInt NOT NULL default 0,

)

Now you are ready to run and preview your first Teams app. Open the Teams Toolkit. From the left side bar, click ‘Run and Debug’ button.

Image of the ‘Run and Debug’ icon

And select `Launch Remote (Edge)` or `Launch Remote (Chrome)` in the dropdown list and Press F5 or `green arrow button` to open a browser.

Image of the ‘Launch Remote’ button in Teams Toolkit

Local Debug

The Teams Toolkit allows you to run your app locally. You can easily achieve this by pressing `F5` from VS Code. When you run the app for the first time, all dependencies are downloaded, and the app is built. A browser window automatically opens when the build is complete. This can take about 3-5 minutes to complete. You will need to sign into Teams in the browser to have a preview of your App. Since the app is using an Azure SQL as database, you will need to create the database manually if you want to debug manually. While in remote debugging mode, you will not need to create database manually because the Teams Toolkit did that for you when it provisioned cloud resources.

Simple Authentication – Single Sign-on

The Todo List app leverages the simple authentication capability to accomplish single sign-on using Teams account. With just 3 lines of code, you can enable this using Teams Toolkit and get the user profile from the `TeamsUserCredential` component. This component stores the user profile like the username, title, avatar and other information such as the SSO token to access Azure Functions API.

import  TeamsUserCredential from"@microsoft/teamsfx";
 
   Const credential=new TeamsUserCredential();
    // Get the user info from access token
    Const userInfo=await credential.getUserInfo();

You can check out this piece of source code in ‘~/tabs/src/components/Tab.js’, or check out the full code in our Todo List Github Repo.

Interacting with Azure Functions Backend

The Todo List frontend web app interacts with backend service by calling Azure Functions API with SSO token got from user credentials.

import{
  getResourceConfiguration,
  ResourceType
}from"@microsoft/teamsfx";
 
 callFunction(command,method,options,params){
      // Get SSO token for the user
      Const accessToken=await this.credential.getToken("");
      // Gets configuration for API
      Const apiConfig=getResourceConfiguration(ResourceType.API);
      Const response=await axios.default.request({
        method: method,
        url: apiConfig.endpoint+"/api/"+command,
        headers: {
          authorization: "Bearer "+accessToken.token
        },
        data: options,
        params
      });
      Return response.data;

Interacting with Azure SQL

The Azure Functions service has two key responsibilities, one is to process the http calls received from UI app and the other is to interact with Azure SQL to update and maintain data consistency. To make CRUD operations in SQL DB, you will need to set up a DB connection.

async function getSQLConnection(){
    const sqlConnectConfig=new DefaultTediousConnectionConfiguration();
    const config=await sqlConnectConfig.getConfig();
    const connection=new Connection(config);
    return new Promise((resolve,reject)=>{
        connection.on('connect',err=>{
            if(err){
                reject(err);
            }
            resolve(connection);
        })
        connection.on('debug',function(err){
            console.log('debug:',err);
        });
    })
}

Use the following method to query data:

async function execQuery(query,connection){
    return new Promise((resolve,reject)=>{
        const res=[];
        const request=new Request(query,(err)=>{
            if(err){
                reject(err);
            }
        });

       request.on('row',columns=>{
            const row={};
            columns.forEach(column=>{
                row[column.metadata.colName]=column.value;
            });
            res.push(row)
        });
 
        request.on('requestCompleted',()=>{
            resolve(res)
        });
 
        request.on("error",err=>{
            reject(err);
        });
 
        connection.execSql(request);
    })

You can check out this piece of source code in ‘~/api/todo/index.js’, or check out the full code in our Todo List Github Repo.

And that’s it! Building and running an app with the Teams Toolkit is easy and we hope you found this tutorial valuable. We can’t wait to see what Teams apps you build!

More samples you can try

Explore more samples in our sample repository.

Get more information about Teams Toolkit .

Quick start to Teams apps development.

Contact us if you need help

We appreciate any questions or feedback you may have. You can get direct help from product experts in Microsoft by logging your issues or ideas in our Github repo issues or by posting your questions using ‘Teams-Toolkit’ tag on StackOverflow.

Also, don’t forget to follow us on Twitter @Microsoft365Dev and stay tuned with this community channel for the more upcoming features!

 

Happy coding!

0 comments

Comments are closed. Login to edit/delete your existing comments