Send email from a common mailbox in Power Automate using Microsoft Teams email address or Shared Mailbox

Power Automate is widely used to automate many business processes and Email is one of most widely used action to send out notifications. Having said that, there will be definitely request to send the email from a generic address instead of the flow creator email address or the email action’s connection owner email address as shown below:

By default, the from Address of the mail generated from Power Automate uses the Flow creator email address as shown above under My connections. To send an email from generic email address, you can

  1. Create a Shared mailbox in exchange online (No license required) and grant access to the flow creator and then use any of the following action in the flow
    • Send an email
    • Send an email from a shared mailbox
  2. Use an existing Microsoft 365 group in
    • Send an email

Setup Shared Mailbox in Exchange Online & Power Automate email actions:

Find steps below to create a shared mailbox in Exchange online & provide delegated permission (Send as) to the flow creator.

  1. Sign into Exchange Admin center. Go to Recipients > Shared and then click New Add Icon. Enter the Name, email address & domain for the shared mailbox and then click Create.
  1. Open the newly created mailbox which opens the mailbox details pane as shown below. Click Manage mailbox delegation.
  1. To use the action Send an email from a Shared Mailbox in the flow
    • Grant Read and manage  and Send As permissions by clicking Edit button>Add permissions and then select the user (Flow Creator) you want to grant permissions to.
  1. Find the flow action for reference
  1. To use the action Send an email in the flow. Grant Send As permissions by clicking Edit button>Add permissions and then select the user (Flow Creator) you want to grant permissions to.
  1. It takes approximately an hour for the permissions to be reflected so as to use in the Power Automate action.

Microsoft 365 group in Send an Email action:

If you have a Microsoft 365 group or a Microsoft Team, you can use the mailbox associated to group in Microsoft Flow for sending the email (Send as). Microsoft Teams creates a Microsoft 365 group whenever a team is created. Let us see how to enable a M365 group in order to use in Power Automate action Send an email action by providing Send as permissions to the flow creator or the email action’s connection owner. Find steps below to grant Send as permissions

  1. Sign into Exchange Admin center. Go to Recipients > Groups and then click the Microsoft 365 group you wish to be used in the flow. Go to Settings>Click Edit manage delegates
  1. Add the Flow creator email address and grant Send as permission
  1. Save changes

Tip:

By default, the Microsoft 365 group are not capable to receiving emails from external senders. To enable it Check the box as shown on the above picture “Allow External senders to email this group”

If the permissions are not set right, you might get any of the following message in the flow

  • You are not authorized to send mail on behalf of the specified sending account
  • Specified folder not found. The error could potentially be caused by lack of access permissions. Please verify that you have full access to the mailbox

Summary: To send an email from third party application you can use the trigger “When a HTTP request is received” with the email action. This trigger generates an anonymous API endpoint which could be used on applications to trigger the flow. Hope you have found this informational.

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.

How to create & setup Dynamic Microsoft 365 Group or Distribution list based on the user’s domain for Teams, Yammer and Exchange

There are many organizations maintaining multiple domains on a single Microsoft 365 or Azure AD tenant, in those cases there might be a need to create dynamic Microsoft 365 groups, security groups & distributions list based on the user’s domain to manage the group’s membership. On this blogpost, let us see how to

  1. Create Dynamic Microsoft 365 group based on the user’s domain for Teams & Yammer
  2. Create a Dynamic distribution list based on user’s domain in Exchange online

To begin with let us see some basics of a Dynamic group. The membership of a dynamic group will automatically update as people join, leave, or move within the organization whenever the user’s Azure Active Directory attributes are changed. In simple terms, rules determines the group membership. The users will be added or removed automatically as and when the user attributes change or users join and leave the tenant which reduces the administrative effort of adding and removing users from a group. Dynamic group can be created based on variety of attributes including role, location, department etc.

Create Dynamic Microsoft 365 group based on the user’s domain for Teams & Yammer

Microsoft Teams and Yammer (Microsoft 365 Connected) supports dynamic membership. It enables the membership of Team or Yammer to be defined by one or more rules that check for certain attributes in Azure AD. Microsoft Teams & Yammer creates a Microsoft 365 group in Azure AD. For this post, the membership rule will be simple one which is based on the user’s domain and country. You can also have a complex rule involving multiple Azure AD attributes like Title, Geography, Department etc. Before we proceed further, there are some pre-requisite & facts to be considered before creating a dynamic group.

  • User Administrator or Global administrator role in Azure AD
  • Users you foresee to be part of a dynamic group membership rule should have an Azure AD premium License P1 or P2
    • Microsoft 365 E3, E5, Front line workers MF3 & MF1 has Azure AD premium 1 service which should suffice.
  • An Azure AD organization can have maximum of 5000 dynamic groups.
  • Any number of Azure AD resources can be members of a single group.

Dynamic Membership based on Domain for Teams:

To create a Dynamic membership MS team, create a Microsoft 365 group first with Dynamic membership in Azure Active directory. You can create a dynamic group from PowerShell but here I will be using Azure Ad GUI to create the dynamic Microsoft 365 group with rule to add users based on their domain and country. I have added a domain m365pal.me to my Azure AD tenant which I will be using here for this example.

  1. Sign in to Azure AD Admin center with administrator role in the Azure AD organization
  2. Click Groups and then click + New Group
  3. Select the Group type as Microsoft 365. Dynamic membership will also work with Security group but for team it should be Microsoft 365 group.
  4. Enter the Group Name & Group email address
  5. Select the Membership type as Dynamic User
  6. Select the Owner and then
  7. Under Dynamic user members section, click Add dynamic query
  8. In Dynamic membership rules panel, add rule to define membership based on users domain & country
    • First rule for Domain: under Property column select userPrinicipalName, Operator should be Contains and the Value should be the domain name in format “@yourdomain.com”. This rule will add all users with the UPN user@yourdomain.com. Now click + Add expression to add the second rule
    • Second rule for country: under Property column select country, Operator should be  Equals and the value should be the country name.
  1. You can also validate the rules by clicking the link Validate Rules and then by adding users to check if the user satisfies the rule
  2. Click Save. This is how it should look like
  1. Click Create.
  2. After waiting for couple of minutes, check the group membership. Please find below screenshot for the group which has two members satisfying the condition. You can also notice the + Add members link is disabled since the group is dynamic membership and not assigned. To modify the rules, click the link Dynamic membership rules link.
  1. Now we are ready to create the MS Teams, go to https://teams.microsoft.com/ and then click Join or create a team at the left bottom corner and then Click Create a team
  2. Click From a group or team and then click Microsoft 365 group
  3. Now select the group you have created in Azure AD and then click Create.
  1. The team is now created, you can find the team on the list. Check the membership of the team which will have the two users satisfying the rules and the owner of the group. One more thing to notice here is the message which says The membership settings prevents you from adding or removing members.
  1. Voila! Dynamic Microsoft team is now created & setup.

If you have an existing team to be converted to a Dynamic team, find the Microsoft 365 group in Azure AD for the Team you wish to convert and then update the membership status from Assigned to Dynamic user with membership rules

Dynamic Membership based on Domain for Yammer:

Yammer (Microsoft 365 Connected) also supports dynamic membership. Find the steps below to create a dynamic yammer group based on the user’s domain. Find the steps below

  1. Sign in to https://yammer.com/ with your organizational ID
  2. Click Create a Community and then Enter the name of the Community
  3. Click the button Create
  1. Now sign in to Azure AD Admin center to the update the membership settings of the Microsoft 365 group connected to the Yammer community. Find the yammer group and then click
  1. Click Properties under the Manage blade and then change the membership type from Assigned to Dynamic user
  1. After updating the membership type to Dynamic user. You will now have option to enter the dynamic query. Click dynamic query
  1. In Dynamic membership rules panel, add rule to define membership based on users domain
    • Rule for Domain: under Property column select userPrinicipalName, Operator should be Contains and the Value should be the domain name in format “@yourdomain.com”. This rule will add all users with the UPN user@yourdomain.com. Now click + Add expression to add rules based on need
    • Click Save
  1. Click Save. Wait for couple of minutes for the membership to be updated.
  2. Now check the Yammer group in Yammer.com for the membership status. Please find below screenshot for your reference which will not have the + icon on the highlighted members section for adding users since this is now a dynamic yammer group

Also, Microsoft 365 group/Security group can be used for different use cases. See some sample use cases below

  • You can use to target SharePoint page/news to specific audience with the help of Microsoft 365 group or Security group. Will it not be more powerful if you use dynamic groups within a SharePoint to target content certain group of audience!
  • Assign Microsoft Licenses to users based on Dynamic Group.
  • Grant access to an App (PowerApps etc) using the dynamic group targeting certain departments, geographies etc

Reference:

https://docs.microsoft.com/en-us/azure/active-directory/enterprise-users/groups-create-rule

https://docs.microsoft.com/en-us/azure/active-directory/enterprise-users/groups-dynamic-membership

https://docs.microsoft.com/en-us/microsoftteams/dynamic-memberships

https://docs.microsoft.com/en-us/yammer/manage-yammer-groups/create-a-dynamic-group

https://docs.microsoft.com/en-us/yammer/manage-yammer-groups/yammer-and-office-365-groups

https://docs.microsoft.com/en-us/azure/active-directory/enterprise-users/directory-service-limits-restrictions

Create a Dynamic distribution list based on user’s domain in Exchange online:

Dynamic distribution groups are mail-enabled Active Directory group to distribute email messages to all its members within a Microsoft Exchange organization. Unlike regular distribution lists that contain a defined set of members, the membership list for dynamic distribution groups is calculated each time a message is sent to the group, based on the filters and conditions that you define in the group. You can create a Dynamic Distribution list from Exchange Admin center as shown below but the options to write advanced filter conditions or rules are limited so PowerShell is preferred.

Dynamic Distribution list from PowerShell:

Make sure the Exchange online PowerShell module is installed. There are some limitations to create a recipient filter (Rules) that worked based on user’s domain with the operator like or contains but there is a workaround. The filter works based on the exchange property WindowsEmailAddress which is always the primary SMTP address, you can also consider using the property WindowsLiveID. Follow the steps below to create a Dynamic Distribution list based on user’s domain

  1. Load the module by the running the command Import-Module ExchangeOnlineManagement
  2. Connect to the Exchange online PowerShell in Microsoft 365
Connect-ExchangeOnline -UserPrincipalName userId@domain.com -ShowProgress $true
  1. After authentication, enter the following command to create the Dynamic DL based on User’s domain. I have added the RecipientTypeDetails in the RecipientFilter to apply the filter rule only to user mailboxes which excludes the SharedMailboxes
New-DynamicDistributionGroup -Name "All Users - M365PAL DL" -RecipientFilter "(RecipientTypeDetails -eq 'UserMailbox') -and (WindowsEmailAddress -eq '*@yourdomain.com')"
  1. You can also validate the users using the following script
Get-Recipient -RecipientPreviewFilter (Get-DynamicDistributionGroup "All Users - M365PAL DL").RecipientFilter
  1. To view the attributes to be used in the recipient filter enter the following command
Get-User -Identity user@yourdomain.com | Format-List

Reference:

https://docs.microsoft.com/en-us/exchange/recipients/dynamic-distribution-groups/dynamic-distribution-groups

https://docs.microsoft.com/en-us/powershell/module/exchange/get-user

https://docs.microsoft.com/en-us/exchange/recipients/dynamic-distribution-groups/view-dynamic-distribution-group-members

Summary: On this post we have seen how to create dynamic groups based on user’s domain. Do some planning to start using the dynamic groups which will help reduce lot of administrative overhead. Hope you have found this informational & helpful. Let me know any feedback or comments on the comment section below

Find the Microsoft 365 account license and service details for a user using Microsoft Graph API

Is there a need to find the type of Microsoft 365 license and the different services assigned for a user to troubleshoot an issue related to the service they have been assigned? You have come to the right place, this post will help you find the details using the Microsoft Graph API endpoints. In Microsoft 365, licenses from licensing plans also known as SKUs give users access to the Microsoft 365 services that are defined for those plans. To find the details, there are endpoints in Graph which gives you those details

GET https://graph.microsoft.com/v1.0/me/licenseDetails

GET https://graph.microsoft.com/beta/me

Microsoft Graph Explorer:

There are various tools to make request against different graph endpoints but here I will be using Microsoft Graph Explorer tool.

After you login to Microsoft Graph Explorer tool, make a request to any of the above given endpoints. Find below screenshot for the GET request to the endpoint me/licenseDetails

In the above picture, the sku Id is nothing but the Microsoft 365 license plan and the service plans array shows list of the Microsoft 365 Services (SharePoint, Power Apps, Power Automate, Exchange, Yammer etc) enabled for the user. If there are multiple license assigned for the same user then you get the list as an array with different skuid’s.

For reference, here are some of the most common sku id information that you might need:

NameID
Office 365 E118181a46-0d4e-45cd-891e-60aabd171b4e
Microsoft 365 E305e9a617-0261-4cee-bb44-138d3ef5d965
Microsoft 365 E506ebc4ee-1bb5-47dd-8120-11324bc54e06
E5 Developer Licensec42b9cae-ea4f-4ab7-9717-81576235ccac
Microsoft 365 F117b4a1d6-2c65-478e-a046-51cf40d25d76
Power BI (Free)a403ebcc-fae0-4ca2-8c8c-7a907fd6c235
Flow Freef30db892-07e9-47e9-837c-80727f46fd3d

Here are some of the most common Service plan Id information:

NameID
SharePoint Online5dbe027f-2339-4123-9542-606e4d348a72
Yammer7547a3fe-08ee-4ccb-b430-5077c5041653
Power Apps9c0dab89-a30c-4117-86e7-97bda240acd2
Power Automate07699545-9485-468e-95b6-2fca3738be01
AAD Premium 2eec0eb4f-6444-4f95-aba0-50c24d67f998
Exchange Onlineefb87545-963c-4e0d-99df-69c6916d9eb0

For more information on the different Microsoft 365 license & service details, refer the below link

https://docs.microsoft.com/en-us/azure/active-directory/enterprise-users/licensing-service-plan-reference

The beta/me endpoint also gives information on the licenses & service plans:

To get this information for a different user, make a get request to the following endpoint with the user ID

To get the information for all users in your tenant

https://graph.microsoft.com/beta/users?$select=id,displayName,assignedLicenses,assignedPlans

If your tenant has more users, consider looking at the following documentation

https://docs.microsoft.com/en-us/graph/paging

Office Profile:

The information can also be accessed from your Office Profile, after logging in to the Office.com

  • Click the Profile icon and then click View account which will take you to the below screen shown on the left side

Now click Subscriptions which will show the all the different SKU’s assigned to you & the different service plan’s. Refer to the above picture on the right side.

PowerShell:

To access this information with PowerShell, refer the following documentation:

https://docs.microsoft.com/en-us/microsoft-365/enterprise/view-account-license-and-service-details-with-microsoft-365-powershell?view=o365-worldwide

Reference:

https://docs.microsoft.com/en-us/graph/api/user-list-licensedetails

https://docs.microsoft.com/en-us/azure/active-directory/enterprise-users/licensing-service-plan-reference

Summary: On this post we have seen how to get information on the assigned Microsoft License & services details for a user. Hope you like this article & find it informational.

Trigger an Azure Webjob from Power Automate

On this post let us see how to trigger or run a WebJob from Power Automate. WebJob is a powerful service in Azure keeping in mind the supported file types or programs it can run. Before proceeding with the instructions to call a WebJob in Power Automate, let us see some basics of an Azure WebJob. WebJobs is a feature of Azure App Service that enables you to run a program or script in the same instance of the Azure web app with no additional cost. As of now it is not supported in App service plan for Linux. There are two types of WebJobs

  1. Continuous WebJob
    • Starts immediately when the WebJob is created. To keep the job from ending, the program or script typically does its work inside an endless loop.
    • Runs on all instances that the web app runs on. You can optionally restrict the WebJob to a single instance.
  2. Triggered WebJob
    • Starts only when triggered manually or on a schedule based on CRON expression.
    • Runs on a single instance that Azure selects for load balancing.

Supported file types for scripts or programs:

The following file types are supported:

  • .cmd, .bat, .exe (using Windows cmd)
  • .ps1 (using PowerShell)
  • .sh (using Bash)
  • .php (using PHP)
  • .py (using Python)
  • .js (using Node.js)
  • .jar (using Java)

Check here the documentation from Microsoft to choose between Flow, Logic Apps, Functions & Webjobs for your automation services with comparisons against each other. If you are using a Function app with a Consumption plan your function can run only to a max of 10 mins. If you have a long running task on a webjob, set this property in the App service Application setting from the Configuration blade as shown below

The above setting is to avoid idling out if there is no CPU activity. The IDLE timeout setting is set to 1 hour in the above screenshot.

Azure WebJobs SDK:

There is a Powerful Azure WebJobs SDK which simplifies the task of writing background processing code that runs in WebJobs. It makes it easier to write code that reads or writes from Azure Storage account and it also facilitates to trigger the WebJob if there is any new data on the queue, blob, table, service bus for an event driven architecture. Azure functions is built on the WebJobs SDK. If you set your web app to run continuous or scheduled (timer-trigger) WebJobs, enable the Always on setting on your web app’s Azure Configuration page to ensure that the WebJobs run reliably. This feature is available only in the Basic, Standard, and Premium tiers of the App service plan.

Create and Deploy a WebJob:

To call a WebJob from Power Automate, let us create a Triggered WebJob (.Net Framework) from Visual Studio. There is a also support for .NET Core console apps as WebJobs. Refer this documentation from Microsoft to create a WebJob from Visual Studio. In Visual studio there is a template to create a WebJob project as shown below

This is how the VS project looks like

The Program.cs has the code to ensure that the Job will be running continuously, for this case it is not required comment or remove the code which is highlighted. The Functions.cs has the code to pick up the message from the Storage Queue (Event-Driven) through the WebJobs SDK runtime, the WebApp must set to Always on to make it work. For this example, it is not required since it is going to be a triggered Job so the file Functions.cs can be deleted.

If you have any arguments to be passed from Power Automate, you can access it on your code as shown below

To deploy the WebJob, right click the project and select Publish. If there is no publish profile yet, create one or export it from Azure WebApp and then Publish. To know more about the Publish settings In the Publish tab, choose Edit as shown below

The WebJob will be now in Azure. Go to your Azure WebApp or App Service and click WebJobs under the settings blade to find the WebJob deployed from Visual Studio. Find the WebJob in the Azure portal

WebJobs API endpoint for the WebJob:

There are API endpoints available for the Azure WebJob which will be used for triggering the WebJob from Power Automate. Go through the following documentation for more details on the list of available endpoints:

https://github.com/projectkudu/kudu/wiki/WebJobs-API

To Trigger or Start a WebJob, you should have the Webhook URL from the Azure Portal. To get the URL, click Properties after selecting the WebJob as shown below

Copy the Web hook URL, User Name and Password to be later used in Power Automate. Let us trigger the WebJob from Postman client using the above information

Method: Post

URL: https://yourappname.scm.azurewebsites.net/api/triggeredwebjobs/webjobname/run

Authorization Type: Basic Auth

User Name and Password copied from the Portal

This will trigger the Job.

If there are parameters to be passed, the API would be like

https://youwebappname.scm.azurewebsites.net/api/triggeredwebjobs/youwebjobname/run?arguments={arg1} {arg2}

Trigger from Power Automate:

Till now we have the WebJob published in Azure, can we call an API in Power Automate. Yes, it is possible with the help of the Premium action HTTP as shown below

Voila! The WebJob has been triggered from Power Automate.

Summary: On this post we have seen how to call a WebJob using PowerAutomate. There is also a trigger to calla  Flow from a PowerApp, which could be used to start the WebJob. Hope you have found this informational & helpful. Let me know any feedback or comments on the comment section below

How to use your MS Teams as an email distribution list

When you create a Microsoft Team, a Microsoft 365 group is created to manage the team membership like Owners, members, guests. I would rather say the Microsoft 365 group is a backbone of a Team. Through the group you also get an email address for the MS team. Find the other Microsoft 365 services which gets created per this documentation whenever there is a Team provisioned

On this blogpost let us see how to enable a team which can also act as an email distribution list so that you can send an email to all the team members, by default this option is disabled. You will have to be an Owner of the team to set this up. There are couple of ways to do this

  • Graph Explorer
  • Outlook
  • Exchange Online Powershell
  • Exchange Online Administrator

Graph Explorer:

Graph explorer is a utility that will let you make requests and get responses against the different graph endpoints as a signed in user (Delegated User). To enable the email distribution functionality, we will have to get the group id of the team for setting a value to True for the property autoSubscribeNewMembers. To get the Group Id information go to the Team and click the Get link to team as shown below

Copy the content from the popup which should be in the below format

To get the group details like Email Address, Mail Nick Name, Display Name etc make a GET request to the following endpoint from the explorer

https://graph.microsoft.com/v1.0/groups/groupId

Make a PATCH request to the endpoint https://graph.microsoft.com/v1.0/groups/groupId with the payload

{
“autoSubscribeNewMembers”:true
}

Now make a GET request on the following endpoint with the group id of the team https://graph.microsoft.com/v1.0/groups/groupId?$select=autoSubscribeNewMembers

to get its status. It is all set now.

Outlook:

The Microsoft 365 group inbox for a Team is not available in Outlook but it can be accessed through the SharePoint site associated to the group. Open the SharePoint site from any of the Teams channel as shown below

Click Conversations on the left navigation

The URL of the Outlook will be in following format: https://outlook.office365.com/mail/group/domain/mailNickName/email

Access the settings of the group

Click Edit group from the Group Settings

On the Group Settings popup, enable the Subscription as shown below and then Save it. By default this setting is disabled for the Microsoft 365 group.

Exchange Online PowerShell:

The same setting can also be enabled from Exchange online PowerShell if you have Exchange online Administrator access on the tenant. Make sure the Exchange online PowerShell module is installed. Follow the steps below to turn on AutoSubscribeNewMembers which distributes emails to all users

  1. Load the module by the running the command Import-Module ExchangeOnlineManagement
  2. Connect to the Exchange online PowerShell in Microsoft 365
    1. Connect-ExchangeOnline -UserPrincipalName userId@domain.com -ShowProgress $true
  3. Set-UnifiedGroup -Identity 539818c4-XXXX-XXXX-b781-78dff1762b72 -AutoSubscribeNewMembers or Set-UnifiedGroup -Identity “Team Display Name” -AutoSubscribeNewMembers
  4. To disable the setting: Set-UnifiedGroup -Identity ” Team Display Name ” -AutoSubscribeNewMembers:$false

Refer to the documentation from Microsoft for more Exchange online commands related to the Microsoft 365 group.

Exchange Online Administrator

Login into the Exchange Online Admin center and click on Groups from the dashboard section. Execute the below steps

  1. Find the group associated to the team (Team Display Name) from the list and then select
  2. Click on Edit (Pencil Icon) from the ribbon
  3. On the General tab, Enable the property Subscribe new members and then Save

Summary: The same setting can also be applied to a Team created through a Microsoft 365 group. Hope you have found this informational. There were already lot of blogs talking about groups

Reference:

https://support.microsoft.com/en-us/office/learn-about-microsoft-365-groups-b565caa1-5c40-40ef-9915-60fdb2d97fa2

https://support.microsoft.com/en-us/office/follow-a-group-in-outlook-e147fc19-f548-4cd2-834f-80c6235b7c36#ID0EAACAAA=Web

https://sharegate.com/blog/office-365-groups-explained

https://www.jumpto365.com/blog/everyday-guide-to-office-365-groups

How to setup custom domain and email address in Microsoft 365 online tenant

On this blogpost let us see how to add a custom domain and configure exchange email address for the added domain in a Microsoft 365 tenant. This will allow you to create M365 identities for the users in the Microsoft 365 tenant like user@domain.com instead of user@domain.onmicrosoft.com. This setup is also required if you have a Hybrid setup with users from Onpremise Active directory. Azure AD connect tool helps you synchronize your AD identity from Onpremise to Azure AD or Microsoft 365 tenant directory only if there is a custom domain added to the directory. The custom domain can be added from Microsoft 365 tenant admin center or Azure Active directory portal associated to the M365 tenant.  

Pre-Requisites:

  • Own a Domain from any domain providers
  • Global administrator of Microsoft 365 tenant

If you don’t add a domain, user account in your organization will use the default onmicrosoft.com domain for their email address and UPN. To setup and configure a custom domain, you will have to

  1. Add a TXT or MX record
  2. Add DNS records to connect Microsoft 365 services

For this blog post I have used Domain.com provider to add the DNS records for the custom domain

Add a TXT or MX record:

The first step is to prove you are Owner of the domain and also make the domain is not associated to different tenant. To generate the DNS record values and to add the custom domain login to the Microsoft 365 Admin Center

  1. Select Show all > Settings > Domains
  2. Click Add domain
  3. Enter the custom domain name you own
  4. Click on the button Use this domain

Select Add a TXT record to the domain’s DNS records but you can also add a MX record or add a text file to the domain’s website. Find the different options

  1. The DNS record values for the TXT record will be generated as shown below. TTL 3600 seconds is 1 hour
  1. Add the DNS record for TXT from the domain provider interface for managing the records
  1. Go back to the Admin center and then click Verify. It takes around 15 mins to an hour for the DNS records to propagate, sometimes it may even take more time. Keep trying till the domain in verified. Once the domain is verified you will be able to proceed to the next step for configuring the Microsoft 365 services like exchange etc. You can also Skip and do the configuration later but with this setup you can create user accounts by using the custom domain as its UPN e.x user@domain.com without email address. Find instructions on this link to add a custom domain from Azure Active directory portal.

Add DNS records to connect Microsoft 365 services:

The domain is added & verified, now its time to connect the Microsoft services like Email (Exchange Online, Outlook), Mobile device Management aka MDM with the custom domain. On this post will be connecting only to Exchange online to receive email through Microsoft 365. After this setup is done Exchange online will be your new email host for the domain. After the domain is verified from the step above, select Add your own DNS records and click Continue button as shown below

The following DNS records will be generated as shown below

  • MX Records (Mandatory)
    • Sends incoming mail for your domain to the Exchange Online service in Office 365. Mails are delivered to the mail exchange server with the lowest preference number for this record, typically.
  • CNAME Records (Optional: For Outlook client to work)
    • Helps Outlook clients to easily connect to the Exchange Online service by using the Autodiscover service. Autodiscover automatically finds the correct Exchange Server host and configures Outlook for users
  • TXT Records (Optional: SPF record for prevention of spamming)
    • Helps to prevent other people from using your domain to send spam or other malicious email. Sender policy framework (SPF) records work by identifying the servers that are authorized to send email from your domain

Go back to the domain hosting provider interface to add the above DNS records, to get the values for each record expand each record shown on the above interface.

MX Record:

Set the priority to the Highest or to the number 0 and then add the DNS record. If the domain is xyz.com

Sample value/Content: xyz-com.mail.protection.outlook.com

CNAME Records:

Name: Autodiscover

Value/content: autodiscover.outlook.com

TTL: 1 hour

TXT Records (SPF):

There can be only one SPF record on the DNS records so if there are another record already (default), refer this link for more information. I already had the default one so the valye for the TXT record looked like v=spf1 ip5:XX.XX.XXX.X/XX include:spf.protection.outlook.com -all

ipX:XX.XX.XXX.X/XX is the default one

Now after all the DNS records are added, choose Continue. This will take you to the last page of the wizard with the message Domain setup is complete

Now the setup is completed, you can create users using the new custom domain or change an existing users UPN and email address on Admin center with the following steps

  1. Go to Users > Active users page
  2. Select the user’s name, and then on the Account tab select Manage username.
  3. On the Aliases box, enter the new alias@yourdomain.com and then click Add
  4. Select the new alias and if required change it to the primary email.

Summary: On this post we have seen how to configure a custom domain with email. There can also be multiple domains in one tenant. Hope you have found this informational. Let me know any feedback or comments on the comment section below

Reference:

https://docs.microsoft.com/en-us/microsoft-365/admin/get-help-with-domains/create-dns-records-at-any-dns-hosting-provider

https://support.microsoft.com/en-us/office/connect-your-domain-to-office-365-cd74b4fa-6d34-4669-9937-ed178ac84515

https://docs.microsoft.com/en-us/microsoft-365/admin/setup/add-domain

https://support.microsoft.com/en-us/office/add-a-new-domain-in-microsoft-office-365-285437c3-d6c9-45cd-8b48-ed29c670c796

https://docs.microsoft.com/en-us/microsoft-365/admin/setup/domains-faq?view=o365-worldwide

https://docs.microsoft.com/en-us/microsoft-365/enterprise/external-domain-name-system-records

https://docs.microsoft.com/en-us/microsoft-365/security/office-365-security/set-up-spf-in-office-365-to-help-prevent-spoofing?view=o365-worldwide

Teams Presence Light with Raspberry Pi

Almost every one of us is working from home these days due to the Corono situation we are in as of the time I am writing this article. I wrote a recent blog post about controlling devices from PowerApps with the help of a Raspberry PI and thought of extending the project by creating a Teams presence light with the help of a Raspberry Pi & couple of LED’s with different colours. This was possible due to the availability of the presence API endpoint in MS Graph, this helps us get the user’s current team presence (Available, Busy, Be right back, Do not disturb etc) for a logged in user. As of the time I am writing this article application permissions are not supported.

Device Code Flow:

The supported permission type is Delegated to get the presence information in MS graph, the user must sign in to get the users Teams presence. So how can a user signin/authenticate on a device like Raspberry Pi if we are only using a Terminal window to develop & run the application which I will doing it here, Device code flow to the rescue which is an authentication flow to get the data from MS graph for handling delegated permissions with remote signin/authentication using an auto generated device code. This flow lets the user use another device (for instance the windows client with the VS Code) to sign-in interactively. By using the device code flow, the application obtains tokens through a two-step process especially designed for these devices like Raspberry Pi. Examples of such applications are applications running on iOT, or Command-Line tools (CLI).

Refer this blog post for the steps & instructions to develop applications remotely on a Raspberry Pi using VS code.

Application Design:

There will be a .NET core console application polling the MS Graph presence endpoint every 5 seconds and based on the status, the corresponding coloured lights will be turned on. Find below the high-level design of the application

Active Directory application registration:

Start with registering an Application in Active directory with the following settings

Supported Account Types: Accounts in any organizational directory

Redirect URI (Public client/native): https://login.microsoftonline.com/common/oauth2/nativeclient

Enable Allow public client flows a required setting for the device code flow to work as shown below

Add the permission Presence.Read.All if you going to create a presence light for some other user other than the signed in user and Presence.Read if its going to be only for the signed in user. Once the permission is added, grant admin consent.

Console Application:

A console application with the following packages

Package NamePurpose
System.Devices.GpioTo control the GPIO pins for turning on different coloured lights
Microsoft.Identity.ClientAuthentication library for .NET console app facilitating MS graph token handling, caching, token expiration etc
System.ThreadingTimer to poll MS graph presence endpoint every 5 seconds
Newtonsoft.JsonTo parse the MS Graph presence endpoint response
System.Net.HttpTo make a HTTP request GET for presence endpoint

If you wanted to try the MS Graph presence endpoint go the Graph explorer and sign-in using your work account linked to your teams

Beta endpoint URL: https://graph.microsoft.com/beta/me/presence

Request Type: GET

In this example, GPIO pins 12 and 13 are used with Green and Red LED’s but you can also use a RGB LED matrix supported for Raspberry Pi which are readily available in the market. Use the Client Id and the tenant id of the application in the app.

  • Provide the GPIO pins the root permissions through the command on the terminal window /usr/bin/gpio export 12 out and /usr/bin/gpio export 13 out.
  • Run the application by using dotnet run
  • Method AcquireByDeviceCodeAsync(IPublicClientApplication pca) generates the device code
  • As soon as the application is run from the command line, the code is generated as shown below
  • Use the URL https://microsoft.com/devicelogin to login and authenticate against the code generated above
  • Code pca.AcquireTokenSilent(Scopes, accounts.FirstOrDefault()).ExecuteAsync(); generates the token which will used along with the graph GET request for getting the teams presence status of the user
  • The Token will be valid only for 3599 seconds which is close to 1 hour. Generate one more token using the same line of code after an hour which I have not handled in the sample code.
  • Polling will happen every 5 seconds using the .NET Timer_timer.Change(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(5));
  • Based on the teams presence, the corresponding lights will be turned on using the below code
switch (presenceStatus)
{
                        case "Available":
                            Console.WriteLine($"{DateTime.Now} : User is Available");
                            controller.Write(pinGreen, PinValue.High);
                            controller.Write(pinRed, PinValue.Low);
                            break;
                        case "Busy":
                            Console.WriteLine($"{DateTime.Now} : User is Busy");
                            controller.Write(pinGreen, PinValue.Low);
                            controller.Write(pinRed, PinValue.High);
                            break;
}

Code for this application can be found in this GitHub repo link.

More Information about the Device code Flow:

 A POST request to the URL https://login.microsoftonline.com/yourTenantID/oauth2/devicecode with the following information for Header:

Content-Type: application/x-www-form-urlencoded

Request Body: resource=https%3A%2F%2Fgraph.windows.net&client_id=ADClientId/Appid

Will generate the following response

Login & authenticate using the URL https://microsoft.com/devicelogin with the work account.

Token Generation:

With the information from the above request, the token can be generated with a POST request to the URL https://login.microsoftonline.com/youtTenantID/oauth2/token with the following information for Header:

Content-Type: application/x-www-form-urlencoded

Request Body: grant_type=device_code&resource=https%3A%2F%2Fgraph.windows.net&code=CAQABAAEAAAB2UyzwtQEKR7-rWbgdcBZIsC_ydGuxXqxKTcIvapYfPR0edvvCOBAW4VoOZgLHdaAgrf0cBy-5s9Szoez1NmqIgoe0Ggs9p_7-vVilrU6r9CFom5N_M(Information from the Previous response)&client_id= ADClientId/Appid

Will generate the token in the response

Refresh Token:

This token is used to generate access token after the initial one expires by making another request with information like this in the request body

All of these are handled for us by the Microsoft Authentication library for .NET.

Summary: I’ve used MSAL for .NET library  but there are also libraries for MSAL for Python and for other languages as well based on your comfort with the programming language. Hope you have found this informational & interesting. Let me know any feedback or comments on the comment section below

Reference:

https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-device-code

https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/Device-Code-Flow

https://github.com/Azure-Samples/active-directory-dotnetcore-devicecodeflow-v2

https://ashiqf.com/2020/10/25/tools-to-call-microsoft-graph-api-endpoints-as-a-user-and-application/

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

Tools to call Microsoft Graph API endpoints as a User and application

This blogpost will help you to explore and interact with MS graph API endpoint’s using the following tools

  • Postman client
    • Signed in as a user/On-behalf-of API call (Delegated permission)
    • Application/daemon API call (Application permissions)
  • Graph Explorer

I have used MS graph extensively on different MS cloud services like SharePoint, PowerAutomate, PowerApps, Azure services like Azure functions and on devices like Raspberry Pi. It is a very powerful service in Microsoft 365 platform. Let start with some basics

Introduction:

MS Graph API is a RESTful web API which enables you to access different Microsoft 365 cloud service resources through its unified programmability model.

Microsoft Graph exposes REST APIs and client libraries to access data on the following Microsoft cloud services:

  • Microsoft 365 services: Delve, Excel, Microsoft Bookings, Microsoft Teams, OneDrive, OneNote, Outlook/Exchange, Planner, SharePoint, Workplace Analytics.
  • Enterprise Mobility and Security services: Advanced Threat Analytics, Advanced Threat Protection, Azure Active Directory, Identity Manager, and Intune.
  • Windows 10 services: activities, devices, notifications, Universal Print (preview).
  • Dynamics 365 Business Central.

Permission Types:

MS Graph exposes granular permissions that controls the access of the apps that has to the different resources like sites, users, groups etc. There are two types of permission

  • Delegated permissions are used by apps that have a signed-in user present. For these apps, either the user or an administrator consents to the permissions that the app requests and the app can act as the signed-in user when making calls to Microsoft Graph.
  • Application permissions are used by apps that run without a signed-in user present. For e.g Apps that run as background services or daemons. Application permissions can only be consented by an administrator.

Access token:

To call a MS Graph API all you need is an access token in the authorization header of an HTTP request.

GET https://graph.microsoft.com/v1.0/me/ HTTP/1.1

Host: graph.microsoft.com

Authorization: Bearer EwAoA8l6BAAU … 7PqHGsykYj7A0XqHCjbKKgWSkcAg==

The access tokens are issued by the Microsoft identity platform which contains information to validate if the requestor has appropriate permissions to perform the operation they are requesting. An active directory app is a pre-requisite to generate an access token to call a Graph API endpoint.

There are also Microsoft identity platform authentication libraries for .NET, JS Android, Objective-C, Python, Java, Angular facilitating validation, cookie handling, token caching and on maintaining a secure connection. Let’s now go ahead and see the tools

MS Graph Explorer:

Graph explorer is a web-based tool which can be used to build and test requests using Microsoft Graph API. The explorer can be accessed from the following URL:

https://developer.microsoft.com/en-us/graph/graph-explorer

There will be a default Active directory application on the Organizational Active directory of the M365 tenant by the name Graph Explorer with application id de8bc8b5-d9f9-48b1-a8ad-b748da725064. This app can be accessed from the Enterprise applications blade of the Active directory as shown below

Delegated permissions are used by Graph Explorer. Based on your access role & admin consent’s you would be able to call different Microsoft Graph API from this tool. After you have signed into the Graph Explorer tool, the access token will be generated automatically

To view the token information, copy the token and paste it on the utility https://jwt.ms/

If your token has a scp (Scope) claim, then it’s a user based token (Delegated permissions). It is a JSON string containing a space separated list of scope the use has access to call different graph endpoints. You can also find other information related to the issued token, token issued at (iat), expirty not before (nbf), expiry time (exp). The data is in UNIX time stamp but you can convert this information to standard time using the online URL

https://www.epochconverter.com/

More information about JWT can be found at

https://auth0.com/docs/tokens/json-web-tokens

Postman Client:

Postman is a tool that can be used to build and test requests using the Microsoft graph API’s. To use this tool for testing the Graph API endpoint’s, register an app in Azure Active directory as per the instructions from this blog post. Provide the permission (Delegated & Application) as per your need to test it using Postman.

Copy the client id, client secret & tenant ID of the registered app. To access the various endpoints like authorization and token, click on the Endpoints from the Overview section of the Active directory app.

Setting up the environment using Postman collections:

There are Postman collections with many MS graph API requests created by Microsoft for us to explore. Import the collections and setup the environment (Client ID, Client secret, tenant id) for Application API calls and on-behalf-of API calls as per the instruction from the following article

https://docs.microsoft.com/en-us/graph/use-postman

Application API Token:

To generate an application token, make a POST request to Get App-Only Access Token from the collection Microsoft Graph. The grant_type is client_credentials since it is Application permissions.

Token Validity:

The token is valid for 3599 seconds which is 1 hour. Post that the token will expire, you will have to regenerate the token by making another call.

The AccessToken (Application API call) will be generated and automatically stored on the Environment (Microsoft Graph environment) AppAccessToken with the help of a script on the Tests tab in Postman. Copy the access token value & paste it on the utility https://jwt.ms/. Find the decoded token below which has information like the Application ID/client id of the AD app, display name and roles to which the app has access to poll the graph endpoint.

Graph API call:

The call to the Graph should have the bearer token

Signed-in user/on-behalf-of API Token:

To generate a Signed-in user token, make a POST request to Get user Access Token from the collection Microsoft Graph. The grant_type is password since it is delegated permissions.

The AccessToken (Signed-in user API call) will be generated and automatically stored on the Environment (Microsoft Graph environment) UserAccessToken with the help of a script on the Tests tab in Postman.

Copy the access token value & paste it on the utility https://jwt.ms/. Find the decoded token below which has information like the Application ID/client id of the AD app, display name and scopes (scp) to which the app has access to poll the graph endpoint. If you remember the Application API token had roles & not scopes, so this is how you can identify the token type.

Storing the production User ID and password is not recommended on the Environmental variables since the information is stored in Postman but this can be handled by generating an access token from the request Authorization tab, set the type as OAuth 2.0 and click Get New Access Token button

Fill in all the information gathered from the App in Azure AD like Appid, Secret, Endpoints (Authorization and Token), state can be any random value

Click Request token, this will prompt the user to enter the Username and password. After authentication, it will generate the token which could be used further to make API calls.

Graph API call:

The call to the Graph should have the bearer token on the Authorization tab or on the Headers tab

Summary: On this post we have seen how to use tools like Graph explorer & Postman to test different MS graph API endpoints. You can make requests like GET, POST, PUT, PATCH, DELETE based on its availability. Refer to the Microsoft documentation for v1.0 and beta endpoints. Once you have explored & tested the API, you are ready to use on applications using the available SDK’s for different programming languages. Let me know any feedback or comments on the comment section below