Design and implement Azure PaaS compute and web and mobile services

  • 4/7/2018

Skill 4.6: Implement Azure Functions and WebJobs

Azure Functions is a serverless compute service that enables you to run code on-demand without having to explicitly provision or manage infrastructure. Use Azure Functions to run a script or piece of code in response to a variety of events from sources such as:

  • HTTP requests

  • Timers

  • Webhooks

  • Azure Cosmos DB

  • Blob

  • Queues

  • Event Hub

When it comes to implementing background processing tasks, the main options in Azure are Azure Functions and WebJobs. It is important to mention, however, that Functions are actually built on top of WebJobs. The choice to use one or the other really depends on the problem you are trying to solve. For example, if you already have an app service running a website or a web API and you require a background process to run in the same context, a WebJob makes the most sense. Here are two examples that may drive you to using a WebJob:

  • The Service Plan You want to share compute resources between the website or API and the WebJob.

  • Shared libraries The WebJob should share libraries that run the website or API.

Otherwise, for situations where you want to externalize a process so that it runs and scales independently from your web application or API environment, or you are implementing an event handler in response to some external event (i.e., a Webhook); Azure Functions are the more modern serverless technology to choose.

Create Azure Functions

The Azure portal gives you a quick and easy way to create a functions app, add functions based on a template and test the function.

To create a function app in the portal follow these steps (Figure 4-86):

  1. Navigate to the portal accessed via https://portal.azure.com.

  2. Select New on the command bar.

  3. Select Compute, and then Function App.

  4. Click Create and supply the app name, subscription, resource group, hosting plan, location, and storage plan (if you select Consumption plan).

    FIGURE 4-86

    FIGURE 4-86 The Create Function App blade

  5. After a few minutes, the Functions App is created (Figure 4-87).

    FIGURE 4-87

    FIGURE 4-87 A new function app

Implement a Webhook function

Visual Studio provides a complete development and debugging environment for Azure Functions with the addition of Azure Functions Extension. To create a Webhook function using Visual Studio 2017, follow these steps:

  1. Ensure you have the Functions App Visual Studio Extension installed first (Figure 4-88).

    FIGURE 4-88

    FIGURE 4-88 Azure Functions and WebJobs Tools

  2. In the New Project dialog, expand Visual C# > Cloud node, select Azure Functions, type a Name for your project, and click OK (Figure 4-89).

    FIGURE 4-89

    FIGURE 4-89 Selecting Azure Functions from the New Project dialog

  3. This creates a new Functions App in your subscription. You may have to log in to the Azure portal to complete the process.

  4. From Visual Studio, go to Solution Explorer, right-click the project node, and select Add > New Item. Select Azure Function, and click Add.

  5. From the New Azure Function dialog, select Generic WebHook, type the function name, and click OK (Figure 4-90).

    FIGURE 4-90

    FIGURE 4-90 Selecting the type of Azure Function

  6. This generates an initial implementation for your function. The FunctionName attribute sets the name of your function. The HttpTrigger(WebHookType = “genericJson”) attribute indicates the message that triggers the function.

    using Microsoft.Azure.WebJobs;
    using Microsoft.Azure.WebJobs.Host;
    using Newtonsoft.Json;
    using System.Net;
    using System.Net.Http;
    using System.Threading.Tasks;
    namespace SolVsFunctionapp
    {
        public static class GenericWebhookFunction
        {
            [FunctionName("GenericWebhookFunction")]
            public static async Task<object> Run([HttpTrigger(WebHookType =
    "genericJson")]HttpRequestMessage req, TraceWriter log)
            {
                log.Info($"Webhook was triggered!");
    
                string jsonContent = await req.Content.ReadAsStringAsync();
                dynamic data = JsonConvert.DeserializeObject(jsonContent);
    
                if (data.first == null || data.last == null)
                {
                 return req.CreateResponse(HttpStatusCode.BadRequest, new
                {
                     error = "Please pass first/last properties in the input
    object"
                });
            }
    
            return req.CreateResponse(HttpStatusCode.OK, new
            {
                greeting = $"Hello {data.first} {data.last}!"
            });
          }
        }
    }
  7. You ran run the function from Visual Studio directly using Azure Functions Tools. Press F5 to run. If prompted, accept the download and install Azure Functions Core tools.

  8. You can copy the URL of your function from the Azure Function runtime output (Figure 4-91).

    FIGURE 4-91

    FIGURE 4-91 The console output after running a Webhook function from Visual Studio

  9. You can now post a JSON payload to the function using any tool that an issue HTTP requests to test the function.

Create an event processing function

To create an event processing function, please complete these steps:

  1. Navigate to the portal accessed via https://portal.azure.com.

  2. Go to your Function App, such as the one created in the previous section, and click the + sign to create a new function (Figure 4-92).

    FIGURE 4-92

    FIGURE 4-92 The Function Apps blade where you can create a new function

  3. Select Timer and CSharp, and select Create This Function (Figure 4-93).

    FIGURE 4-93

    FIGURE 4-93 The Function Apps blade where you can choose the type of function

  4. This creates a skeleton function that runs based on a timer. You can edit the function.json file to adjust settings for the function (Figure 4-94).

    FIGURE 4-94

    FIGURE 4-94 A new timer-based function

  5. You can view the output of the function and any logs emitted as it executes.

Implement an Azure-connected function

To create an Azure-connected function using Azure Queues, follow these steps:

  1. Navigate to the portal accessed via https://portal.azure.com.

  2. Go to your Function App, such as the one used in the previous section, and click the + sign to create a new function.

  3. Select QueueTrigger - C#, provide a name for the function, provide the name of the queue and the storage account that it belongs to. Click Create to create the function (Figure 4-95).

    FIGURE 4-95

    FIGURE 4-95 The setup for a QueueTrigger

  4. A skeleton implementation for the function is created. This is triggered for each message written to the specified queue (Figure 4-96).

    FIGURE 4-96

    FIGURE 4-96 The code behind the QueueTrigger function

  5. To complete the integration, create the storage account and queue that you specified when creating the function. From the function app definition, select the Integrate tab, and select the storage queue under Triggers. Expand the Documentation link and enter the storage account name and key. The function will use these credentials to connect to the storage account (Figure 4-97).

FIGURE 4-97

FIGURE 4-97 The integration blade for setting up the storage queue trigger credentials

To test the function, add a message to the queue. After a few seconds the function log in the portal shows output from processing the message (Figure 4-98).

FIGURE 4-98

FIGURE 4-98 The log output for the function after processing a single message

Integrate a function with storage

To create a function integrated with Azure Storage Blobs, follow these steps:

  1. Navigate to the portal accessed via https://portal.azure.com.

  2. Go to your Function App, such as the one used in the previous section, and click the + sign to create a new function.

  3. Select BlobTrigger - C#, provide a name for the function, provide the path to the blob container item and the storage account that it belongs to. Click Create to create the function (Figure 4-99).

    FIGURE 4-99

    FIGURE 4-99 The setup for a BlobTrigger

  4. A skeleton implementation for the function is created. This is triggered for each blob written to the specified storage container (Figure 4-100).

    FIGURE 4-100

    FIGURE 4-100 The code behind the BlobTrigger function

  5. To complete the integration, create the storage account and blob container that you specified when creating the function. From the function app definition, select the Integrate tab, and select Azure Blob Storage under Triggers. Expand the Documentation link, and enter the storage account name and key. The function uses these credentials to connect to the storage account (Figure 4-101).

    FIGURE 4-101

    FIGURE 4-101 The integration blade for setting up the blob trigger credentials

  6. To test the function, add a file to the blob container. After a few seconds the function log in the portal shows output from processing the message, as illustrated in the previous section for Azure storage queues.

Design and implement a custom binding

Function triggers indicate how a function is invoked. There are a number of predefined triggers, some already discussed in previous sections, including:

  • HTTP triggers

  • Event triggers

  • Queues and topic triggers

  • Storage triggers

Every function must have one trigger. The trigger is usually associated with a data payload that is supplied to the function. Bindings are a declarative way to map data to and from function code. Using the Integrate tab (as shown in previous sections to connect a Queue to a function, for example) you can provide connection settings for such a data binding activity.

Debug a Function

You can use VS Code or Visual Studio 2017 to debug an Azure Function. For more information on working with local Functions projects and local debugging, see: https://docs.microsoft.com/en-us/azure/azure-functions/functions-run-local.

Implement and configure proxies

If you have a solution with many functions you’ll find it can become work to manage given the different URLs, naming, and versioning potentially related to each function. An API Proxy acts as a single point of entry to functions from the outside world. Instead of calling the individual function URLs, you provide a proxy as a facade to your different function URLs.

To create a simple API Proxy, follow these steps (Figure 4-102):

  1. Consider an existing function that includes the function code (API key) and any query string parameters in the URL such as the following example:

    https://sol-newfunctionapp.azurewebsites.net/api/
    AirplanesApi?code=N8eJPFEkD1MkOeQngOqRsaLVxeHRQ4QcxacFRdLtMDBdak3eeN/
    kNQ==&id=0099991
  2. API proxies require two important pieces of information:

    1. The Route Template Provides a template of how the proxies are triggered, for example a REST-compliant API path that removes the need for the function code and query string parameters:

      /api/airplanes/86327
    2. The Backend URL The function URL to match to.

    FIGURE 4-102

    FIGURE 4-102 The settings while creating a new API proxy

  3. Update the Backend URL too so that it uses the variables provided in the route template.

    https://sol-newfunctionapp.azurewebsites.net/api/{rest}Api?code=q/vTyTaw4wTzyFuY16wuMOnUPEhJLzRFqKRDXaChGz3/HzS0myMaNw==&id={id}.
  4. When you request the URL, the variables in the route template (i.e., {rest} and {id}) are replaced with whatever is passed in the request. For example, this URL:

    https://sol-newfunctionapp.azurewebsites.net/api/airplanes/3434

    Routes to this URL:

    https://sol-newfunctionapp.azurewebsites.net/api/airplanesApi?code=q/
    vTyTaw4wTzyFuY16wuMOnUPEhJLzRFqKRDXaChGz3/HzS0myMaNw==&id=3434

Integrate with App Service Plan

Functions can operate in two different modes:

  • Consumption Plan Where your function is allocated dynamically to the amount of compute power required to execute under the current load.

  • App Service Plan Where your function is assigned a specific app service hosting plan and is limited to the resources available to that hosting plan.

For more information about the difference between Consumption and App Service Plans see: https://docs.microsoft.com/en-us/azure/azure-functions/functions-scale. For more information about setting up an App Service Plan see: https://docs.microsoft.com/en-us/azure/app-service/azure-web-sites-web-hosting-plans-in-depth-overview.