Build a Serverless app in 30 minutes with Azure Functions and Logic Apps

Overview

In this lab we will build a serverless app to respond to events streaming off an Event Hub. It will start with an Event Hub, which we will push to an Azure Function to process, and finally an Azure Logic App will orchestrate as needed.

Getting Started

  1. Log into the machine for the lab TECH-CAD-ILL201
  2. You may want to increase the resolution to full screen for easier navigation
  3. You should have accounts on the right-hand side of Azure and Office 365
  4. Go to the Azure Portal

Creating Azure Resources

You should now be at the Azure Dashboard. Here you can spin up the resources you need

Azure Event Hubs

Azure Event Hubs is a big-data and high-volume event handler in Azure. We will use it to push data from simulated IoT Devices.

  1. Click New in the top left, select Internet of Things and Event Hubs
  2. Give it a globally unique name, either pricing tier is fine, create a new resource group, move to whatever location you want, and pin to the dashboard.
  3. Event Hubs will take about 30 seconds to deploy – feel free to jump to start creating the Azure Function while you wait.
  4. Open the Event Hub namespace resource after deployment, and click to create a new Event Hub.
  5. Name the event hub iot, give it 6 partitions, and leave the rest as default
  6. Click Shared access policies on the left hand menu and you should see the default RootManageSharedAccessKey. Open it and copy the Connection string-primary key. BE SURE you get the one that is prefaced Connection string- and not just the primary key.
  7. Copy and paste the connection string into something like “Notepad” for later (or keep the tab open. You’ll need this connection string later).

Azure Functions

Azure Functions is serverless compute for doing on-demand processing of any event. We will use this to analyze data streaming off our event hub.

  1. Click New in the top left, select Serverless function app
  2. Give a globally unique name, put in your resource group from before, leave as a Consumption plan (pay-only-when-use), whatever location you want, create a new storage account, and pin to your dashboard. Enable application insights

Azure Logic Apps

Azure Logic Apps provides serverless orchestration and integration. We will use this to to fire off a business workflow whenever an IoT event requires manual intervention

  1. Click New in the top left, select Enterprise integration and Logic App
  2. Give it a unique name, select your existing resource group, whatever location you want, pin to your dashboard and create.

Building the app

Before we start writing the app, we will be using the local Azure Storage emulator to build. So open the start menu and fine the Azure Storage Emulator and open it so it will start running.

Once that is running, we can continue into VS 2017.

  1. Open Visual Studio 2017 on the computer taskbar.
  2. Click File, New -> Project
  3. Under Visual C# select Cloud category and choose the Azure Functions project. Give it any name you want and select OK.
  4. On the Function version selector, select Azure Functions v1 (.NET Framework)
  5. Select they Empty template and click OK to create the function app project.

The Azure Function project should now be scaffolded in your local account. A few files you should note:

Configuring the Event Hubs Trigger

To get the Azure Function connected to the Event Hub, we need to create an app setting with the Event Hub connection string (pulled from the section above).

  1. Open the local.settings.json file
  2. Add a new property in the Values object for an EventHub connection string. It should look like the below, only with your Azure Event Hub connection string:

NOTE: Your connection string should NOT have an ‘EntityPath=’ near the end. If it does you have a specific hub connection string, and Functions requires a namespace

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "AzureWebJobsDashboard": "UseDevelopmentStorage=true",
    "EventHub": "Endpoint=YourEventHubConnectionString"
  }
}
  1. Now that you have a connection for Event Hubs configured, right-click your project and select Add and New Item to add a new function into the app.
  2. Select Azure Function, you can change the name or leave as Function1.cs, and click Add
  3. Choose Event Hub trigger. Connection refers to the app setting set above, so type in EventHub. Path is the name of the Event Hub, so type in iot.
  4. Open the new .cs file created (like Function1.cs) and notice the code that will run on an event hub.

Testing the function locally

One of the unique capabilities of Azure Functions is the ability to run the function runtime locally, set breakpoints, and test.

  1. Click the run button at the top of the toolbar.

    You’ll notice the Azure Functions runtime starts up in a seperate window. It will take a few seconds to initialize and now will be connected to the Event Hub and listening to events.
  2. Go to https://aka.ms/awesome-test
    • This is a simple test app to send a message like the following to your event hub. If you have any troubles with it you can also download the Azure Service Bus Explorer, extract, and open the ServiceBusExplorer.exe program. It will want you to paste in your Event Hub connection string, but should have an option to right-click and send a message (like the below sample) to your Event Hub. Feel free to use whatever tool works for your needs.
{ "type": "alert", "device": "readylab", "location": "seattle"}
  1. This will open a website to send a test event. Just paste in your Event Hub connection string (from creating event hub) and submit and it should send one message to your Event Hub.

  2. Switch back over to the Azure Function runtime window. You should see a test event got recieved (sometimes takes a few seconds).

  3. Go back into Visual Studio, set a breakpoint on the log, and send another event. You’ll notice the breakpoint is hit, you can hover over myEventHubMessage and click Continue to continue.

  4. Click the stop button (or close the Azure Function popout) to close the function.

Adding business logic to the function

We want to start a business process whenever an IoT Event is an “Alert.”

  1. Add in the function code so it looks like the following:
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.WebJobs.ServiceBus;
 
namespace FunctionApp1
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static void Run(
            [EventHubTrigger("iot", Connection = "EventHub")]IoTMessage myEventHubMessage, 
            TraceWriter log)
        {
            log.Info($"C# Event Hub trigger function processed a message: {myEventHubMessage.device}");
            if(myEventHubMessage.type == "alert")
            {
                log.Info("Alert message received");
                // Fire a logic app
            }
        }
 
        public class IoTMessage
        {
            public string type { get; set; }
            public string device { get; set; }
            public string location { get; set; }
        }
    }
}

Now whenever an IoT message comes in with an alert, it will hit the if statement and (for right now) log an alert. We’ll come back later and add in the logic to call Logic Apps.

Building the Logic App

  1. Return to the Azure Subscription and open the Logic App created earlier. The designer should open since it’s empty, but if not just click the Edit button on the top menu.

  2. Scroll down and select the Blank Logic App template.

  3. Notice the number of triggers or events that Logic Apps can start from. For our purposes let’s just use the Request trigger and When a HTTP Request is received

  4. Click New step and add an action to Send an Email with the Office 365 Outlook connector. Use your Microsoft AAD account to authenticated - or if you wish use the Office 365 credentials provided to authenticate. DON’T use your Azure credentials which may be the default. Send to any email you wish with any message you prefer. In my testing I found that sending to my personal email from the pre-provisioned O365 account would get spam filtered, so consider sending to your temporary admin account (admin@xxxxx.onmicrosoft.com) and using office.com to check for mail. If you use your Microsoft AAD account to authenticate and connect it should send mail without issue.

  5. Click the Save button and then test it out with the Run button. You can see what happens during a run, and the status of each step. You should also get an email You could continue to add more complex logic, integrate with services like Microsoft Teams or Google Docs, but for now we’ll leave this simple app.

  6. After testing, click the Designer button on the top menu (next to save) and open the HTTP request trigger. You’ll notice you can now copy the URL needed to invoke this logic app. Keep this tab open or copy this into something like “Notepad” so you can paste it into your Azure Function.

Now that we have the URL and Logic App built, we just need to connect the Function to it and publish the function.

Connecting all of the pieces

Go back into your Azure Function and make the final code look like this (feel free to copy paste). You’ll need to replace “https://YOUR-LOGIC-APP-URL” with your URL copied from above.

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.WebJobs.ServiceBus;
using System.Net.Http;
using System.Threading.Tasks;
 
namespace FunctionApp1
{
    private const string logicappURL = "https://YOUR-LOGIC-APP-URL";
    private static HttpClient client = new HttpClient(); 

    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task Run(
            [EventHubTrigger("iot", Connection = "EventHub")]IoTMessage myEventHubMessage, 
            TraceWriter log)
        {
            log.Info($"C# Event Hub trigger function processed a message: {myEventHubMessage.device}");
            if(myEventHubMessage.type == "alert")
            {
                log.Info("Alert message received");
                // Fire a logic app
                await client.PostAsJsonAsync<string>(logicappURL, $"Alert for {myEventHubMessage.device} at {myEventHubMessage.location}");
            }
        }
 
        public class IoTMessage
        {
            public string type { get; set; }
            public string device { get; set; }
            public string location { get; set; }
        }
    }
}

You can now try running the funciton locally, and you should notice when you send a test event it runs the function which calls the logic app.

Publishing the function

  1. Right click the project in Visual Studio 2017
  2. Select Publish
  3. Choose Select Existing and choose Create Profile
  4. In the top-right dropdown, select Add an account and add your Azure account
  5. Open your resource group in the selector and select the Function you created during setup
  6. Click Publish to publish to this function app

It will take some time deploy the bits to the Azure Function. The last piece it won’t yet have is your connection string to the Event Hub. This right now is only in your local.settings.json. So the last step you need to do is open the Application Settings for your cloud function and paste the connect string there.

  1. Click Manage Application Settings… from the publish screen.
  2. Add a new one called EventHub and paste in the connection string from earlier (can also copy and paste from your local.settings.json file if you forgot)
  3. Click Apply to save the settings, and Ok to close.

Now the function app you had published locally is running in Azure. If you continue to simulate messages you should notice your Logic app continues to fire - even if Visual Studio is closed. If 10,000 events were pushed, your Function App would scale to process them all on-demand.

Extra Credit

  1. In Azure, open your Azure Logic App and Azure Function and notice the runs or logs that are emitted as it runs
    • The Logic App has a run history you can verify runs are being fired and executed
    • The Function has both streamed logs (if you open the Event Grid triggered function - named something like Function1 - at the bottom there should be a Show Logs tab you can open to observe logs. After firing you should see a few logs sent)
  2. Add steps to your logic app to do more actions
  3. Open “Application Insights” from your Azure Function. A few tabs from App Insights that are worth diving into:
    • Select the Analytics section to open analytics. Here you can query traces and requests that are being generated. For example in the query editor you could double-click traces and click “run” to see all traces
    • Select the Live Stream tile and you can observe the load in real time. Since we are only sending a message or two you likely won’t notice much of any traffic. But this is useful if pushing traffic at high-loads as you can observe how many instances are being run and messages per second being processed in real-time.

Conclusion

Hopefully you were successful and understand the power and speed in which you can ship cloud-scale applications with serverless. If you have any questions or need any help feel free to contact me at jehollan@microsoft.com