Convert Speech to Text using OpenAI Whisper in Power Apps

OpenAI has released a new neural network called Whisper, which is an open-source model that can convert speech to text with impressive accuracy. This model is specifically designed to transcribe spoken language into text with high precision and speed, making it an ideal tool for a variety of applications, such as virtual assistants and video captioning. Whisper relies on advanced machine learning algorithms to analyze audio signals from multiple languages and convert them into written text. OpenAI has recently made API endpoints available to the public since March 1, 2023, allowing developers to easily integrate this powerful technology into their own applications.

The Speech to Text Open API can

  • Transcribe audio into whatever language the audio is in.
  • Translate and transcribe the audio into English.

As of the date I am writing this post, this model is not available in Azure. In this blog post, I will cover how to use the Microphone control and File Upload control to convert speech to text using the OpenAI Whisper API in a Power Automate flow.

Download Link to the Sample App: https://github.com/ashiqf/powerplatform/blob/main/OpenAI-SpeechtoText.msapp. Replace the API Key in the Power Automate flow HTTP Action Authorization Header.

OpenAPI Speech to Text API:

The speech to text API provides two endpoints, transcriptions and translations. At present, the maximum file size allowed for uploads is 25 MB and the supported audio formats are mp3, mp4, mpeg, mpga, m4a, wav, and webm. In this blog post, I utilized the Translation API to demonstrate its capability to convert English audio into text, it can understand other languages as well

POST https://api.openai.com/v1/audio/translations

If you have not yet created an API key, please sign up/login for OpenAI and obtain it from there.

Body:

Integration with Power Apps:

I have used a Power Automate flow with the Power Apps trigger to invoke the Speech to Text API via the HTTP connector in Power Automate. Alternatively, you can achieve the same outcome by constructing a Custom Connector. This sample app can be downloaded from this github link.

Microphone Control:

The audio control captures audio input through the device’s microphone and will be sent to the Power Automate flow for conversion into text using the Whisper API. The audio format of the recording depends on the type of device being used

  • 3gp format for Android.
  • AAC format for iOS.
  • Webm format for web browsers.

I’ve tested this control from the app accessed through the web browser. If you encounter an unsupported audio format for OpenAI, you can use utilities such as FFMpeg. Additionally, a .Net version of the control is available for download which can be used in Azure Function. John Liu (MVP) has written a sample Azure function that handles the conversion of audio formats using the aforementioned utility.

Step 1: To add a microphone control to the canvas, insert the Microphone control from the command bar. To preview the recorded audio from the Microphone control, add an Audio control

Step 2: Add a button to convert and to trigger the Power Automate flow. Find below the Power FX code

//Generates a JSON Text with the binary of the Audio file or Recorded audio
Set(varJson,JSON(Microphone1.Audio,JSONFormat.IncludeBinaryData));
Set(strB64Audio, Last(Split(varJson, ",")).Value);
Set(strB64AudioContent, Left(strB64Audio, Len(strB64Audio) - 1));
//Extract Audio Format
Set(varAudioFileType,Mid(varFileContent,Find(":",varFileContent)+1,Find(";",varFileContent)-Find(":",varFileContent)-1));
//Call the Power Automate Flow
Set(audioText,'SpeechtoText-OpenAIWhisper'.Run(strB64AudioContent,varAudioFileType).audiotext);

The Power FX code performs the following task

  • Stores the audio captured by a Microphone control in a variable as JSON data, including binary data.
  • Extracts the base64-encoded audio content from the JSON data using the string manipulation functions Split, Left, Mid.
  • Determines the audio file type by parsing a string variable.
  • Uses the extracted audio content and file type to call the Power Automate flow ‘SpeechtoText-OpenAIWhisper’ to obtain the corresponding text transcription which comes in later section of this post.
  • Assigns the resulting text transcription to a variable named ‘audioText’, this is assigned to a Text Label to display the converted text from the OpenAI Whisper API.

Step 3: Add a Label control to display the converted Text set to the variable audioText

File Upload Control

As of the day I am writing this post there is no file control that can handle all types of files in Power Apps, I have created a custom component utilizing the Attachment control to create a file attachment control. For further details, please refer to blogpost Uploading Files Made Easy: A Guide to Using the Attachment Control in Power Apps to add the control to the app.

Step 1: Add the file attachment control to the app from the component library. Set the input property for Maximum Attachments to 1 from the component.

Step 2: To extract the binary content of an audio file, add an Image control to the app. The Image control is capable of working with any type of file to extract its content.

Step 3: Add a Button control to convert the Audio from the uploaded file. Find the PowerFX below

//Generates a JSON Text with the binary of the Audio file using the Image control
Set(varFileContent,JSON(Image1.Image,JSONFormat.IncludeBinaryData));
//Extract Base64 content
Set(varExtractedFileContent,Last(Split(varFileContent,",")).Value);
//Remove the last character " from the string
Set(varExtractedFileContent,Left(varExtractedFileContent,Len(varExtractedFileContent)-1));
//Extract Audio Format
Set(varAudioFileType,Mid(varFileContent,Find(":",varFileContent)+1,Find(";",varFileContent)-Find(":",varFileContent)-1));
//Call the Power Automate Flow
Set(audioText,'SpeechtoText-OpenAIWhisper'.Run(varExtractedFileContent,varAudioFileType).audiotext);

Step 4: Add a Label control to display the converted Text set to the variable audioText

Power Automate Flow

Now, let’s create a Power Automate flow with the Trigger type Power Apps to invoke the OpenAI Whisper API and convert speech to text. Step 1: Add two compose action (input parameters) to receive the audio format and content from either the recorded audio captured by the Microphone control or the uploaded audio file from the file attachment control in the Power Apps

{
  "$content-type": @{outputs('Compose-AudioFormat')},
  "$content": @{triggerBody()['Compose-FileContent_Inputs']}
}

Step 2: Add a HTTP connector to make a request to the Whisper API endpoint. Refer to the blog post How to use form-data and form-urlencoded content type in Power Automate or Logic Apps HTTP action for handling multipart/form-data in the HTTP action

Request Body:

{
  "$content-type": "multipart/form-data",
  "$multipart": [
    {
      "headers": {
        "Content-Disposition": "form-data; name=\"model\""
      },
      "body": "whisper-1"
    },
    {
      "headers": {
        "Content-Disposition": "form-data; name=\"file\";filename=\"audiofile.webm\""
      },
      "body": @{outputs('Compose-FileContent')}
    }
  ]
}

Step 3: Add the Respond to a PowerApp or a flow action to pass the converted text back to the app. To get the converted text, use the following expression

body('HTTP-CallaOpenApiModel')['Text']

The expression was constructed based on the response of the Whisper API call. In the event that the response property changes in the future, please ensure to update the expression accordingly.

Summary:

In this post, I’ve outlined a step-by-step guide on how to develop a basic app with Speech to Text functionality using Power Apps and a Power Automate flow leveraging the OpenAI’s Whisper API. The possibilities for using this technology are endless, from creating virtual assistants to generating audio captions and translations. Furthermore, the Whisper API can also be used to transcribe video files, adding even more versatility to its capabilities. It’s worth noting that while Azure offers its own Speech to Text service, it currently does not rely on the OpenAI Whisper Model. However, it’s possible that the two services will eventually integrate in the future. Hope you have found this informational & thanks for reading. If you are visiting my blog for the first time, please do look at my other blogposts.

Do you like this article?

Subscribe to my blog with your email address using the widget on the right side or on the bottom of this page to have new articles sent directly to your inbox the moment I publish them.

Advertisement

Uploading Files Made Easy: A Guide to Using the Attachment Control in Power Apps

The Attachment control in Power Apps is a useful feature that allows users to upload and delete files, but it can only be used with data sources such as SharePoint List or Dataverse table. However, if you need to upload and delete files without using these data sources, you can create a custom component using the Attachment control or you can directly use this control in the app. I have followed the tip from Shane Young in this YouTube video to add the Attachment control to a component library.

By creating a custom component Library for the attachment control, you can upload and delete files similar to a Picture control but with the ability to handle any file type across any apps within an environment. This blog post is not a tutorial on how to create the component, but rather

  • How to use it
  • To Save the file in SharePoint Document Library using Power Automate Flow
  • How to customize the component to fit your needs.

How to use it – Add the Component to the Power Apps:

To incorporate this component into your app, you need to first import it into your environment. Please find below the steps to follow

Step 1: Download the component library from my github repo.

Step 2: Create a Blank Canvas App with a temporary name, on the studio command bar, click on the ellipsis > Click ‘Open’, browse to select the downloaded .msapp package. Save the App and then publish it. You would now be able to see the component from the Component Libraries.

Step 3: After following the instructions outlined in this documentation to import the Published component into your app, the component will be available for use in any app within the environment as shown below.

Step 4: Modify the input parameters of the component to adjust settings such as maximum number of attachments, border colour, attachment size, and other defined parameters of the component.

Step 5: To display the uploaded file content within the app or to send the file to a Power Automate flow, you can incorporate any of the following controls based on the file type:

In the Media Property of the control, the formula to display the file content is

First(FileAttachment_1.Attachments.FileAttachment).Value

The file content will be uploaded to the app as binary data with the URL appres://blobmanager/ for each file uploaded from the attachment control. To get the file Name:

First(FileAttachment_1.Attachments.FileAttachment).Name

Note: In the above screenshot, I have set the Max Attachments Component property to 1 in the Step 4

Send the File to Power Automate:

In order to send or store a file using a Power Automate flow, I needed to convert the file content to Base64 format. To accomplish this, I used a image control to capture the file content in binary format. Here is how I configured the image control:

This control works with any types of files to get the binary content.

After obtaining the binary content of the file using the JSON function, I performed some string manipulations to extract the binary content while excluding the Content-Type. Specifically, I used a combination of Split(), Left() and Last() functions to separate the content into an variable varExtractedFileContent.

Set(varFileContent,JSON(Image2.Image, JSONFormat.IncludeBinaryData));
Set(varExtractedFileContent, Last(Split(varFileContent, ",")).Value);
Set(varExtractedFileContent, Left(varExtractedFileContent, Len(varExtractedFileContent) - 1));

By performing these manipulations, I was able to extract the binary content of the file in a format that could be easily passed to a Power Automate flow or other API or action.

This allowed me to send the file to a Power Automate flow, which could then save the file in a SharePoint library or call some other API or action that required the data to be in Base64 format.

The Power Automate flow used to save the file to a SharePoint Document Library is simple. The flow consists of a Power Apps trigger and a SharePoint action Create File, which takes two input parameters: File Name and File Content.

I have used the base64toBinary() expression to convert the base64-encoded string to binary data. This expression is a prerequisite for the SharePoint create file action and ensures that the file is saved correctly to the SharePoint Document Library.

PowerFx to call the flow from Power Apps:

ProcessAttachments.Run(First(AttachmentComponent_1.Attachments.FileAttachment).Name,varExtractedFileContent);

If you need to upload multiple files to a library using the Attachment control, you can use Gallery control with the Image control, Collections, ForAll function, and the OnAddFile property from the Attachment control. First, create a collection to store the files that are uploaded using the Attachment control using the OnAddFile property. Then, use the Gallery control to load the binary of the uploaded files in the Image control. Next, use the ForAll function to iterate through each file in the gallery and call the Power Automate flow on a button click.

Customizing the Component:

The component I’ve created is a simple one for handling file attachments, but it does not have all the properties from the Attachment control. If you need more customization, you can easily modify it to suit your specific needs by adding additional input or output properties.

To add a new property, you can simply edit the component code and include the new property as an input or output parameter.

By customizing the component in this way, you can tailor it to your specific requirements and ensure that it meets all of your file attachment needs

Summary:

In summary, the Attachment control in Power Apps is a useful feature for uploading and deleting files, but it is limited to certain data sources. To work around this limitation, you can create a custom component using the Attachment control, which allows you to handle any file type and bypass the use of data sources like SharePoint or Dataverse tables. Hope you have found this informational & thanks for reading. If you are visiting my blog for the first time, please do look at my other blogposts.

Do you like this article?

Subscribe to my blog with your email address using the widget on the right side or on the bottom of this page to have new articles sent directly to your inbox the moment I publish them.

Call SharePoint REST API in a custom connector (Power Apps/Power Automate)

The Power Automate action Send an HTTP request to SharePoint could come handy in many scenarios to execute SharePoint REST API queries but you will not able to use this action directly in Power Apps. In this blogpost, let us see how to call the SharePoint REST API in a custom connector which can be used either in Power Automate or Power Apps. There are many REST API endpoints available within SharePoint but the following use cases are not satisfied with a SharePoint standard connector in Power Platform

  • Creating a site
  • Adding user to a SharePoint group

Pre-Requisites:

Azure Active Directory Application:

To execute a SharePoint REST API in Power Apps or Power Automate there must be an Azure AD app registered with appropriate SharePoint permission intended for the operations through a custom connector. For this example I have registered an AD application with the delegated permissions AllSites.Read.

Obtain the Client ID from the Overview section and create a secret from the Certificates & secrets under Manage blade. Once the secret is created, copy the value to be used in the custom connector. Add a Web Redirect URI https://global.consent.azure-apim.net/redirect as shown below

The Redirect URI is common and will be created while creating the custom connector.

Creation of Custom Connector:

Custom connector can be created from Power Apps maker portal or Power Automate portal. Custom connector created from any of the above-mentioned interfaces can be used in a Power App or Power Automate cloud flow. Let us see how to create a SharePoint communication site with the below permission using a custom connector. In the Power Automate portal, expand Data on the left panel > Custom connectors > + New custom connector > Create from blank

In Host field, enter tenantname.sharepoint.com and some description about the connector.

Along this article wherever you find the keyword tenantname, replace it with the name of the organizations Microsoft 365 tenant.

Now click Security on the right bottom corner to enter the Azure AD application information for the OAuth 2.0 authentication type. Under the section OAuth 2.0

Enter the Scope as AllSites.Read based on the permissions you have added on the Azure AD app. If you have multiple permission, leave a space between each permission

After the above information is filled in, click Create connector which will autogenerate the Redirect URL https://global.consent.azure-apim.net/redirect. This is the URL we have added as a Redirect Web URI in the Azure AD application. The connector is now ready for the actions based on SharePoint API endpoint to

Create SharePoint Communication site:

Details about the REST API to create a communication site can be found here. Find below the HTTP request details

Mode: POST

Request URI: https://tenantname.sharepoint.com/_api/SPSiteManager/create

Headers: application/json

Body:

{
  "request": {
    "Title": "Communication Site 1",
    "Url":"https://tenantname.sharepoint.com/sites/test-commsite2",
    "Lcid": 1033,
    "Description":"Description",
    "WebTemplate":"SITEPAGEPUBLISHING#0",
    "SiteDesignId":"96c933ac-3698-44c7-9f4a-5fd17d71af9e",
    "Owner":"owner@tenantname.com",
    "WebTemplateExtensionId":"00000000-0000-0000-0000-000000000000"
  }
}

Replace tenantname and Owner in the body

After the custom connector is created in the above step, now click the Definition tab of the Custom Connector > click + New action which will create the following screen to enter information about the action

After the Summary, Description and Operation ID is entered click + Import from sample under the Request section, enter the REST API details on the following screen per the information given above to create a site

Click Import and then make changes to the Headers and Body section as shown below

Make the parameter required and add the default values as shown below

After the above changes are done, click Update connector. The custom connector action to create a new communication site is ready to be tested. Click the Test tab and enter the body information for various parameters or enter the JSON directly by toggling the Raw Body property to On

In the response, you get the Site Object id of the newly created site.

Summary:

Many of the SharePoint REST API’s are available in Microsoft Graph’s ecosystem but there are still a few which is not but this method can solve that problem. If you are interested to know on calling a SharePoint REST API as an daemon application in Power Automate, go through this blogpost. Hope you have found this informational & thanks for reading. If you are visiting my blog for the first time, please do look at my other blogposts.

Do you like this article?

Subscribe to my blog with your email address using the widget on the right side or on the bottom of this page to have new articles sent directly to your inbox the moment I publish them.

Share Power Apps with Microsoft Teams Users

You can share an app with Microsoft Teams users since each Microsoft team also creates a Microsoft 365 group in Azure AD. The only pre-requisite is the associated Microsoft 365 group of the Microsoft Team should be securityEnabled. By default, the Microsoft team group is not security enabled. If you are trying to share a Power Apps with a Microsoft team which is not security enabled, you will not be able to add or select the group

Microsoft has documentation on how to security enable a Microsoft 365 group but you should have PowerShell installed on your computer. In this blog post, let us see how to enable securityEnabled property using Graph Explorer which is a web portal.

Pre-requisite:

  • Owner of the Microsoft Team
  • Access to Graph Explorer

Step 1: Find the Microsoft Teams Group Object ID. Login to the Microsoft Azure Active directory admin portal. Search for the Microsoft teams group using the display name of the Team. From the overview section of the group, copy the group Object Id

Step 2: Sign in to Graph Explorer. Find below the request details

Request Type: Patch

URL: https://graph.microsoft.com/v1.0/groups/groupObjectId

Request Body:

{
    "securityEnabled": true
}

If you have consent for permissions, click Modify permissions as shown above to grant consent. Once everything is set, click Run query to enable security role. Once the property is set to True, you can share the Power App with Teams users. This setting is not required to share a Microsoft cloud flow.

Hope you have found this informational & thanks for reading. If you are visiting my blog for the first time, please do look at my other blogposts.

Call Microsoft Graph API in Power Apps and Power Automate using a Custom connector

Microsoft graph is the gateway to data and intelligence in Microsoft 365 which connects multiple services like SharePoint, Teams, Planner etc and devices. Microsoft graph has one common endpoint that is RESTful Web API enabling you to access Microsoft Cloud service resources. With that said if you want to communicate with Microsoft Graph Services or any API services, custom connectors can be used to address needs which are not available as prebuilt connectors in Power Apps and Power Automate. The purpose of this blog post is to show how to

  • Create & setup Custom Connector to call Microsoft Graph API
  • Call Microsoft Graph API in Power Apps using custom connector
  • Call Microsoft Graph API in Power Automate using custom connector

Custom connector supports the following authentication types

  • Anonymous (No Authentication)
  • Basic Authentication (UserName & Password)
  • API Key
  • OAuth 2.0

As of the time I am writing this article, custom connector supports only authentication flow Authorization code & not client credentials. If you use OAuth 2.0, it means you can use only delegated permissions & not application permissions as permission type in the custom connector. To be more precise, the logged in user from PowerApps or flow actions/trigger connection user should have access to the resource to be accessed from Microsoft Graph & cannot access the resource as a daemon app (Application Permission). Find below the pre-requisite for the custom connector

  1. Premium Plan (App/user based) for all users intended to use the custom connector in Power Apps or Power Automate. To test the custom connector you can also get a community plan if you do not have a premium plan.
  2. Access to register Application in Azure AD portal

Create & setup Custom Connector to call Microsoft Graph API:

Custom connector can be created from Power Apps maker portal or Power Automate portal. Custom connector created from any of the above-mentioned interfaces can be used in a Power App or Power Automate cloud flow. A custom connector is nothing but a wrapper around a REST API that allows Power Apps or Power Automate and Azure Logic Apps to communicate with that REST API.

Azure Active Directory Application:

To access the Microsoft Rest API there must be an Azure AD app registered with appropriate graph permission intended for the operations through a custom connector. For this example I have registered an AD application with the following delegated permissions

  1. Calendars.Read
    • To display the users recent events in Power Apps gallery control
  2. Sites.Manage.All
    • To create a New list item in SharePoint list from Power Apps and Power Automate
  3. User.Read
    • To display users profile information from an Extension Attribute in Power Apps

Obtain the Client ID from the Overview section of the Azure AD app and create a secret from the Certificates & secrets under Manage blade. Once the secret is created, copy the value to be used in the custom connector.

Add a Web Redirect URI https://global.consent.azure-apim.net/redirect as shown below

The Redirect URI is common and will be created while creating the custom connector. Now we are ready to create the custom connector, go to Power Automate portal and expand Data on the left panel > Custom connectors > + New custom connector > Create from blank

After entering the connector name, you will get the below screen. Do not have the word SharePoint part of your connector name to avoid issues.

Enter graph.microsoft.com on Host and some description about the connector. You can also change the logo to a custom one. Now click Security on the right bottom corner to enter the Azure AD application information for the OAuth 2.0 authentication type. Under the section OAuth 2.0

  • Change the Identity provider to Azure Active Directory
  • Enter the Client id & Client secret of the Azure AD application
  • Leave the Login URL as https://login.windows.net & Tenant ID as common
  • Enter the Resource URL as https://graph.microsoft.com
  • Enter the Scope as Calendars.Read Sites.Manage.All User.Read based on the permissions you have added on the Azure AD app. Leave a space between each permission

After the above information is filled in, click Create connector which will autogenerate the Redirect URL https://global.consent.azure-apim.net/redirect. This is the URL we have added as a Redirect Web URI in the Azure AD application. The connector is now ready to add actions based on Graph API endpoint to

  • Get users recent events from the users default Outlook calendar
  • Create a List item in SharePoint List
  • Get users custom extension attribute from users Active directory profile

Get users recent events from the Outlook calendar:

The Graph API to get the logged in users list of recent calendar events is

Http Request Mode: GET

Request URI: https://graph.microsoft.com/v1.0/me/calendar/events

After the custom connector is created in the above step, now click the Definition tab of the Custom Connector > click + New action which will create the following screen to enter information about the action

After the Summary, Description and Operation ID is entered. Click + Import from sample under the Request section to the enter the Graph API endpoint url https://graph.microsoft.com/v1.0/me/calendar/events.

It is Okay to exclude the url https://graph.microsoft.com since we have provided the information in the Security tab.

Now we are ready to provide default response for the action. To get the request response sample for the graph api endpoint, SignIn to the Graph Explorer with your organizational ID to copy the response of the API request to be used in the custom connector action

After running the query in the graph explorer tool, copy the whole content (CTRL+A) from the Response preview section as shown on the above screenshot. If there is any error related to permissions while executing the http request in the explorer tool, make sure you have consented to the permissions in the Modify permissions tab.

Click + Add default response and then paste the content copied from the graph explorer tool on Body as shown below

Click Import and then click Update connector. Let us add the second action to create a list item in a SharePoint list

Create a List item in SharePoint List:

The graph API to create a List item in a SharePoint List is

Http Request Mode: POST

Request URI: https://graph.microsoft.com/v1.0/sites/siteId/lists/listId/items

You should replace the SiteId and listId in the above URL. Easy way to get the ListId and SiteId is by viewing the Viewing the page source of the SharePoint site with the list open

Request Body:

For this example I have a SharePoint list with a default column Title and a single line of text column by the name Location.

{
  "fields": {
    "Title": "Widget",
    "Location": "Stockholm"
  }
}

Once again click + New action on the Definition tab to add an action for creating a new list item.

After the Summary, Description and Operation ID is entered click + Import from sample under the Request section to the enter the Graph API endpoint url with the Verb now selected as POST and the request body or payload

Click Import. To get the request response sample for the graph api endpoint, go to the graph explorer to copy the request response as shown below for the above POST request to create the list item

Click + Add default response and then add the response copied from the graph explorer tool on the Body section as shown below

Click Import button and then click Update connector. Let us add the second action to read the users active directory profile to extract extension attribute information

Get users custom extension attribute from users Active directory profile:

On my tenant I have added additional properties on extension attribute in Azure AD profile of the user & displayed them on the User profile card using the profile card graph API. The graph API to get the extension attribute information of the user is in Beta as of now

Http Request Mode: GET

Request URI: https://graph.microsoft.com/beta/me

Once again click + New action on the Definition tab to add the third action for getting the users profile information from Azure active directory.

After the Summary, Description and Operation ID is entered click + Import from sample under the Request section to the enter the Graph API endpoint url with the Verb selected as GET

Click Import. Go to the graph explorer to copy the request response for the GET request for https://graph.microsoft.com/beta/me and then click + Add default response to paste the request response copied from the graph explorer tool. Click Import button and then click Update connector. We have till now added three actions which can be tested in the same interface

Test the Action:

To test the different actions added in the connector, click the Test tab and then click + New connection.

You will be prompted to sign in using the Organization ID and provide a consent for the permissions requested as a scope on the custom connector.

After the connection is created, you can test the different actions available as shown below for one of the action CreateListItem in SharePoint

The custom connector creates the Swagger definition, you can also view and update the Swagger definition by turning on Swagger Editor

If you look at the security definitions in the above screenshot for the connector we have created till now, the authentication flow used to authenticate the user is Authorization code which supports only delegated permissions and not application permissions in MS Graph. The Swagger definition file can be downloaded from interface shown below

The Swagger definition file can be used to re-create the custom connector by clicking the Down arrow and then by clicking Import an OpenAPI file. On the popup window enter the Connector Name and select the downloaded Swagger file to recreate the connector after filling in information on the Security tab.

You download the Swagger definition file of the custom connector with the above mentioned actions from this github link.

Call Microsoft Graph API in Power Apps using custom connector:

To call a custom connector in Power Apps, the first step is to add the connector to the Power App by the app maker. Click Data on the left panel and then click the button Add data > look for the connector by the name > Click the connector name to create a connection.

Once the connection is created & added, you will be able to use it in the different controls added to the app

I added the following controls to

  1. Label – To display the Extension attribute of the user from the action GetUserProfile
  2. Gallery – To display the users recent calendar events from the action
  3. Button – To create new item on the list and to get information from Graph about the user calendar events and to get the users AD profile

A Button control to load the data from Microsoft Graph GET actions GetUserProfile &  GetMyEvents on a context variable.

UpdateContext({userProfileData:'NameoftheConnector'.GetUserProfile(),userCalendarEvents:'NameoftheConnector'.GetMyEvents().value})

Once we have the data loaded on the context variable using the OnSelect button click event, the data can be displayed on different controls. Use the graph explorer tool to validate the response of the request and to help with display the data on a control. Find below the response for the me endpoint which provides the profile information of user including the extension attribute.

To display the Extension attribute1 information on a label control, the code is

userProfileData.onPremisesExtensionAttributes.extensionAttribute1

I have added a gallery control to display the calendar events. First step is to bind the gallery control to the context variable (userCalendarEvents) using Items property of the control

Items: userCalendarEvents

On the gallery control fields

field1: ThisItem.subject

field2: ThisItem.organizer.emailAddress.name

For constructing the above formula (Field1 and Field2) for displaying the information on the different fields in the control, graph explorer response preview will help you

I have added a button control to create the list item using the action CreateListItem with the following formula on the OnSelect event

'NameoftheConnector'.CreateListItem({fields: {Title: "Mohamed Ashiq Faleel",Location:"Sunbyberg"}});

Reference: https://docs.microsoft.com/en-us/powerapps/maker/canvas-apps/functions/function-json

Once the Power App is shared with other users

  • Connecter will be shared along with the app
  • The user has to create a connection to the Custom Connector & provide consent for the Graph permission (User.Read Sites.Manage.All Calendars.Read) for the first time
  • The users of the app should have premium license (App/user based)

Call Microsoft Graph API in Power Automate using custom connector:

To use a custom connector by a user in a flow Instant/Scheduled/Automated, it

  • Must be shared to the user by the custom connector Owner/creator
  • Premium license for the flow user
  • Consent to be provided for the graph permissions. The consent can be individual or admin consent

Add the action to the flow by clicking Custom and then select the custom connector as shown below

Now select the action

It will ask you to Sign In to create the connection and there will be a prompt to provide consent to the permission for the AD application for the first time as shown below

Enter the parameter values to create the list item

Summary: Microsoft Power Apps and Power Automate are great and simple to get started with no code. If you are a pro developer and want to extend the capabilities with Microsoft Graph & other external/custom RESTFul API’s you can do so with the custom connector. Hope you have found this informational & thanks for reading. If you are visiting my blog for the first time, please do take a look at my other blogposts.

Azure IoT with Arduino UNO board to turn on/off LED using a .NET core console application connected to Power Apps

This post is in continuation to my journey with IoT leveraging Microsoft cloud services & it’s technology and based out of few questions I have been asked in few of the events I’ve spoken on the Topic Controlling Devices using Power Apps. In this post let us see how to turn on/off a LED connected to an Arduino UNO board by sending a message from Azure IoT hub or Power Apps with the help of a .NET core console application created from Visual studio code.

What is Arduino UNO Board:

Arduino Uno is an open-source & low cost microcontroller board based on Microchip ATmega328P microcontroller. The board is equipped with digital and analog Input/Output pins that can be interfaced with other circuits. If there is a need to collect data from sensors (Temperature, Humidity etc) then the mode of the pin should be Input and for controlling devices or activating relays the pin mode must be Output. For this example since we will have to turn on/off a LED, the pin mode has to set as Output.

Arduino IDE:

The IDE is a cross platform application written using C++. If you have worked with an Arduino board already, you would have probably used the Arduino IDE to deploy code called as Sketch. The code written on the sketch is compiled to a HEX file (Machine language) which can be understood by the microcontroller once the sketch is uploaded. The hex file is then sent to the Arduino UNO board using the USB port.

Pre-Requisite:

Find below the design with information on the different components used:

Azure IoT Hub:

IoT hub is a managed service hosted in cloud that acts as a central message hub for bi-directional communication from the device to the cloud and the cloud to the device. There is an also a Free-Tier limited to one per subscription which can add up to 500 devices and 8000 msgs/day as of today based on the Pricing calculator. Create a IoT Hub for us to send a message to the Arduino UNO device as per the instruction given in the article. After the IoT hub is created.

  1. A device must be registered with your IoT hub before it can connect. There are different ways to register a device like using Azure Cloud shell, in this case we will use portal. Click IoT Devices under the Explorers blade on the IoT hub and click on + New, enter the Device ID and click save.
  1. Copy the Primary key of the registered device
  2. Copy the Hostname from the IoT Hub Overview blade
  3. These values will be used later in the .NET console application

Arduino Sketch:

Let us now create a simple Arduino project sketch from Visual studio code to send signal to Arduino Board using the serial port with the help of the Nuget package System.IO.Ports. Make sure the Arduino IDE and the Arduino extension for VS code is installed. The Arduino board can now be plugged in to the USB port of your laptop or computer with the provided cable. Follow the below mentioned steps to create an Arduino sketch template from VS Code

  1. Create a folder on the development machine for the Arduino project and then open the folder in Visual Studio code
  2. In VS Code, hit the key CTRL+Shift+P to open the command pallete
  3. Type the command Arduino: Initialize which will try to create a file with name app.ino. Change the name of the file relevant to your project. I have named it as ControlDevicesforCSharp.ino.
  4. You will now be prompted to select the name of the Arduino board. I have selected Arduino UNO. You can also select the board and port from the VS Code right bottom corner as shown below

The serial port will be visible if the board in plugged in and recognized by the computer. This is how it looks after the board and the port is selected.

  1. Now update the code as shown below to receive signal from the console application. If it receives a value of A to the character variable inputValue from the console application, then the PIN 13 is set to HIGH which means it generates 5v as an output and if the inputValue is B the PIN 13 is set to LOW which means the Output of the pin will be zero as opposed to 5v when set to HIGH. If you want, you can connect a LED to the PIN 13 with a 220 ohm resistor bu the pin 13 has a in-built LED to test. You can also notice on the code the PIN mode for 13 is set to Output.
#define BaudRate 9600

char inputValue;
int led1 = 13;

void setup() {
  // Initialize serial communication at 9600 bits per second
  Serial.begin(BaudRate);
  // Prepare the digital output pins
  pinMode(led1, OUTPUT);
  // Initially all are off
  digitalWrite(led1, LOW);
}

// the loop function runs over and over again forever
void loop() 
{
  // Reads the input
  inputValue = Serial.read();
  if(inputValue == 'A')
  {
    // Turn on the LED  
    digitalWrite(led1, HIGH);   
  }
  else if (inputValue == 'B') 
  {
    // Turn off the LED
    digitalWrite(led1, LOW);     
  }
}
  1. Now you verify the sketch by pressing CTRL+AL+R if there is any compile error. If all is well, you can now upload the sketch by pressing the key CTRL+ALT+U. If the upload is successful, you will the following message on the VS output terminal

Now the sketch is ready, it is now time to create the console application to receive message from Azure IoT hub to control the LED from cloud applications like Power Apps.

.NET core console Application:

The package System.IO.Ports supports to control serial ports which will be used to send message to Arduino board (A or B) to turn on or off the LED. Follow the below given steps to create the console application

  1. Use the same directory you have used to create the Arduino sketch. On the VS Code terminal window, enter the command dotnet new console to create a new console application
  2. Add the package System.IO.Ports using the nuget package manager plugin by CTRL+SHIFT+P > NuGet Package Manager: Add Package or enter the command on the terminal window dotnet add package System.IO.Ports –version 6.0.0-preview.1.21102.12
  3. Add the package Microsoft.Azure.Devices.Client to connect to client devices to Azure IoT Hub
  4. Use the Hostname of Azure IoT Hub, Device ID, Primary key of the Device copied earlier during the setup
    • private const string IotHubUri = “YourIoTHub.azure-devices.net”;
    • private const string deviceKey = “Your Key”;
    • private const string deviceId = “Your device ID”;
  5. In the code the
    • Method deviceClient.ReceiveAsync() receives a message from the IoT hub queue
    • Method Encoding.ASCII.GetString(receivedMessage.GetBytes()) reads the message
    • Method deviceClient.CompleteAsync(receivedMessage, _ct) deletes the message from the queue
  6. The following code establishes the connection on the serial port COM4
// Initialises the serial port communication on COM4
SerialPort = new SerialPort("COM4")
{
                BaudRate = 9600,
                Parity = Parity.None,
                StopBits = StopBits.One,
                DataBits = 8,
                Handshake = Handshake.None
};
// Subscribe to the event
SerialPort.DataReceived += SerialPortDataReceived;
// Now open the port.
SerialPort.Open();

With the help of the following method to Subscribe

static void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
{
 var serialPort = (SerialPort)sender;
 // Read the data that's in the serial buffer.
 var serialdata = serialPort.ReadExisting();
}
  1. The code SerialPort.Write(“A”) send the message to the Arduino Sketch.
  2. Now run the dotnet application using the command dotnet run. Now send a message from the Azure IoT explorer or from Azure portal IoT device explorer ON1 or Off1 to turn On/Off the LED connected to PIN 13
  1. The complete code is uploaded in my Github here.

Azure Function App – HTTP Trigger & Power Apps:

For the Azure function and Power Apps code, go through my other blog post

https://ashiqf.com/2020/11/01/learn-how-to-control-devices-from-powerapps-using-raspberry-pi/

Summary: On this post we have seen how to control the I/O pins of Arduino board with Azure IoT and integration to Power App.

Learn how to control devices from PowerApps using Raspberry Pi

I have recently purchased a Raspberry Pi 4 to explore IoT with Microsoft 365 platform. The Raspberry Pi is a low-cost credit-card sized computer which can be connected to a monitor, keyboard, mouse and to Internet via Wi-Fi or ethernet port. In addition, the Raspberry Pi has a 40 pin GPIO (General Purpose I/O) connector for us to connect sensors (Input) and to control devices (Output) through a relay. It enables people of all ages to explore computing and to learn how to program in languages like Scratch, Python, .NET core etc. One of the most popular operating system for the Raspberry Pi is Raspbian which is also the official one but there are also other operating systems like Ubuntu, Windows 10 IoT core (Not supported for Raspberry Pi 4). On this blog post, I will cover the different components used to integrate Raspberry Pi with Microsoft 365 service PowerApps & Azure services like Azure functions & Azure IoT hub to control devices. Find below the design and the different components used

  1. Environment Setup
    1. Raspberry Pi setup for IoT with .NET Core
    2. Visual Studio Code setup for remote development
  2. Azure IoT hub
  3. .NET Core Console Application
  4. Azure Function – HTTP Trigger
  5. Power Apps
    1. Custom Connector
    2. Canvas Apps

Environment Setup:

Raspbian OS is based on the Debain Operating System which has been optimized for Raspberry Pi hardware and it is the official one. You can find here some instructional videos on the following link to the install the OS on your Raspberry Pi

https://www.raspberrypi.org/help/noobs-setup/

If you have ordered a Raspberry Pi with a starter kit, most of the sellers would have loaded the Raspbian OS image on the SD card as a part of the kit. Once the OS is installed & configured, it is ready for use with the default username pi and the password is raspberry. Find below the schematic and the GPIO pin out diagram. On the sample code I have used Pin 17 and Pin 18 to control devices

Remote Tools:

There are tools to connect raspberry Pi remotely from your Windows client. Software xrdp provides a graphical interface for the users to remotely connect Raspberry Pi using Microsoft’s RDP mstsc.exe. Follow along this blogpost to set this up on the Raspberry Pi to enable remote connectivity. You can also use PuTTY a SSH tool to remotely connect with Raspberry Pi device. To know the IP address of the device, login to the Router to which the raspberry pi is connected or through the command hostname -I on the command line. To use PuTTY client & VS Code remote development plugin, SSH must be enabled on the Raspberry Pi OS. By default, it is disabled to enable follow the below steps

  1. Launch Raspberry Pi Configuration from the Preferences menu.
  2. Navigate to the Interfaces tab.
  3. Select Enabled next to SSH.
  4. Click OK

Raspberry Pi Setup for IoT with .NET Core:

.NET core is an open source development platform maintained by Microsoft and .NET community on Github. I have chosen .Net core and the programming language C# in which I am comfortable with. There are also python libraries to control GPIO pins in Raspberry Pi. To use .NET core IoT libraries install .NET core 3.1 on Raspberry Pi. Follow the instructions below to install .NET core

  1. Copy the Direct link of the .NET core SDK from the link for Linux ARM32. Based on information gathered from few blogposts .NET core is supported for ARM64 though Raspberry Pi is 64 bit. Get the latest link from https://dotnet.microsoft.com/download/dotnet-core/3.1
  2. Open a Terminal window in Raspberry Pi. Enter the following command to download the .Net core sdk binary

wget https://download.visualstudio.microsoft.com/download/pr/8a2da583-cac8-4490-bcca-2a3667d51142/6a0f7fb4b678904cdb79f3cd4d4767d5/dotnet-sdk-3.1.403-linux-arm.tar.gz

  1. Update the Raspbian OS by entering the following command

sudo apt-get update
sudo apt-get upgrade

  1. Run the following command to make the .NET SDK commands available for the terminal session

mkdir -p $HOME/dotnet && tar zxf dotnet-sdk-3.1.403-linux-arm.tar.gz -C $HOME/dotnet
export DOTNET_ROOT=$HOME/dotnet
export PATH=$PATH:$HOME/dotnet

  1. To make it available permanently on all the sessions. Run the following command to open the .profile file to save the information

sudo nano .profile

  1. Add the following lines at the end of the file by scrolling and then save it (CTRL+S) and then exit using (CTRL+X)

# set .NET Core SDK and Runtime path
export DOTNET_ROOT=$HOME/dotnet
export PATH=$PATH:$HOME/dotnet

  1. Run the command dotnet –info to know the version of the .Net core

Visual Studio Code setup for remote development:

You can develop applications remotely on a Raspberry Pi device using VS Code with the help of a plugin Remote Development which uses SSH to connect. After the plugin in installed, perform the following steps to remotely connect the Raspberry Pi device

  1. Have the IP address of the Raspberry Device ready which will be used to add a SSH host. Use the command hostname -I on the Raspberry Pi’s terminal window will reveal the IP address
  2. Go to the VS code and press CTRL+SHIFT+P together and type Remote-SSH: Connect to Host & select
  1. Click Add New SSH Host
  2. Type ssh pi@x.x.x.x -A and then press Enter. X.X.X.X is the IP address of your raspberry device and pi is the username (Default)
  3. Select the configuration file. I have used default, %USERPROFILE%\.ssh\config on Windows 10
  1. Host will be added. You are now ready to connect remotely provided the SSH is enabled on the Raspberry Pi.

Azure IoT Hub:

IoT hub is a managed service hosted in cloud that acts as a central message hub for bi-directional communication from the device to the cloud and the cloud to the device. There is a also a Free-Tier limited to one per subscription which can add up to 500 devices and 8000 msgs/day as of today based on the Pricing calculator. Go through the Microsoft documentation about IoT hub. Create a IoT Hub for us to send a message to the Raspberry Pi device for us control the device as per the instruction given in this article. After the IoT hub is created

  1. A device must be registered with your IoT hub before it can connect. There are different ways to register a device like using Azure Cloud shell, in this case we will use portal. Click IoT Devices under the Explorers blade on the IoT hub and click on + New, enter the Device ID and click save.
  1. Copy the Primary key of the registered device
  2. Copy the Hostname from the IoT Hub Overview blade
  3. These values will be used later in the .NET console application

Device Explorer:

It is a tool which helps you to manage devices by connecting to the IoT hub you have just created, it can be also done from the Azure portal, Azure Cli etc. It is very easy to connect to the IoT hub using the connection string. Download the device explorer from the https://aka.ms/aziotdevexp

To get the connection string, click Shared access policies under Settings blade and click iothubowner policy. Copy the Connection string-primary key and paste it on the Configuration section of the Device explorer and click Update as shown below

To send a message to the device click the tab Messages to Device and for registering new devices click Management.

.NET Core Console Application:

The Microsoft .NET core team also has a .NET core IoT library. The package System.Device.Gpio supports GPIO pins to control sensors (Pin Mode: Input) and devices like relay, LED’s (Pin Mode: Output). In this case we will be using the Pin no 17 & 18 to turn on or off a LED with Pin mode set as Output.

Setup for controlling devices:

To control a LED, connect a 220 ohm resistor to the long lead and the other end to a GPIO Pin (17 & 18) & the short LED lead to any one of the GPIO Ground.

In my setup I have used a Breadboard, GPIO Extension board & GPIO extension cable. GPIO Pin’s 17 & 18 are used, there are many other pins for us to use. Look at the GPIO pin schematics for more details on the pins. There are also relays designed for Raspberry Pi which helps controlling real devices, there are different relays module (4 channel, 8 channel, 10 channel etc) available in the market.

Connect Remotely to Raspberry Pi using VS code:

Connect the VS code to the Raspberry Pi using SSH by using keyboard shortcut CTRL+SHIFT+P and click Remote-SSH: Connect to Host and click the IP of the raspberry PI or the hostname based on the VS code setup (SSH Host) we have done earlier

After the password (Default: raspberry) is entered. If you see on the left bottom corner of the VS code with SSH: IP Address or host name, it is then successfully connected

In the terminal window you can enter all bash commands in context of Raspberry Pi.

VS Code Plugin:

To add a package from VS code to the Console app project install a plugin Nuget Packet manager. You can also use the CLI command on the terminal window to add the package but the plugin will help us to add different packages using the UI. All the packages will be installed on Raspberry Pi device as shown below

I also recommend you install to C# and CodeTour extensions (code walkthrough for the code I’ve used for this sample project).

Create the first Console Application to control a LED:

Follow the below steps to control a LED connected to GPIO PIN 22 using the .NET IoT package System.Device.Gpio

  1. On the VS Code terminal window, enter the command dotnet new console to create a new console application
  2. Add the package System.Device.Gpio using the nuget package manager plugin by CTRL+SHIFT+P > NuGet Package Manager: Add Package
  3. Add the following code to the Program.cs file
using System;
using System.Device.Gpio;

namespace DemoProject-GPIOControl
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Turning on Light from Pin 22");
            using var controller = new GpioController();
            controller.OpenPin(22, PinMode.Output);
            controller.Write(22, PinValue.High);
            Console.ReadKey();

        }
    }
}

  1. Run the command on the Terminal window dotnet run. There will be an unauthorized exception as below
Unhandled exception. System.UnauthorizedAccessException: Setting a mode to a pin requires root permissions.
 ---> System.UnauthorizedAccessException: Access to the path '/sys/class/gpio/gpio17/direction' is denied.
 ---> System.IO.IOException: Permission denied
  1. Enter the following command on the terminal window to provide root permission for Pin no 22: /usr/bin/gpio export 22 out. This command has to be executed everytime you restart the Raspberry Pi unless you provide root permissions to the account which could be done by setting a value on the root configuration file.
  2. Now run the dotnet console app using the command dotnet run which will turn on the LED light connected to PIN 22. The output voltage on PIN will be 3.2 volt if the pinvalue is set to High and will be Zero if its set to Low.
  3. Code controller.Write(22, PinValue.Low); will turn off the light
  4. To remotely debug on the Linux Arm, follow the instruction on this article.
  5. To disconnect in VS code, click File > Close Remote Connection

Console application connected to Azure IoT hub:

There is a .NET SDK for Microsoft Azure IoT to enable development using .NET and we will be using the package Microsoft.Azure.Devices.Client to connect client devices to Azure IoT hub. The other package used in this project is System.Devices.Gpio.

Use the Hostname of Azure IoT Hub, Device ID, Primary key of the Device copied earlier during the setup and the GPIO pins as shown below

private const string IotHubUri = “YourIoTHub.azure-devices.net”;
private const string deviceKey = “Your Key”;
private const string deviceId = “Your device ID”;
private const int Pin1 = 17;
private const int Pin2 = 18;

In the code the

  • Method deviceClient.ReceiveAsync() receives a message from the IoT hub queue
  • Method Encoding.ASCII.GetString(receivedMessage.GetBytes()) reads the message
  • Method deviceClient.CompleteAsync(receivedMessage, _ct) deletes the message from the queue

Do not forget to run the commands /usr/bin/gpio export 17 out and /usr/bin/gpio export 18 out based on the pins you are controlling. Then run the dotnet application using the command dotnet run. Now send a message from the Device explorer or from Azure portal IoT device explorer ON1 or Off1 to turn On/Off the LED connected to PIN 17 and ON2 or Off2 to turn On/Off the LED connected to PIN 18.

On this example we have used Cloud to device messages which sends a one way notification but you can also use Direct Methods & Device Twin to control devices, go through the following documentation from Microsoft with guidance to send cloud to device communications using different methods

https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-c2d-guidance

Find here the sample of the console application from GitHub. Now the console application is ready, let us create the Azure Function app to use it in the PowerApps.

Azure Function App – HTTP Trigger:

I’ve used a Consumption plan Function app which gets triggered on a HTTP request to send a message to IoT hub registered device using the method ServiceClient.SendAsync from the package Microsoft.Azure.Devices to send a one way notification to the registered Raspberry Pi device. The message will be sent to the device on the HTTP request as query string (Parameter name: name)

  1. Create a Function App from the Visual Studio 2019, I’ve used VS 2019 but you can also use VS Code
  2. Add the HTTP trigger with authorization Level of the Function App as Function
  3. Add the Nuget Package Microsoft.Azure.Devices
  4. Have the connection string handy for the iothubowner policy used on the device explorer.
  5. Copy the following Code:
 using System;
 using System.IO;
 using System.Threading.Tasks;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.Azure.WebJobs;
 using Microsoft.Azure.WebJobs.Extensions.Http;
 using Microsoft.AspNetCore.Http;
 using Microsoft.Extensions.Logging;
 using Newtonsoft.Json;
 using Microsoft.Azure.Devices;
 using System.Text;
 using System.Net;
  
 namespace FunctionApp_IoT
 {
     public static class Function1
     {
         static ServiceClient serviceClient;
         static string connectionString = "HostName=YourIoTHub-env.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=Yourkey";
         static string targetDevice = "Your Device ID";
         [FunctionName("Function1")]
         public static IActionResult Run(
             [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
             ILogger log)
         {
             log.LogInformation("C# HTTP trigger function processed a request.");
  
             string name = req.Query["name"];
  
             serviceClient = ServiceClient.CreateFromConnectionString(connectionString);
  
             SendCloudToDeviceMessageAsync(name).Wait();
             
             return new OkObjectResult(new { status = "Light turned On or Off" });
             
         }
         private async static Task SendCloudToDeviceMessageAsync(string condition)
         {
             var commandMessage = new
              Message(Encoding.ASCII.GetBytes(condition));
             await serviceClient.SendAsync(targetDevice, commandMessage);
         }
     }
  
 } 
  1. Publish the function app to Azure. Test it by sending HTTP requests using Postman tool or browser. The function API is ready, we are now ready to call the function in PowerApps
  2. Function app URL will be https://yourfunctionappsubdomain.azurewebsites.net/api/Function1?code=authorizationcode. Since I’ve chosen authorization level as function there will be a code

PowerApps:

So far we have progressed till a HTTP API endpoint using serverless which sends a message to the Raspberry Pi through the IoT hub, if we have to call this API on PowerApps we will have to create a custom connector which allows you to connect to any RESTful API endpoint. Bear in mind that to use a PowerApp which has a custom connector, the users should have a premium license.

Custom Connector:

Let us go ahead and create the custom connector, you can find here on the GitHub repo for the swagger definition file for creating the custom connector. Download the file and go to your Power Platform environment and click to the Custom Connectors link under Data.

Click the Import an OpenAPI file under New custom connector and import the Swagger definition file you have downloaded from the repo

Once it is imported, change the host on the General tab based on the function app URL and the Security will have authentication type as API Key and on the Definition tab there will be one action which be called from the PowerApps to control devices. After the settings are configured you can create the connector by clicking the link Create connector. You can test the connector by creating the connection by passing in the Code parameter of the function app and pass the message to test the operation. Make sure the console app is running in order to receive the message & to turn on/off the device.

PowerApps Canvas App:

Once the custom connector is created you can use it on the PowerApps canvas app by creating a connection to the connector like below

After the connection is created and added on the app, you can use on the PowerApps controls like Toggle, button etc to turn on/off the devices using the code ‘IOT-ControlDevice’.ControlDevice({name: “on1”}) / ‘IOT-ControlDevice’.ControlDevice({name: “off1”}). If a toggle control is used, the code will be something like this

If(
    ToggleL1.Value = true,
    'IOT-ControlDevice'.ControlDevice({name: "on1"}),
    'IOT-ControlDevice'.ControlDevice({name: "off1"})
)

Voila, now you were able to control devices from PowerApps.

Summary: On this post we have seen how to integrate Azure IoT with PowerApps and to control devices through a PowerApps. This is just a sample, you can extend this example based on your needs. Hope you have found this informational & interesting. Let me know any feedback or comments on the comment section below

Reference:

https://www.hanselman.com/blog/visual-studio-code-remote-development-over-ssh-to-a-raspberry-pi-is-butter

https://edi.wang/post/2019/10/6/azure-remote-controlled-light-with-net-core-30-on-raspberry-pi

https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-csharp-csharp-c2d

https://github.com/Microsoft/vscode-azure-iot-toolkit/wiki/Quickstart-.NET

https://docs.microsoft.com/en-us/connectors/custom-connectors/define-blank

https://jussiroine.com/2020/06/developing-remotely-on-raspberry-pi-4-and-linux-using-visual-studio-code

How to use a sample PCF component in your Power Apps

If you are PowerApps developer and wanted to extend the capabilities by bringing in third party or community driven PCF (Power Apps Component Framework) components, you can find lot of samples from the Power Apps community website PCF.gallery, Power Apps Community and from Microsoft for Model driven and Canvas apps.

Sample components from Microsoft

If you are new to component framework, I recommend going through the documentation from the following link:

https://aka.ms/pcfdocs

The PowerApps component framework enables the developers to create code components for model-driven and canvas apps. I have recently used a control from the PCF gallery community site, let’s see how to package and deploy a sample control to the Power Apps environment and then consume it on your Canvas app. There are two methods to deploy a code component:

  1. Import the solution in to CDS
  2. Power Apps CLI

To follow along the blog post, have the following available and installed on your environment

  1. Install Power Apps CLI and Node.js
  2. Access to Power Apps CDS Environment
  3. Developer Command prompt for Visual Studio 2017 or 2019
  4. Power Platform Administrator
  5. Enabling the PowerApps component framework on canvas applications

Method 1: Import the solution in to CDS:

For this post, I have chosen the React Face pile component from Microsoft Power Apps samples github repo. Follow the steps to create the solution ZIP file to be imported on the solutions gallery. If you already have the solution package, directly proceed to the Step 10.

Step 1: Download as a ZIP package and extract to a folder on your computer or git clone from the Microsoft Github repository. I have downloaded on C:\ PCF\Controls\sample-controls

git clone https://github.com/microsoft/PowerApps-Samples.git

Step 2: Open the Developer command prompt and navigate to the folder on the computer where you have downloaded the React Face pile component using the cd folder-path-react-facepile-component command e.g folder-path: C:\ PCF\Controls\sample-controls\PowerApps-Samples\component-framework\TS_ReactStandardControl

Step 3: Install all the required dependencies by running the command

npm install

Step 4: Create a folder (e.g ReactStandardControlSolution) on the root of the React face pile component project (e.g C:\ PCF\Controls\sample-controls\PowerApps-Samples\component-framework\TS_ReactStandardControl) either manually or using the command mkdir ReactStandardControlSolution

Step 5: Navigate to the created folder by using the command cd ReactStandardControlSolution

On your command prompt, you should now be on e.g C:\ PCF\Controls\sample-controls\PowerApps-Samples\component-framework\TS_ReactStandardControl\ ReactStandardControlSolution

Step 6: Create a new solution project using the following command. The solution project is used for bundling the code component into a solution zip file that is used for importing into Common Data Service.

pac solution init --publisher-name developer --publisher-prefix dev

The Published-name and publisher-prefix values should be unique to your environment

Step 7: Add the reference using the command shown below. This reference informs the solution project about which code components should be added during the build. The path should to the root of the downloaded react face pile component and not to the newly created solution folder

pac solution add-reference --path C:\ PCF\Controls\sample-controls\PowerApps-Samples\component-framework\TS_ReactStandardControl\

Step 8: To generate the ZIP package, enter the following command

msbuild /t:build /restore

Step 9: The generated ZIP file will be available on \bin\debug\ folder once the build is successful

Note: Make sure there is no spaces on the folders you create to avoid deployment issues

Reference:

https://docs.microsoft.com/en-us/powerapps/developer/component-framework/import-custom-controls

https://docs.microsoft.com/en-us/powerapps/developer/component-framework/use-sample-components

Step 10: Now it’s time to import the solution to the solutions gallery by signing into Power Apps and select Solutions from the left navigation. On the command bar, select import and then browse to the Zip file solution created from the above steps. After the solution is imported successfully, the solution is available to use in Power Apps canvas and Model driven apps.

Reference: https://docs.microsoft.com/en-us/powerapps/maker/common-data-service/import-update-export-solutions

Let’s see the next method to deploy the code component

Method 2: Power Apps CLI:

In the previous method Power Apps CLI was used to generate the solution package and then the solution was imported to the gallery, on this method the code component will be directly pushed to the CDS service instance using the CLI push command.

Step 1: Create an authentication profile to the CDS instance by executing the following command on a command prompt, it’s not necessary to open a VS command prompt.

pac auth create --url https://xyz.crm.dynamics.com

To get the url sign into Power Apps and select your environment which has CDS in the top right corner and the environment you are planning to deploy the code component. Select the settings button in the top right corner and select Advanced settings. Now copy the URL from the webbrowser which should look like below

https://orgchangedhere.crm4.dynamics.com/main.aspx?settingsonly=true

The URL is https://orgchangedhere.crm4.dynamics.com/

Once your profile is successfully created, you should see the following message on your command prompt

Step 2: Navigate to the root folder of the custom component project using the cd folderpath command which has the .pcfproj file (e.g C:\ PCF\Controls\sample-controls\PowerApps-Samples\component-framework\TS_ReactStandardControl)

Step 3: Install all the required dependencies by running the command

npm install

Step 4: Run the following command to push the code components to the CDS instance

pac pcf push --publisher-prefix contoso

Note: The publisher prefix that you use with the push command should match the publisher prefix of your solution in which the components will be included.

Reference:

https://docs.microsoft.com/en-us/powerapps/developer/component-framework/import-custom-controls#deploying-code-components

List of common PAC commands

https://docs.microsoft.com/en-us/powerapps/developer/common-data-service/view-download-developer-resources

The component is now ready to be used in the Canvas or a Model driven app after the code deployment using Method 1 or Method 2.

To add the component in a Canvas App:

Follow along then the documentation from Microsoft

https://docs.microsoft.com/en-us/powerapps/developer/component-framework/component-framework-for-canvas-apps#add-components-to-a-canvas-app

Find below the sample controls I’ve added on the Power App canvas app

To add the component in a Model Driven app:

https://docs.microsoft.com/en-us/powerapps/developer/component-framework/add-custom-controls-to-a-field-or-entity

Summary: You can also create a custom component from scratch or extend the functionality from the available samples based on your needs. Hope you have found this informational & helpful in some way. Let me know any feedbacks or comments on the comment section below

Multiple ways to access your On-premise data in Microsoft 365 and Azure

If your organization is using a hybrid cloud environment, this post will shed some light to integrate on-premise resources with Microsoft 365 & Azure services. Hybrid integration platforms allows enterprises to better integrate services and applications in hybrid environments (on-premise and cloud). In this blog post, I will write about the different services & tools available with in Microsoft Cloud which allows you to connect or expose your On-premises data or application in Office 365. There are still many enterprise organizations on Hybrid mode due to various factors. It can be a challenging task to integrate your on-premises network but with right tools & services in Office 365 & Azure it can be easier. Find below the high-level overview & some references on how to

  1. Access your on-premise data in Power Platform & Azure Apps (Logic Apps, Analysis Services & Azure Data factory)
  2. Programmatically access your on-premise resources in your Azure Function app
  3. Access on-premise resources in Azure automation account
  4. Expose your on-premise Application or an existing WEB API in Office 365 cloud

Access on-premise data in Power Platform & Azure Apps (Logic Apps, Analysis Services & Azure Data factory):

The on-premises data gateway allows you to connect to your on-premises data (data that isn’t in the cloud) with several Microsoft cloud services like Power BI, Power Apps, Power Automate, Azure Analysis Services, and Azure Logic Apps. A single gateway can be used to connect multiple on premise applications with different Office 365 applications at the same time.

At the time of writing, with a gateway you can connect to the following on-premises data over these connections:

  • SharePoint
  • SQL Server
  • Oracle
  • Informix
  • Filesystem
  • DB2

To install a gateway, follow the steps outlined in MS documentation Install an on-premises data gateway. Install the gateway in standard mode because the on-premises data gateway (personal mode) is available only for Power BI.

Once the data gateway is installed & configured its ready to be used in the Power platform applications.

  1. PowerApps
  2. PowerAutomate
  3. PowerBI

The other catch the gateway is not available for the users with Power Automate/Apps use rights within Office 365 licenses as per the Licensing overview documentation for the Power Platform. Data gateways can be managed from the Power Platform Admin center.

Shane Young has recorded some excellent videos on this topic for PowerApps & PowerBI.

To use in

  1. Azure Logic Apps
  2. Azure Analysis service
  3. Azure Data Factory

create a Data Gateway resource in Azure.

High Availability data gateway setup:

You can use data gateway clusters (multiple gateway installations) using the standard mode of installation to setup a high availability environment, to avoid single points of failure and to load balance traffic across gateways in the group.

No need to worry about the security of the date since all the data which travels through the gateway is encrypted.

Data gateway architecture:

Find below the architecture diagram from Microsoft on how the gateway works

I recommend you to go through On-premises data gateway FAQ.

Integration Service Environment:

As per the definition from Microsoft an integration service environment is a fully isolated and dedicated environment for all enterprise-scale integration needs. When you create a new integration service environment, it’s injected into your Azure Virtual Network allowing you to deploy Logic Apps as a service in your VNET. The private instance uses dedicated resources such as storage and runs separately from the public global Logic Apps service. Once this logic apps instance is deployed on to your Azure VNET, you can access your On-premise data resources in the private instance of your Logic Apps using

  • HTTP action
  • ISE-labeled connector for that system
  • Custom connector

For the pricing of ISE, refer this link.

Programmatically access your on-premise resources in your Azure Function app

As you all know Azure Functions helps in building functions in the cloud using serverless architecture with the consumption-based plan. This model lets the developer focus on the functionality rather than on infrastructure provisioning and maintenance. Okay let’s not more talk about what a Function app can do but let us see on how to connect to your on-premise resources (SQL, Biztalk etc) within your function.

During the creation of a Function app in Azure, you can choose the hosting plan type to be

  • Consumption (Serverless)
  • Premium
  • App Service plan

Consumption based plan is not supported for the on-premise integration so while creating the app the hosting plan has to either premium or app service based plan & the Operating system has to to be Windows. On-premise resources can be accessed using

  1. Hybrid Connections
  2. VNet Integration

Hybrid Connections:

Hybrid Connections can be used to access application resources in private networks which can be on-premise. Once the Function app resource is created in Azure, go to Networking section of the App service to setup & configure. Go through the documentation from Microsoft for the detailed instructions to set this up.

How it works:

The Azure Hybrid Connection represents a connection between Azure App Service and TCP endpoint (host and port) of an on-premise system. On the diagram below Azure Service Bus Relay receives two encrypted outbound connections. One from the side of Azure App Service (Web App in our case) and another from the Hybrid Connection Manager (HCM). HCM is a program that must be installed on your on-premise system. It takes care of the integrations between the on-premise service (SQL in this case) with Azure Service Bus Relay.

Once the setup is done, you can create a connection string in Appsettings.json file or from Azure function app interface of your function app. After this you can access the data in your function app code.

I’ve found a couple of interesting blogs about this setup.

VNet Integration:

In the Networking features of the App service, you can add an existing VNET. An Azure Virtual Network (VNet) is a representation of your own network (private) in the cloud. It is a logical isolation of the Azure cloud dedicated to your subscription.

In Azure Vnet you can connect an on-premise network to a Microsoft VNet, this has been documented from Microsoft here. Once there is integration between your Azure Vnet & on-premise network and the VNet is setup on your function app you are set to access on-premise resources in your function app.

Access on-premise resources in Azure automation account:

Azure Automation is a service in Azure that allows you to automate your Azure management tasks and to orchestrate actions across external systems from right within Azure. Hybrid runbook worker feature allows you to access on-premise resources easily. The following diagram from Microsoft explains on how this feature works

I’ve written a blogpost recently about this feature for automating on-premise active directory.

Expose your on-premise Application or an existing WEB API in Office 365 cloud:

Azure Active Directory’s Application Proxy provides secure remote access to on-premises web applications (SharePoint, intranet website etc). Besides secure remote access, you have the option of configuring single sign-on. It allows the users to access on-premise applications the same way they access M365 applications like SharePoint Online, PowerApp, Outlook etc. To use Azure AD Application Proxy, you must have an Azure AD Premium P1 or P2 license.

How it works:

The following diagram from Microsoft documentation shows how Azure AD and Application Proxy works

Find below documentations on how to

  1. Add an on-premises application for remote access through Application Proxy in Azure Active Directory
  2. Secure access to on-premises APIs with Azure AD Application Proxy
  3. Use Azure AD Application Proxy to publish on-premises apps for remote users
  4. Deploy Azure AD Application Proxy for secure access to internal applications in an Azure AD Domain Services managed domain

Once the connector service is installed from your Azure AD application proxy, you can add an on-premise app as shown below

The above step will register an application with App registrations.

Summary: I’ve given some overview about the different services & tools to connect & integrate on-premise resources with Microsoft cloud. Hope you like this post & find it useful. Let me know any feedback or comments on the comment section below