Send Teams Activity Feed notification from Power Automate using custom Teams Bot

Activity feed notifications appears in the Teams activity feed panel with link to various locations thus enabling developers to build actionable content. These notifications are sent as push notifications in the Teams client. In this blogpost, let us see how to send Teams activity feed notification using

  1. Custom Teams App with a Bot
  2. Power Automate standard action: Post a feed notification

Pre-Requisites:

Custom Teams App with a Bot:

Microsoft graph has API endpoints to send activity feed notifications to Teams users. The pre-requisite to use the activity feed graph endpoint is to have a custom Teams app scoped to a Team, or in a chat or user.

Step 1: Custom Teams App scoped to Team:

For this blogpost, I have used a custom Teams app scoped to a Team. Refer to the following blogpost to create a custom Team app scoped to a Team with a Bot capable of sending an Adaptive card message on a channel

Do not install the Teams App yet before completing the other steps given below. After the Teams bot is created, a custom Azure Active directory Application must be registered.

Step 2: Azure AD Application – Microsoft Graph Activity Feed permission:

Register an Azure AD application to add the Microsoft Graph permission to be send activity feed. Copy the Application (client) ID and Tenant Id of the registered app from the Overview section and create a secret from the Certificates & secrets under Manage blade per the screenshot shown below. Once the secret is created, copy the value to be used in the Power Automate cloud flow

Add the application permission TeamsActivity.Send with an admin consent.

Step 3: Link the AD app to the Teams App

The AD application with permission to send activity feed is created, the next step is to link the Teams app created in Step 1 with the AD app. In the Teams Developer portal, enter the Application (client) ID in the apps Basic Information under the Overview section as shown in the below screen shot

Don’t forget to Save the App in the Developer portal after the Application ID is entered. Now go to the App Features and then click Activity Feed notification as shown below

Click + Add an activity and enter the following information per the screenshot below

Type: informationBroadcasted

Description: Information Broadcasted Activity

Title: Notification from {actor} broadcasted by {broadcastedBy}

Click Save. The Teams app is now ready to be installed, follow the instructions here to install the bot in a Team for testing the Activity Feed notifications.

Power Automate Cloud Flow to send Adatpive card message and Activity Feed:

The Teams app is ready and now let’s create an Instant cloud flow with manual trigger to send an Adaptive card message to a Teams channel (General or any standard channel) and then Deep link to the adaptive card post in the Teams Channel to the activity feed notification.  I have used a Premium HTTP connector action to send the adaptive card using Bot Framework REST API. Go through the following post to send the Adaptive card

In the flow after the action HTTP-SendAdaptiveCardMessage, add a compose action with the following expression to get the Message ID of the Adaptive card channel message

body('HTTP-SendAdaptiveCardMessage')?['id']

Add two compose action to store the TeamIdorGroupId and TeamChannelID as shown below

Add a HTTP action (Premium) to send the activity feed to all Team members (Beta) using the Graph Activity Feed API. Find the details below for the HTTP request

Type: POST

URI: https://graph.microsoft.com/beta/teams/teamIdorGroupId/sendActivityNotification

Replace teamIdorGroupId from the compose action

Body:

{
  "topic": {
    "source": "entityUrl",
    "value": "https://graph.microsoft.com/v1.0/teams/@{outputs('Compose-TeamIdorGroupId')}/channels/@{outputs('Compose-ChannelID')}/messages/@{outputs('Compose-MessageId')}"
  },
  "activityType": "informationBroadcasted",
  "previewText": {
    "content": "Urgent Information"
  },
  "recipient": {
    "@odata.type": "microsoft.graph.teamMembersNotificationRecipient",
    "teamId": "@{outputs('Compose-TeamIdorGroupId')}"
  },
  "templateParameters": [
    {
      "name": "broadcastedBy",
      "value": "Mohamed Ashiq Faleel"
    }
  ]
}

If you are having issues (Invalid Expression) while saving the flow, add additional @ keyword in the recipient as shown below

Click Show advanced options in the HTTP action to enter the Authentication details. Enter the Client (Application) ID, Secret and Tenant Id from Step 2

Time to test the Power Automate flow. Find below the Activity Feed message for a Teams user

Note:

The Teams app can also be enabled with Resource Specific Consent, to do so in the Teams Developer portal click Permissions on the Left bar. In the section Team Permissions select TeamsActivity.Send.Group under Application. If you have done this, Step 2 is not required. I will cover this in a different blog post.

Power Automate standard action: Post a feed notification:

There is a standard Teams action Post a feed notification which creates an activity feed with/without Deep link to a chat or Teams Channel using the Power Automate Teams Bot. Find below the action

Summary:

Isn’t this powerful to have engaging and actionable content for the users in Teams. There can be many use cases which could be applied for this setup e.g: Notify user and deep link to a Power App added in Teams channel etc. 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.

Send Teams channel message aka proactive message using custom Teams bot and Power Automate – Part 2

In the last post, we have seen till the installation of the Teams App with the Bot on a Microsoft Team. Let us now continue to send a proactive message, be it an Adaptive card or a simple Text message on a Teams channel using Bot Framework REST API from a Power Automate Cloud Flow.

A proactive message is any message sent by a bot that isn’t in response to a request from a user. Ex: Welcome messages, Notifications, Scheduled messages, Broadcast message etc

Power Automate Cloud Flow:

For this blog post, I have used a Power Automate Instant cloud flow with manual trigger to send the message to a Teams Channel. To follow along the blog post, be ready with the following information

  1. Team ID & Channel ID

This information is required to send the proactive message to a Microsoft Team Channel. To get this information, in Microsoft Teams Client identify the Team channel in scope > Click the ellipsis of the channel in scope > Get link to channel as shown below

After decoding the channel link, the url will be in the format as shown in the below image from which you can get the channel Id and Team group ID

If you are building a Teams broadcaster or communicator application using Power Apps, these information can be stored in Table or a SharePoint list. There are Graph API endpoints which can used to get the Channel Id’s etc.

  1. Bot ID [Part 1 – Step 6]
  2. Bot Secret [Part 1 – Step 7]
  3. Teams Service URL

The service URL is the base URI for all Bot framework API requests. In Teams the service URL will change based on user’s region [EMEA, America, APAC, India etc]. This example delivers messages only on the Team channel and not to the users directly so you can choose the service URL based on the Microsoft 365 Tenant Location. Find below some URL’s based on region

RegionService URL
EMEAhttps://smba.trafficmanager.net/emea/
Americahttps://smba.trafficmanager.net/amer/
Indiahttps://smba.trafficmanager.net/in/
APAChttps://smba.trafficmanager.net/APAC/

All the required information is now available to proceed with sending the channel message using REST API.

Generate Access Token – Bot Framework REST API:

There are SDK’s in Bot Framework for programming languages like .NET, JavaScript, Python etc to handle all conversations for you but an alternative to using the SDK is leveraging Bot Framework REST API. The first step in using the different REST API endpoints from Bot Framework is to generate an access token which is then added to the Authorization header of each API request in this format

Authorization: Bearer ACCESS_TOKEN

To request an access, make a HTTP request per the following details

Method: POST

Request URL:

https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token

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

Body:

grant_type=client_credentials&client_id=botId&client_secret=botSecret&scope=https://api.botframework.com/.default

Replace the botId and botSecret with the values stored from the previous steps. The Bot Id and the secret are from the custom Teams app created based on the previous post.

Add a HTTP Action in your Power Automate flow to add the above details for generating the token

The JWT access token is valid for 24 hours, if the token expires make another request.

Send Teams Channel Message:

The Teams Channel conversation post or proactive message on a channel can now be sent using the REST API to Create Conversation with the access token generated in above step.

Simple Text Message:

Find below the HTTP request detail to send a simple proactive message on a Teams Channel. The conversation Id is the Teams Channel Id

Type: POST

Request URL:

https://smba.trafficmanager.net/emea/v3/conversations/teamsChannelId/activities

Replace teamsChannelId (conversationId) with the actual Team channel Id

Body:

{
  "type": "message",
  "text": "Simple Text Message"
}

Authorization Header: Bearer access_tokenvalue

The Authentication of the HTTP action should be set to Raw, the value should be in the format

Bearer access_token

You can use Parse JSON Action to extract the access token from the previous HTTP action HTTP-GenerateBOTToken or you can directly get the value using the following expression

body('HTTP-GenerateBOTToken')?['access_token']

The above HTTP request will create a HTTP response with the activity id which can be potentially used to send a reply etc.

Adaptive Card Message:

Adaptive cards are platform-agnostic snippets of UI authored in JSON that different Microsoft apps and services like Teams, Outlook can use. It can be designed using the Adaptive Card designer portal. To send an Adaptive to a Teams Channel, everything else remains the same when comparted with above give HTTP request for the Simple Text message except the Body as below

{
  "type": "message",
  "attachments": [
    {
      "contentType": "application/vnd.microsoft.card.adaptive",
      "content": {
       "msTeams": {
          "width": "full"
        },
        Replace the ADAPTIVE CARD JSON PAYLOAD from the designer portal
      }
    }
  ]
}

You can get the complete body of request from this Link. This method can be used to send the message on any standard channel but not on Private Teams channel, Microsoft has not opened the possibility to send a channel message on private channel using a Bot. Find below adaptive card message posted on the Teams Channel from the Power Automate flow

Summary:

There are lot of possibilities with the Bot connector service REST API, what I have shown above is only an endpoint to send a message in a Teams Channel. Look at this documentation on the available conversation operations like Reply, Delete, Update conversation etc. Using this approach you can build a Company broadcaster app with the possibility of reaching out to multiple Teams without the user being the member or owner of the Team. 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.

Send Teams channel message aka proactive message using custom Teams bot and Power Automate – Part 1

Microsoft Teams connector in Power Automate has actions which can send a simple text message or Adaptive card as a flow bot in a Teams channel. Messages or cards are posted as the user who’s signed into the connector in the flow or by using the flow bot.

Messages can be posted on a Teams channel only if the signed in user or account of the connector is a member or an Owner of the Microsoft Team. Recently I had a requirement from my customer to post or broadcast messages on numerous Teams channels (> 1000). It is impossible per the limits for Microsoft Teams to have a dedicated service account as a member of all teams in scope. There is no graph API with application permission which can send a message in a channel. In this blog post, let us see how I have overcome the limitation of posting a message or card in multiple teams with the help of

  1. Custom Teams App with a Bot
  2. Installation of Teams App in Teams
  3. Bot connector REST API to post a Message or Adaptive Card aka proactive message

Custom Teams App with a Bot:

The teams in scope to receive the channel post or Adaptive card message should have a custom Teams app installed. The Teams app should have a Bot as its app features enabling the Microsoft team to receive the message. In this section, let us see how to create a Teams App with a Bot using the Developer Portal for Teams. Step 1: Login to the Teams Developer portal using your Microsoft 365 login ID and then Click + New app as shown below

Step 2: In the following screen for the Basic information of the app, enter the following mandatory information like Short name, App ID (Auto Generated), Short description, Long description, Developer or company name, Website (Valid HTTPS URL), Privacy policy url, Terms of use url. Once all of the above information is entered, click Save at the top left corner as shown below.

To apply a custom logo or an app icon for the Teams app, click Branding on the left navigation bar in the Teams developer portal as shown above.

Application (client) ID – Teams Activity Feed:

You can leave the Application (client) ID as blank. This section will be filled for custom Teams Activity Feed use case.

Step 3: On the left navigation, click App features > Bot

Step 4: Click Create a new bot which will take you to the Bot management portal. If you already have a bot where you are an Owner, it will be listed in the dropdown as shown below.

Step 5: In the Bot management, click + New Bot > Enter the name of the bot > Add

This step also registers an Azure AD app registration in the Azure AD Portal.

Step 6: Once the bot is added. In the Bot management portal url from the Developer Portal, copy the Bot ID and keep it handy to be used in the Power Automate cloud flow.

Step 7: Now click the registered bot in the above screen to Add a secret as shown below. As soon as the secret is generated, copy the value and keep it handy to be used in Power Automate cloud flow.

To change the logo of the Bot, login to this URL https://dev.botframework.com/bots

Step 8: Go back to the created Teams app in the Developer Portal, in App features > Select the created bot > Set the scope to Team > Save

Installation of Teams App in Teams:

The Teams app is now configured with required features to send Teams channel conversation post. Download the App manifest package from the Developer Portal as shown below

Upload app in Microsoft Teams [Side Loading]:

Go through this Microsoft Documentation link to sideload the Teams App to your Teams client as a developer before publishing the package to the Teams Organization App catalog.

Go to the Teams Desktop Client > Apps > Manage your apps > Upload a custom app > Select the App manifest Zip package from above step > Add to a team > Select the Team to install the app > Setup a bot.

Find below the screenshot for your reference from Teams Desktop client

To validate the installation of the app, go to the Installed Team > Manage Team > Apps > You can find the installed app as shown below

Upload app in Microsoft Teams [Organization App Catalog]:

After the app is tested, the app can be deployed at scale once the app is available in the Teams Organization App catalog through Graph API. The pre-requisite to call the Graph API enpoint to install the app is the

  1. Teams ID (Group ID)
  2. Teams APP ID from the App catalog

Summary:

In the next post I will cover how to use Bot Framework REST API in Power Automate Cloud Flow to send the Adaptive card message in a Teams Channel. 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.

Deep Link SharePoint News post in Teams using Adaptive card and Power Automate

Microsoft Teams helps us bring together content from different Microsoft 365 services for easier collaboration. In Microsoft Teams connected SharePoint site, SharePoint News connector would help receive news updates from the site. In this post let us see how to create Notifications about new News post with deep link to the post from a communication site in an Adaptive card on a Teams channel using

  1. Adaptive card
  2. Stage View
  3. Power Automate cloud flow

The users from a Teams channel would be able to read & engage on the News post by click of a button as shown below

Adaptive card:

Adaptive Cards are a platform-agnostic method of sharing and displaying blocks of information using JSON across various host applications like Teams, Outlook, Bots etc. The above adaptive card has following information from the News Post

  1. Title
  2. Description
  3. Banner Image Url
  4. Author Profile picture
  5. Author Name
  6. Published Date
  7. Deep Link to the post

The card can be designed based on your requirements from the Adaptive Card Designer portal. The JSON content of the above adaptive card can be downloaded from here.

Stage View:

Stage View helps provide a seamless experience of viewing content in Teams. Users can view the content without leaving the context thus leading to have a higher engagement. For this post, I have used stage view through deep link for a SharePoint News post. Find the syntax below to deep link SharePoint News post

https://teams.microsoft.com/l/stage/teamsAppId/0?context={"contentUrl":" newsPostPageUrl","websiteUrl":"newsPostPageUrl","name":"Internal News"}

In the above syntax replace teamsAppId, newsPostPageUrl & title which I have named as Internal News.

teamsAppId: 2a527703-1f6f-4559-a332-d8a7d288cd88

newsPostPageUrl: The url of the News post in SharePoint.

In the adaptive card action set OpenUrl the following from the stage view syntax should be encoded

{
  "contentUrl":" newsPostPageUrl",
  "websiteUrl":"newsPostPageUrl",
  "name":"Internal News"
}

I have also tested stage view for Microsoft forms & Power BI. You can find the app id for other Microsoft 365 service here on this link

https://docs.microsoft.com/en-us/graph/teams-configuring-builtin-tabs

Power Automate cloud flow:

The Cloud flow is used to send an adaptive card to a Teams channel with the SharePoint News post deep link whenever there is a new News post published in a Communication site.

Step 1: Let us start with creating the Automated cloud flow with SharePoint trigger When an item is created or modified. In the trigger, the Site Address should be url of the communication site and the List Name as the Site Pages Library GUID as shown below

Step 2: In the trigger settings enter the following trigger condition to fire only on the first major version of the News Post

@and(equals(triggerOutputs()?['body/PromotedState'],2),contains(triggerOutputs()?['body/{VersionNumber}'],'1.0'))

For more information on trigger conditions for SharePoint online, go through this blog post.

Step 3: The compose action Compose-StageViewURL with the following code

{
  "contentUrl": "@{triggerOutputs()?['body/{Link}']}",
  "websiteUrl": "@{triggerOutputs()?['body/{Link}']}",
  "name": "Internal News"
}

The trigger output Link should have the url of the News post.

Encode the content in the compose action Compose-StageViewURL using the expression encodeUriComponent() and form the remaining part of the URL.

https://teams.microsoft.com/l/stage/2a527703-1f6f-4559-a332-d8a7d288cd88/0?context= @{encodeUriComponent(outputs('Compose-StageViewURL'))}

on another compose action Compose-StageViewURL-Encoded.

Step 4: Add the action Get user photo to display the picture of the author in the adaptive card. The User (UPN) property of the action can be provided from the trigger output Created By Email. The next step is to convert the output of the Get user photo action to Base64 encoded string using the following expression

concat('data:',body('Get_user_photo_(V2)')?['$content-type'],';base64,',body('Get_user_photo_(V2)')?['$content'])

Step 5: Add the action Post Adaptive card in a chat or channel as shown below

In the adaptive card JSON, find below the mapping information of each property from the output of trigger or action

  1. Title: {triggerOutputs()?[‘body/Title’]
  2. Description: triggerOutputs()?[‘body/Description’]
  3. Banner Image Url: triggerOutputs()?[‘body/BannerImageUrl’]
  4. Author Profile picture: outputs(‘Compose-Base64ProfilePic’)
  5. Author Name: triggerOutputs()?[‘body/Author/DisplayName’]
  6. Published Date: formatDateTime(triggerOutputs()?[‘body/Created’], ‘g’)
  7. Deep Link to the post: outputs(‘Compose-StageViewURL-Encoded’)

The export version of the flow can be downloaded from this GitHub link.

Summary:

The adaptive card with stage view to a SharePoint News post allows the users to open and view the content without leaving the context. The user can also Like or Comment on the News post. 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.

Get deleted SharePoint site details using Microsoft Graph API

The deleted sites are retained for 93 days and an Admin can restore them. In this blog post let us see how to get the deleted SharePoint site details using Microsoft Graph API application permission.

Step 1: Register an application in Azure AD and obtain the client id, client secret & tenant id for the registered application. Add Sites.Read.All Microsoft Graph application permission

Step 2: Find the list GUID of the Hidden List DO_NOT_DELETE_SPLIST_TENANTADMIN_ALL_SITES_AGGREGA which has all the deleted site information from the tenant.

Make a GET request to the following Graph API endpoint with the token generated from the above AD app using PostMan or using Graph Explorer if you are an Global or SharePoint administrator

https://graph.microsoft.com/v1.0/sites/tenantName-admin.sharepoint.com/lists

Replace the tenantName with name of your tenant from the above URL

Step 3: Graph API to list all Deleted Sites within the tenant

https://graph.microsoft.com/v1.0/sites/tenantName-admin.sharepoint.com/lists/1dd71312-bceb-48bb-b853-7c0d33ac5618/items?$expand=fields

Make a GET query after replacing the tenantName and the list GUID of DO_NOT_DELETE_SPLIST_TENANTADMIN_ALL_SITES_AGGREGA from Step 2.

You can filter from different fields available [Title, SiteUrl etc]. To filter based on SharePoint site URL

https://graph.microsoft.com/v1.0/sites/tenantName-admin.sharepoint.com/lists/1dd71312-bceb-48bb-b853-7c0d33ac5618/items?$expand=fields&$filter=fields/SiteUrl eq 'https://tenantName.sharepoint.com/sites/siteName'

Step 4: To do this from Power Automate or Azure logic app, follow this post

https://ashiqf.com/2021/03/16/call-microsoft-graph-api-as-a-daemon-application-with-application-permission-from-power-automate-using-http-connector/

There are activity alerts which you can setup from Security center for Deleted Site but it will send you information on the Site URL and the name of the user deleted the site, as of now it does not provide the Title, Site ID etc. So this API can provide you additional details. 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.

Handling nonexistent, null and multi value type properties in Parse JSON action

In Power Automate cloud flow, Parse JSON action is used to access properties in JSON content enabling you to select those properties from the dynamic content list on your subsequent actions. Typically the JSON content will be from a response to an API call. The first step after adding the action is to select the source of the JSON content and to add the schema, you can either provide a JSON schema from your request payload or the action can generate based on a sample content. If you chose to generate the schema from a sample, the schema is generated based on the first object from the sample JSON content.

For the following sample JSON content, the property

  • Name in the first element is of type string and in the second element is of type null
  • EmpNo in the first element is of type integer and in the second element is of type string
  • Country in the first element is of type string and in the second element it does not exist
[
  {
    "Name": "Mohamed Ashiq Faleel",
    "EmpNo": 123456,
    "Country": "Sweden"
  },
  {
    "Name": null,
    "EmpNo":  "EX-123456"
 }
]

the generated schema is

{
    "type": "array",
    "items": {
        "type": "object",
        "properties": {
            "Name": {
                "type": "string"
            },
            "EmpNo": {
                "type": "integer"
            },
            "Country": {
                "type": "string"
            }
        },
        "required": [
            "Name",
            "EmpNo"
        ]
    }
}
  • The Type of the properties in the above schema is based on the property values from the first element [Name – String, EmpNo – Integer & Location – String]
  • The required property only Name and EmpNo since Country is not available in the second element

In this blog post, let us see how to handle the following in Parse JSON action

  1. Null and Multi value type property
  2. Non Existent property

I have added the above sample content in an Array variable and the above generated schema in the Parse JSON action as shown below

Null and Multi value type property:

The sample content had elements with null property value [Name – second element] and the type of the property is different on each element [EmpNo – Integer and String]. If you run the flow, it will fail with the message ValidationFailed. The schema validation failed for the Parse JSON action and the output should have the following error in the output

  • Invalid type. Expected String but got Null.
    • Reason – Property Name in the second element null and not string as defined in the schema
  • Invalid type. Expected Integer but got String
    • Reason – Property EmpNo in the second element had string value and not integer as defined in the schema

There are two methods to solve this problem.

Method 1:

Add additional data types to the property Name [null] and EmpNo [string] as shown below

{
  "type": "array",
  "items": {
    "type": "object",
    "properties": {
      "Name": {
        "type": [
          "string",
          "null"
        ]
      },
      "EmpNo": {
        "type": [
          "integer",
          "string"
        ]
      },
      "Country": {
        "type": "string"
      }
    },
    "required": [
      "Name",
      "EmpNo"
    ]
  }
}

The drawback with this approach is the property values will not show in dynamic content panel.

You will have to write expression to get the value

items('Apply_to_each')?['Name']
items('Apply_to_each')?['EmpNo']

Remove the type information for the property Name and EmpNo from the schema as shown below

{
    "type": "array",
    "items": {
        "type": "object",
        "properties": {
            "Name": {},
            "EmpNo": {},
            "Country": {
                "type": "string"
            }
        },
        "required": [
            "Name",
            "EmpNo"
        ]
    }
}

This way you will not loose the selection of properties from the dynamic content

Non Existent property:

The sample content did not have the property Country in the second element. The first check is to validate the required property from the schema

"required": [
            "Name",
            "EmpNo"
        ]

If you look above which is taken from the schema, Country is not there so all is good. The expression to get the value is

items('Apply_to_each')?['Country']

Find below screenshot of the run for the property Country from the second element

To have a meaningful output, you can write an expression to show some default text (Not Available) if the property is non existent else the actual value. Find below the expression

if(empty(items('Apply_to_each')?['Country']),'Not Available',items('Apply_to_each')?['Country'])

You can use the above condition to show some default text for null values.

Summary:

The parse JSON action makes your flow cleaner with the availability of the properties from the dynamic content panel. It is always recommended to go through the generated schema of the action and do some clean up on unwanted or not going to be used properties and do updates to the different properties based on all scenarios of the expected content. 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.

Parse an array without using Parse JSON action in Power Automate cloud flow

In this blog post let us see how to access the property of an array object without using Parse JSON action.

Find below the sample array which has been initialized in an array variable

[
{
    "Name": "Mohamed Ashiq Faleel",
    "Location": "Stockholm"
  },
  {
    "Name": "Megan Bowen",
    "Location": "New York"
  }
]

Add a Apply to each control with output selected from the array variable EmployeeArray as shown below

Add the compose action inside the Apply to each control loop to access the property Name from the array. In the compose action add the following expression to get the Name value

item()?['Name']

Find below the screenshot with the expression

For country it should be

item()?[‘Country’]

The generic expression is

item()?['Property-Name']

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.