Safely Consume an Azure Function Through Power Automate

Last Updated on Dec 1, 2020

Introduction

You might have heard that “Either you are the one who is involved in creating automation or you are the one becoming automated”. Now, you get to decide whether you want to be a part of the revolution or transform  yourself through automation. In both cases, the victory is yours. A pioneering company like Microsoft has been a game-changer when it comes to automation and has been an inevitable part of the revolutionizing journey of automation. Microsoft has been successfully launching many cutting-edge applications but in this one, we are more focused to talk about one specifically. This one started off with a name called Microsoft flow is now famously known as Power Automate. If you have used Ms Flow, you must be knowing that Microsoft power automate is all about automating the process. It enables businesses of all sizes and shapes to create repeatable workflows whenever required. There is a leap of actions that can be performed and processed. In this article, we will be understanding the nitty-gritty of Microsoft created Power automate for all types of business models. What are the services and features provided by Power automate and how it helps in creating higher business value.

Azure Functions

Azure Function is a Microsoft-based server-less, event-driven compute service that allows software developers to easily run code or script written in any language of their choice. In response to various events performed while scaling on demand and paying only for the duration their code runs. Using Azure Function, you are not required to worry about provisioning the whole application or managing infrastructure. It makes developers more productive by allowing them to develop  applications using their preferred language such as Node.js, Java, C#, F# or PHP. An Azure Function extends the capabilities of Azure WebJobs and are is built on top of Azure WebJobs with some enhancements in the underlying infrastructure.

Features of Azure Functions

Below are some of the key features of Azure Function:

Feature Description
Language Choice Program functions using your preferred choice of language, JavaScript, C# or F#
Pay-per-use pricing plan Pay only for the duration till your code executes
Use your own dependencies/assemblies Consume your preferred libraries as Functions support NuGet and NPM
Integrated security Secure HTTP-triggered functions using OAuth providers such as Microsoft, Google, Facebook, Google and Azure Active Directory account
Simplified Integration Utilize Azure services and software-as-a-service (SaaS) utilities
Adaptable development Easily set up integrations and code deployments through Azure DevOps services and GitHub
Open-source Functions runtime is open-source and can be accessed through GitHub

Power Automate is the top choice for companies to do mechanized tasks in Office 365. It is an online workflow service that automates tasks over the most generally perceived apps and services. It is routinely used to automate work processes between your favored applications and services, synchronize records, get notifications, assemble data, and altogether more for better SharePoint development and implementation. When you sign up, you can interface with more than 220 services and can organize data either on-premises or on cloud sources like SharePoint, Microsoft SQL Server and many more as the list of applications for SharePoint developers to use with Power Automate that grows continuously.

For example, you can automate the below-mentioned tasks like

  • Instantly respond to high-need warnings or messages.
  • Capture, track, and catch up with new sales clients.
  • Copy all email attachments to your OneDrive Business account.
  • Collect data about your business and share that data information with your team.
  • Automate an approval workflow.

Refer to the following online journals related to Power Automate (MS Flow) for more clarity on the topic.

Power Automate with Artificial Intelligence

Let’s get started by calling an Azure Function through Power Automate (MS Flow). But before that, a SharePoint developer must have active Azure and Office 365 subscriptions.

Call Azure Function Through Power Automate

SharePoint developers can use Azure Function to leverage the utilization of Power Automate, which makes it easy for you to automate business processes between Azure services and apps.

We will create an Azure function that will calculate the cost of the wind turbine repair based on the provided number of hours and turbine capacity and the revenue generated through the turbine in 24 hours. The Azure function also results in whether it is feasible to undergo wind turbine maintenance or repair criteria or not. After this function, we will configure a flow, based on wind turbines maintenance or repair criteria. If the turbine repair is feasible and non-expensive, then the flow will trigger an email to the respective email address that a repair is recommended.

Use Azure API Management to create an OpenAPI definition that helps you leverage Azure function

Let’s create a function that checks whether an emergency repair on a wind turbine is feasible and non-expensive.

Add a function app

A function app enables you to host a collection of functions as logical units for scaling, deployment, easy resource sharing, and deployment.

  • Navigate to the Azure portal. Click Create a resource link on the top-left corner of the portal page, choose Compute > Function App.
  • Pass Function App settings as mentioned below and click on Create to provision and create a new Function App.

Setting Suggested value Description
App name Globally unique name: turbineCostMgmt Logical name to identify your function app. Characters valid: a-z, 0-9 and –
Subscription Your subscription Azure subscription under which resource is created
Resource Group Name for your resource group: turbineCostMgmtResourceGroup Resource group name under which your function app resides
OS Windows Linux hosting is in preview currently
Hosting Plan Consumption plan Determines plan to allocate resources to your function app
Location Region of Azure resources: West Europe Select a region near you or your Azure resources
Runtime stack Choice of your language: .NET Core A runtime supporting your preferred programming language e.g .NET for C#
Storage Use default created a globally unique name Storage account for your function app
Application Insights Default Adds Application Insights resource, same as your app name
  • After creating the Function App, access the Notification icon on the top-right corner of the portal and verify the Deployment success message.
  • Click Go to the resource button shown in the above image to navigate to your newly created Function App. SharePoint developers can also choose Pin to dashboard to quickly access the created Function App from your Azure portal dashboard.

Add a function

We will use HTTP triggered function has two parameters:

  • Time (in hours) estimation for turbine repair or maintenance.
  • Capacity (in kilowatts) of the turbine.

The function will calculate the turbine repair cost, and the revenue made through the turbine in 24 hours.

Follow the below steps to create HTTP triggered function using the Azure portal:

  • In your function app, click the + icon next to Functions. Select In-portal and then Continue at the bottom.
  • Choose More Templates… and then Finish and view templates.
  • Choose HTTP Trigger.
  • Provide function Name as “TurbineRepair” and select Authorization level as “Function”. Click the Create.
  • Replace the default code inside run.csx script with the below code.
run.csx
#r "Newtonsoft.Json"
 
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
 
<strong>const</strong> double revenuePerkW = 0.12;
<strong>const</strong> double technicianCost = 250;
<strong>const</strong> double turbineCost = 100;
 
public <strong>static</strong> async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    <em>// Get query strings if they exist</em>
    int tempVal;
    int? hours = Int32.TryParse(req.Query["hours"], out tempVal) ? tempVal : (int?)<strong>null</strong>;
    int? capacity = Int32.TryParse(req.Query["capacity"], out tempVal) ? tempVal : (int?)<strong>null</strong>;
 
    <em>// Get request body</em>
    string requestBody = await <strong>new</strong> StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
 
    <em>// Use request body if a query was not sent</em>
    capacity = capacity ?? data?.capacity;
    hours = hours ?? data?.hours;
 
     <em>// Return bad request if capacity or hours are not passed in</em>
    <strong>if</strong> (capacity == <strong>null</strong> || hours == <strong>null</strong>){
        <strong>return</strong> <strong>new</strong> BadRequestObjectResult("Please pass capacity and hours on the query string or in the request body");
    }
    <em>// Formulas to calculate revenue and cost</em>
    double? revenueOpportunity = capacity * revenuePerkW * 24;  
    double? costToFix = (hours * technicianCost) +  turbineCost;
    string repairTurbine;
 
    <strong>if</strong> (revenueOpportunity > costToFix){
        repairTurbine = "Yes";
    }
    <strong>else</strong> {
        repairTurbine = "No";
    };
 
    <strong>return</strong> (ActionResult)<strong>new</strong> OkObjectResult(<strong>new</strong>{
        message = repairTurbine,
        revenueOpportunity = "$"+ revenueOpportunity,
        costToFix = "$"+ costToFix
    });
}

The above code returns Yes or No to determine whether an emergency turbine repair or maintenance is cost-effective, the revenue opportunity generated by the turbine in one day, and the expense or cost to repair the turbine.

  • Click the Save button.
  • Expand the test tab at the far right of the function app and select Test to verify the function. Pass below value inside the Request body, and then select Run.








    run.csx -> Test -> Request body
    {
    "hours": "6",
    "capacity": "2500"
    }


    run.csx -> Test -> Request body
    {
    “hours”: “6”,
    “capacity”: “2500”
    }




  • You can see below the value returned inside response body Output.








    Output JSON
    {"message":"Yes","revenueOpportunity":"$7200","costToFix":"$1600"}


    Output JSON
    {“message”:”Yes”,”revenueOpportunity”:”$7200″,”costToFix”:”$1600″}



    Finally, you have a function that indicates the feasibility and cost-effectiveness of emergency turbine maintenance and repairs. Now, SharePoint developers are ready to create an OpenAPI definition for the above Function App.

    Generate OpenAPI definition

    • In your function app, under Platform features, select API Management.
    • Click Create new link on the API Management page.
    • Pass API Management service settings as mentioned in the below table. Click Create to generate the API Management instance.

    Setting Suggested value Description
    Name Globally unique name: turbineCostMgmt-apim Auto-generated name depending on your function app.
    Subscription Azure subscription Azure subscription under which new resource is generated
    Resource Group Name of your resource group:turbineCostMgmtResourceGroup
    Resource group specified while creating your function
    Location Region of Azure resources: West Europe Select a region near you or your Azure resources
    Organization name Your organization name: TatvaSoft Name used in Azure portal and for email notifications
    Administrator email Your email address Email ID that receives API Management notifications
    Pricing tier Your pricing plan Azure pricing plan

    The API Management instance provisioning may take a few minutes. After provisioning is completed, a message as shown below will be displayed.

    • Select Enable Application Insights to view logs inside the function application, accept the defaults and then click Link API.
    • Click Select on Import Azure Functions dialog, where TurbineRepair function is highlighted.
    • Accept the defaults on the Create from Function App page and click Create to register API for the function.

    Test the API
    SharePoint developers need to test and check whether or not the API works before you utilize the OpenAPI definition.

    • Click POST operation on the Test tab of “turbineCostMgmt” function.
    • Provide values for hours and capacity in JSON format. Click Send.








      JSON Request body
      {
      "hours": "6",
      "capacity": "2500"
      }


      JSON Request body
      {
      “hours”: “6”,
      “capacity”: “2500”
      }




    • Observe the HTTP response.
    • Download OpenAPI definition file

      You can download your OpenAPI definition turbinecostmgmt.json file if your API works properly

      • Click Download OpenAPI definition at the top of API Management page.
      • Observe OpenAPI definition in the downloaded JSON file.

      Prerequisites

      • Power Automate account with the same authentication credentials as Azure Active Directory account.
      • Consumption Plan, as it requires limited utilization of resources and only pays for the time the function is executed.

      Note: The selection of Consumption Plan or App Service Plan depends on your needs.

      • SharePoint, to be used as a data source.

      Provision a SharePoint list

      Create a SharePoint list Turbines that you will use as a data source for the flow.

      The list will have the below columns:

      List ColumnData TypeDescription
      TitleSingle line of textName of the turbine
      LastServiceDateDate 
      MaxOutputNumberOutput of the turbine, in KwH
      ServiceRequiredYes/No 
      EstimatedEffortNumberEstimated time for the repair, in hours

      When you’re done with the creation of list columns, the default list view should look like the one below:

      Get Azure function URL

      You will require Azure Function URL in the flow later.

      • Under TurbineRepair function, click </> Get function URL link.
      • Copy function URL which is displayed by clicking Copy link.

      Configure a flow to call Azure function
      Once the SharePoint developer has run the Azure Function URL and a SharePoint list, you can configure a flow to call azure function.

      • Browse to https://flow.microsoft.com, select My flows and click New > Instant-from blank
      • Add When an item is created SharePoint trigger. Select Site Address as your SharePoint site name and required List Name as “Turbines” that contains the turbine data in SharePoint Trigger.
      • Specify a condition to execute the next set of actions. Insert a new step and add a new Condition control, which will add two branches: If yes and If no.
      • You can specify a condition to match a criterion and add steps/actions to one or both the branches based on the condition. Select the first box on the Condition card and choose ServiceRequired under Dynamic Content dialog returned through When an item is created trigger.
      • Add true for the condition i.e triggerBody()?[‘ServiceRequired’] is equal to true.

      SharePoint site list displays the value as Yes or No, but it is stored in Boolean form, either True or False. The above condition checks if ServiceRequired field value is set to Yes in the Turbines list. If it is, the flow executes If yes branch else the If no branch.

      • Click Add an action in the If yes branch and add a step (action) – HTTP-HTTP-HTTP action. Rename the HTTP action action to Calculate costs.
      • Change Method to “POST” and add Function URL copied earlier as URI to call the Turbine Repair Azure function. Add Body as shown below. You can also select a Dynamic Content dialog box to pass the Estimated Effort (for hours) and MaxOutput (for capacity) list item values.
        Action: Calculate costs -> Body {       "hours": "triggerBody()?['EstimatedEffort']",       "capacity": "triggerBody()?['MaxOutput']" }

        Action: Calculate costs -> Body
        {
        “hours”: “triggerBody()?[‘EstimatedEffort’]”,
        “capacity”: “triggerBody()?[‘MaxOutput’]”
        }

      • Provide flow name as Turbine Repair Approval and Save the flow.
      • At this point of time, check the Flow run by adding a new item or row in the Turbines list.
      • Navigate to Turbine Repair Approval flow and click on the Flow start date to check that the flow succeeds or not.
      • You can observe the output Body that the flow action returns: message > “Yes”, as well as revenueOpportunity (potential revenue) > “$7200” and costToFix (cost of repair) > “$2600” values from TurbineRepair Azure function it call.
      • Add a Compose action at the bottom of If yes branch to the store value of Message returned from Calculate costs action.
        Compose -> Inputs  body('Calculate_costs')['Message']

        Compose -> Inputs
        body(‘Calculate_costs’)[‘Message’]

      • Add another condition at the bottom of If yes branch below Compose operation.
      • Select the first box in Condition 2 card and add Output of Compose operation under Dynamic content tab.
      • Add Yes for the condition i.e outputs(‘Compose’) is equal to Yes. The flow executes next If yes or If no branch based on if Message value returned by Azure function is yes (repair required) or no (repair not recommended).
      • Add two Compose operations, one each to store repair cost and potential revenue returned by Calculate Costs action. We will be using these values later while sending an email.
        Compose 2 -> Inputs body('Calculate_costs')['costToFix']

        Compose 2 -> Inputs
        body(‘Calculate_costs’)[‘costToFix’]

        Compose 3 -> Inputs body('Calculate_costs')['revenueOpportunity']

        Compose 3 -> Inputs
        body(‘Calculate_costs’)[‘revenueOpportunity’]

      • Add an action Office 365 Outlook – Send an email at the bottom of “If yes branch” of the second condition to notify respective people regarding turbine repair as well as costs and potential revenue.
      • Note: SharePoint consultants can carry out several operations based on your requirement such as updating a SharePoint list or starting an approval process through Power Automate.

        Search for Office 365 Outlook and select the required action based on your email system.

        • After Office 365 outlook search and selecting the action, Pass a valid email address of the user in your organization in To field, add email Subject and compose email inside Body. Fetch the value of Title token for SharePoint list under Dynamic content tab and CostToFix and RevenueOpportunity from the above Compose 2 and Compose 3 operations respectively.
          Send an email -> Subject Recommended repair for triggerBody()?['Title']

          Send an email -> Subject
          Recommended repair for triggerBody()?[‘Title’]

          Send an email -> Body Based on our calculations, the cost to fix triggerBody()?['Title'] is outputs('Compose_2') and the revenue opportunity is outputs('Compose_3'). Please arrange for the repair to be made.

          Send an email -> Body
          Based on our calculations, the cost to fix triggerBody()?[‘Title’] is outputs(‘Compose_2’) and the revenue opportunity is outputs(‘Compose_3’). Please arrange for the repair to be made.

        • Save the flow. The completed flow should look like the one below:
        • Once flow configuration is completed, add a new item or row inside the Turbines list.
        • Adding a new item triggers the Turbine Repair Approval flow. On the flow page, check the Flow run.
        • If your flow ran successfully, you can observe flow operations by expanding various actions.
        • Verify the email account (Outlook) inbox for the person you passed in the To field of Send email action. The received email should look like the one below.
        • You can observe that the tokens have been replaced with the actual values from the SharePoint list and the TurbineRepair Azure function.

          Conclusion

          In this article, our development team has given a hit to this approach of Power Automate Azure Function calling consuming an Azure Function in MS Flow. Here, in Power Automate (MS Flow). SharePoint developers can collate data from various services like Dynamics 365, Salesforce, OneDrive, Dropbox, etc. and manage data in them. Power Automate can call the data returned from an Azure function into any service or vice-versa. Being a superset of Azure WebJob, Azure Function is also very cost-effective from business perspectives.

          Cite on our blog identified with the call of an Azure WebJob through the Power Automate.

          In this article, our development team has ensured that this approach of Power Automate Azure Function calling covers all that is necessary. Here, in Power Automate (MS Flow), SharePoint developers can collate data from various services like Dynamics 365, Salesforce, OneDrive, Dropbox, etc. and manage data in them. Power Automate can call the data returned from an Azure function into any service or vice-versa. We have tried to explain it using an example and showcased its features throughout the blog. Being a superset of Azure WebJob, Azure Function is also very cost-effective from business perspectives.

          Cite on our blog identified with the call of an Azure WebJob through the Power Automate.

Comments


Your comment is awaiting moderation.