Home Cloud & Networking Azure Serverless Computing Cookbook - Second Edition

Azure Serverless Computing Cookbook - Second Edition

By Praveen Kumar Sreeram , Jason Marston
books-svg-icon Book
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Developing Cloud Applications Using Function Triggers and Bindings
About this book
Microsoft provides a solution for easily running small segments of code in the cloud with Azure Functions. The second edition of Azure Serverless Computing Cookbook starts with intermediate-level recipes on serverless computing along with some use cases demonstrating the benefits and key features of Azure Functions. You’ll explore the core aspects of Azure Functions, such as the services it provides, how you can develop and write Azure Functions, and how to monitor and troubleshoot them. As you make your way through the chapters, you’ll get practical recipes on integrating DevOps with Azure Functions, and providing continuous integration and continuous deployment with Azure DevOps. This book also provides hands-on, step-by-step tutorials based on real-world serverless use cases to guide you through configuring and setting up your serverless environments with ease. You will also learn how to build solutions for complex, real-world, workflow-based scenarios quickly and with minimal code using Durable Functions. In the concluding chapters, you will ensure enterprise-level security within your serverless environment. The most common tips and tricks that you need to be aware of when working with Azure Functions on production environments will also be covered in this book. By the end of this book, you will have all the skills required for working with serverless code architecture, providing continuous delivery to your users.
Publication date:
November 2018
Publisher
Packt
Pages
424
ISBN
9781789615265

 

Developing Cloud Applications Using Function Triggers and Bindings

In this chapter, we will cover the following recipes:

  • Building a backend Web API using HTTP triggers
  • Persisting employee details using Azure Storage table output bindings
  • Saving the profile images to Queues using Queue output bindings
  • Storing the image in Azure Blob Storage
 

Introduction

Every software application needs backend components that are responsible for taking care of business logic and storing the data in some kind of storage, such as databases and filesystems. Each of these backend components could be developed using different technologies. Azure serverless technology also allows us to develop these backend APIs using Azure Functions.

Azure Functions provide many out-of-the-box templates that solve most common problems, such as connecting to storage, building Web APIs, and cropping images. In this chapter, we will learn how to use these built-in templates. Apart from learning about the concepts related to Azure serverless computing, we will also try to implement a solution to a basic domain problem of creating components, which is required for any organization who wants to manage internal employee information.

The following is a simple diagram that will help you understand what we will achieve in this chapter:

 

Building a backend Web API using HTTP triggers

We will use the Azure serverless architecture to build a Web API using HTTP triggers. These HTTP triggers can be consumed by any frontend application that is capable of making HTTP calls.

Getting ready

Let's start our journey of understanding Azure serverless computing using Azure Functions by creating a basic backend Web API that responds to HTTP requests:

We will be using C# as the programming language throughout this book. Most of these functions are developed using the Azure Functions V2 runtime. However, there are a few recipes that are not yet supported in V2 runtime, which is mentioned in the respective recipes. Hopefully, by the time you read this book, Microsoft will have made those features available for V2 runtime as well.

How to do it...

Perform the following steps:

  1. Navigate to the Function App listing page by clicking on the Function Apps menu, which is available on the left-hand side.
  2. Create a new function by clicking on the + icon:
  1. You will see the Azure Functions for .NET - getting started page, where you will be prompted to choose the type of tools you would like to use. You can choose the one you are the most interested in. For the initial few chapters, we will use the In-portal option, where you can quickly create Azure Functions right from the portal without any tools. Later, in the following chapters, we will use Visual Studio and Azure Functions Core Tools to create our functions:
  1. Next select More templates and click on Finish and view templates, as shown in the following screenshot:
  1. In the Choose a template below or go to the quickstart section, choose HTTP trigger to create a new HTTP trigger function:
  1. Provide a meaningful name. For this example, I have used RegisterUser as the name of the Azure Function.
  2. In the Authorization level drop-down, choose the Anonymous option. We will learn more about the all authorization levels in Chapter 9, Implementing Best Practices for Azure Functions:
  1. Click on the Create button to create the HTTP trigger function.
  1. As soon as you create the function, all the required code and configuration files will be created automatically and the run.csx file will be opened for you so that you can edit the code. Remove the default code and replace it with the following code. I have added two parameters (firstname and lastname), which will be displayed in the output when the HTTP trigger is triggered:
#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<IActionResult> Run(
HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string firstname=null,lastname = null;
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

dynamic inputJson = JsonConvert.DeserializeObject(requestBody);
firstname = firstname ?? inputJson?.firstname;
lastname = inputJson?.lastname;

return (lastname + firstname) != null
? (ActionResult)new OkObjectResult($"Hello, {firstname + " " + lastname}")
: new BadRequestObjectResult("Please pass a name on the query" + "string or in the request body");
}
  1. Save these changes by clicking on the Save button, which is available just above the code editor.
  2. Let's try and test the RegisterUser function using the Test console. Click on the Test tab to open the Test console:
  1. Enter the values for firstname and lastname in the Request body section:

Make sure that you select POST in the HTTP method drop-down.

  1. Once you have reviewed the input parameters, click on the Run button, which is available at the bottom of the Test console:
  1. If the input request workload is passed correctly with all the required parameters, you will see a Status 200 OK, and the output in the Output window will be like what's shown in the preceding screenshot.

How it works...

We have created the first basic Azure Function using HTTP triggers and made a few modifications to the default code. The code just accepts the firstname and lastname parameters and prints the name of the end user with a Hello {firstname} {lastname} message as a response. We also learned how to test the HTTP trigger function right from the Azure Management portal.

For the sake of simplicity, I didn't perform validations of the input parameter. Make sure that you validate all the input parameters in the applications that are running on your production environment.

See also

The Enabling authorization for function apps recipe in Chapter 9, Implementing Best Practices for Azure Functions.

 

Persisting employee details using Azure Storage table output bindings

In the previous recipe, you learned how to create an HTTP trigger and accept the input parameters. Now, let's work on something interesting, that is, storing the input data into a persistent medium. Azure Functions gives us the ability to store data in many ways. For this example, we will store the data in Azure Table storage.

Getting ready

In this recipe, you will learn how easy it is to integrate an HTTP trigger and the Azure Table storage service using output bindings. The Azure HTTP trigger function receives the data from multiple sources and stores the user profile data in a storage table named tblUserProfile.

We will take the following prerequisites into account:

How to do it...

Perform the following steps:

  1. Navigate to the Integrate tab of the RegisterUser HTTP trigger function.
  2. Click on the New Output button, select Azure Table Storage, and then click on the Select button:
  1. You will be prompted to install the bindings. Click on Install. This should take a take a few minutes. Once the bindings are installed, choose the following settings of the Azure Table storage output bindings:

    • Table parameter name: This is the name of the parameter that you will be using in the Run method of the Azure Function. For this example, provide objUserProfileTable as the value.
    • Table name: A new table in Azure Table storage will be created to persist the data. If the table doesn't exist already, Azure will automatically create one for you! For this example, provide tblUserProfile as the table name.
    • Storage account connection: If you don't see the Storage account connection string, click on new (as shown in the following screenshot) to create a new one or choose an existing storage account.
    • The Azure Table storage output bindings should be as follows:
  1. Click on Save to save your changes.
  2. Navigate to the code editor by clicking on the function name and paste in the following code. The following code accepts the input that's passed by the end user and saves it in Table Storage:
#r "Newtonsoft.Json"
#r "Microsoft.WindowsAzure.Storage"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Microsoft.WindowsAzure.Storage.Table;

public static async Task<IActionResult> Run(
HttpRequest req,
CloudTable objUserProfileTable,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string firstname=null,lastname = null;
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic inputJson = JsonConvert.DeserializeObject(requestBody);
firstname = firstname ?? inputJson?.firstname;
lastname = inputJson?.lastname;
UserProfile objUserProfile = new UserProfile(firstname, lastname);
TableOperation objTblOperationInsert = TableOperation.Insert(objUserProfile);
await objUserProfileTable.ExecuteAsync(objTblOperationInsert
);
return (lastname + firstname) != null
? (ActionResult)new OkObjectResult($"Hello, {firstname + " " + lastname}")
: new BadRequestObjectResult("Please pass a name on the query" + "string or in the request body");
}

class UserProfile : TableEntity
{
public UserProfile(string firstName,string lastName)
{
this.PartitionKey = "p1";
this.RowKey = Guid.NewGuid().ToString();
this.FirstName = firstName;
this.LastName = lastName;
}
UserProfile() { }
public string FirstName { get; set; }
public string LastName { get; set; }
}
  1. Let's execute the function by clicking on the Run button of the Test tab by passing the firstname and lastname parameters in the Request body:
  1. If everything went well, you should get a Status 200 OK message in the Output box, as shown in the preceding screenshot. Let's navigate to Azure Storage Explorer and view the table storage to see whether the table named tblUserProfile was created successfully:

How it works...

Azure Functions allows us to easily integrate with other Azure services, just by adding an output binding to the trigger. For this example, we have integrated the HTTP trigger with the Azure Storage table binding and also configured the Azure Storage account by providing the storage connection string and the Azure Storage table name in which we would like to create a record for each of the HTTP requests that's received by the HTTP trigger.

We have also added an additional parameter for handling the table storage, named objUserProfileTable, of the CloudTable type, to the Run method. We can perform all the operations on Azure Table storage using objUserProfileTable.

The input parameters are not validated in the code sample. However, in your production environment, it's important that you validate them before storing them in any kind of persisting medium.

We also created a UserProfile object and filled it in with the values we received in the request object, and then passed it to a table operation.

You can learn more about handling operations on the Azure Table storage service at https://docs.microsoft.com/en-us/azure/storage/storage-dotnet-how-to-use-tables.

Understanding storage connection

When you create a new storage connection (refer to step 3 of the How to do it... section of this recipe), new App settings will be created:

You can navigate to App settings by clicking on the Application settings menu, which is available in the GENERAL SETTINGS section of the Platform features tab:

What is the Azure Table storage service?

Partition key and row key

The primary key of the Azure Table storage table has two parts:

  • Partition key: Azure Table storage records are classified and organized into partitions. Each record that's located in a partition will have the same partition key (p1, in our example).
  • Row key: A unique value should be assigned to each of the rows.

There's more...

The following are the very first lines of code in this recipe:

#r "Newtonsoft.json"
#r "Microsoft.WindowsAzure.Storage"

The preceding lines of code instruct the runtime function to include a reference to the specified library in the current context.

 

Saving the profile images to Queues using Queue output bindings

In the previous recipe, you learned how to receive two string parameters, firstname and lastname, in the Request body, and stored them in Azure Table storage. In this recipe, we'll add a new parameter named ProfilePicUrl for the profile picture of the user that is publicly accessible via the internet. In this recipe, you will learn how to receive the URL of an image and save the URL in the Blob container of an Azure Storage account.

You might be thinking that the ProfilePicUrl input parameter could have been used to download the picture from the internet in the previous recipe, Persisting employee details using Azure Storage table output bindings. We didn't do this because the size of the profile pictures might be huge, considering the modern technology that's available today, and so processing images on the fly in the HTTP requests might hinder the performance of the overall application. For that reason, we will just grab the URL of the profile picture and store it in Queue, and later we can process the image and store it in the Blob container.

Getting ready

We will be updating the code of the RegisterUser function that we used in the previous recipes.

How to do it...

Perform the following steps:

  1. Navigate to the Integrate tab of the RegisterUser HTTP trigger function.
  2. Click on the New Output button, select Azure Queue Storage, and then click on the Select button.
  3. Provide the following parameters in the Azure Queue Storage output settings:
    • Message parameter name: Set the name of the parameter to objUserProfileQueueItem, which will be used in the Run method
    • Queue name: Set the value of the Queue name to userprofileimagesqueue
    • Storage account connection: Make sure that you select the right storage account in the Storage account connection field
  4. Click on Save to create the new output binding.
  5. Navigate back to the code editor by clicking on the function name (RegisterUser, in this example) or the run.csx file and make the changes marked bold that are given in the following code:
public static async Task<IActionResult> Run(
HttpRequest req,
CloudTable objUserProfileTable,
IAsyncCollector<string> objUserProfileQueueItem,
ILogger log)
{

....

string firstname= inputJson.firstname;
string profilePicUrl = inputJson.ProfilePicUrl;
await objUserProfileQueueItem.AddAsync(profilePicUrl);

....
objUserProfileTable.Execute(objTblOperationInsert);
}
  1. In the preceding code, we added Queue output bindings by adding the IAsyncCollecter parameter to the Run method and just passing the required message to the AddAsync method. The output bindings will take care of saving the ProfilePicUrl into the Queue. Now, Click on Save to save the code changes in the code editor of the run.csx file.
  2. Let's test the code by adding another parameter, ProfilePicUrl, in the Request body and then click on the Run button in the Test tab of the Azure Function code editor window. The image that's used in the following JSON might not exist when you are reading this book. So, make sure that you provide a valid URL of the image:
{
"firstname": "Bill",
"lastname": "Gates",
"ProfilePicUrl":"https://upload.wikimedia.org/wikipedia/ commons/1/19/Bill_Gates_June_2015.jpg"
}
  1. If everything goes well you will see a Status : 200 OK message. The image URL that you have passed as an input parameter in the Request body will be created as a Queue message in the Azure Storage Queue service. Let's navigate to Azure Storage Explorer and view the Queue named userprofileimagesqueue, which is the Queue name that we provided in step 3. The following is a screenshot of the Queue message that was created:

How it works...

In this recipe, we added Queue message output binding and made the following changes to the code:

  • Added a new parameter named out string objUserProfileQueueItem, which is used to bind the URL of the profile picture as a Queue message content
  • Used the AddAsync method of IAsyncCollector to use the Run method, which saves the profile URL to the Queue as a Queue message
 

Storing the image in Azure Blob Storage

In the previous recipe, we stored the image URL in the queue message. Let's learn how to trigger an Azure Function (Queue Trigger) when a new queue item is added to the Azure Storage Queue service. Each message in the Queue is the URL of the profile picture of a user, which will be processed by the Azure Functions and stored as a Blob in the Azure Storage Blob service.

Getting ready

In the previous recipe, we learned how to create Queue output bindings. In this recipe, you will grab the URL from the Queue, create a byte array, and then write it to a Blob.

This recipe is a continuation of the previous recipes. Make sure that you have implemented them.

How to do it...

Perform the following steps:

  1. Create a new Azure Function by choosing Azure Queue Storage Trigger from the templates.
  1. Provide the following details after choosing the template:

    • Name your function: Provide a meaningful name, such as CreateProfilePictures.
    • Queue name: Name the Queue userprofileimagesqueue. This will be monitored by the Azure Function. Our previous recipe created a new item for each of the valid requests that came to the HTTP trigger (named RegisterUser) into the userprofileimagesqueue Queue. For each new entry of a queue message to this Queue storage, the CreateProfilePictures trigger will be executed automatically.
    • Storage account connection: The connection of the storage account where the Queues are located.
  2. Review all the details and click on Create to create the new function.
  3. Navigate to the Integrate tab, click on New Output, choose Azure Blob Storage, and then click on the Select button.
  4. In the Azure Blob Storage output section, provide the following:
    • Blob parameter name: Set it to outputBlob
    • Path: Set it to userprofileimagecontainer/{rand-guid}
    • Storage account connection: Choose the storage account where you would like to save the Blobs and click on the Save button:
  1. Click on the Save button to save all the changes.
  1. Replace the default code of the run.csx file of the CreateProfilePictures function with the following code. The following code grabs the URL from the Queue, creates a byte array, and then writes it to a Blob:
        using System;
public static void Run(Stream outputBlob,string myQueueItem,
TraceWriter log)
{
byte[] imageData = null;
using (var wc = new System.Net.WebClient())
{
imageData = wc.DownloadData(myQueueItem);
}
outputBlob.WriteAsync(imageData,0,imageData.Length);
}
  1. Click on the Save button to save changes. Make sure that there are no compilation errors in the Logs window:
  1. Let's go back to the RegisterUser function and test it by providing the firstname, lastname, and ProfilePicUrl fields, like we did in the Saving the profile images to Queues using Queue output bindings recipe.
  2. Navigate to the Azure Storage Explorer and look at the userprofileimagecontainer Blob container. You will find a new Blob:
  1. You can view the image in any tool (such as MS Paint or Internet Explorer).

How it works...

We have created a Queue trigger that gets executed as and when a new message arrives in the Queue. Once it finds a new Queue message, it reads the message, and as we know, the message is a URL of a profile picture. The function makes a web client request, downloads the image data in the form of a byte array, and then writes the data into the Blob, which is configured as an output Blob.

There's more...

The rand-guid parameter will generate a new GUID and is assigned to the Blob that gets created each time the trigger is fired.

It is mandatory to specify the Blob container name in the Path parameter of the Blob storage output binding while configuring the Blob storage output. Azure Functions creates one automatically if it doesn't exist.

You can only use Queue messages when you would like to store messages that are up to 64 KB in size. If you would like to store messages greater than 64 KB, you need to use the Azure Service Bus.
About the Authors
  • Praveen Kumar Sreeram

    Praveen Kumar Sreeram is an author, Microsoft Certified Trainer, and certified Azure Solutions Architect. He has over 15 years of experience in the field of development, analysis, design, and the delivery of applications of various technologies. His projects range from custom web development using ASP.NET and MVC to building mobile apps using the cross-platform Xamarin technology for domains such as insurance, telecom, and wireless expense management. He has been given the Most Valuable Professional award twice by one of the leading social community websites, CSharpCorner, for his contributions to the Microsoft Azure community through his articles. Praveen is highly focused on learning about technology, and blogs about his learning regularly. You can also follow him on Twitter at @PrawinSreeram. Currently, his focus is on analyzing business problems and providing technical solutions for various projects related to Microsoft Azure and .NET Core.

    Browse publications by this author
  • Jason Marston

    Jason Marston is a Cloud Solution Architect based in England. He was recruited by Microsoft because of his OSS background. Jason has worked with Java since version 1 and has a long history with open source. He has over 30 years' experience of developing software and now helps organizations migrate and modernize legacy applications to the cloud. Jason was an SME in the Worldwide Communities project at Microsoft and, as part of the leadership team for those communities, helped many people solve their problems by adopting Java on Azure. In his spare time, Jason reads science fiction books and has two children who think he is a geek/nerd.

    Browse publications by this author
Azure Serverless Computing Cookbook - Second Edition
Unlock this book and the full library FREE for 7 days
Start now