Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Azure Serverless Computing Cookbook

You're reading from   Azure Serverless Computing Cookbook Build and monitor Azure applications hosted on serverless architecture using Azure functions

Arrow left icon
Product type Paperback
Published in Jun 2020
Publisher Packt
ISBN-13 9781800206601
Length 458 pages
Edition 3rd Edition
Tools
Concepts
Arrow right icon
Author (1):
Arrow left icon
Praveen Kumar Sreeram Praveen Kumar Sreeram
Author Profile Icon Praveen Kumar Sreeram
Praveen Kumar Sreeram
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Accelerating cloud app development using Azure Functions 2. Working with notifications using the SendGrid and Twilio services FREE CHAPTER 3. Seamless integration of Azure Functions with Azure Services 4. Developing Azure Functions using Visual Studio 5. Exploring testing tools for Azure functions 6. Troubleshooting and monitoring Azure Functions 7. Developing reliable serverless applications using durable functions 8. Bulk import of data using Azure Durable Functions and Cosmos DB 9. Configuring security for Azure Functions 10. Implementing best practices for Azure Functions 11. Configuring serverless applications in the production environment 12. Implementing and deploying continuous integration using Azure DevOps Index

Persisting employee details using Azure Table Storage output bindings

In the previous recipe, you created an HTTP trigger and accepted input parameters. Now, let's learn how to store input data in a persistent medium. Azure Functions supports many ways to store data. For this example, we'll store data in Azure Table storage, a NoSQL key-value persistent medium for storing semi-structured data. Learn more about it at https://azure.microsoft.com/services/storage/tables/.

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

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

Getting ready

This recipe showcases the ease of integrating an HTTP trigger and the Azure Table storage service using output bindings. The Azure HTTP trigger function receives data from multiple sources and stores user profile data in a storage table named tblUserProfile. We'll follow the prerequisites listed here:

Let's get started.

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:
    Choosing Azure Table Storage output binding
    Figure 1.10: New output bindings
  3. If you are prompted to install the bindings, click on Install; this will take a few minutes. Once the bindings are installed, choose the following settings for the Azure Table Storage output bindings:

    Table parameter name: This is the name of the parameter that will be used 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 the Storage account connection string is not displayed, click on new (as shown in Figure 1.11) to create a new one or to choose an existing storage account.

    The Azure Table storage output bindings should be as shown in Figure 1.11:

    Azure Table Storage output bindings settings
    Figure 1.11: Azure Table Storage output bindings settings
  4. Click on Save to save the changes.
  5. Navigate to the code editor by clicking on the function name.

    Note

    The following are the initial lines of the code for this recipe:

    #r "Newtonsoft.json"

    #r "Microsoft.WindowsAzure.Storage"

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

    Paste the following code into the editor. The code will accept the input passed by the end user and save it in Table storage; click Save:

    #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; } 
      }
  6. Execute the function by clicking on the Run button of the Test tab by passing the firstname and lastname parameters to the Request body.
  7. If there are no errors, you'll get a Status: 200 OK message as the output. Navigate to Azure Storage Explorer and view the Table storage to see whether a table named tblUserProfile was created successfully:
    Viewing data in Storage Explorer
Figure 1.12: Viewing data in Storage Explorer

How it works…

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

We have also added an additional parameter to handle 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.

Note

The input parameters are not validated in the code sample. However, in a production environment, it's important to validate them before storing them in any kind of persistent medium.

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

Note

Learn more about handling operations on the Azure Table storage service at https://docs.microsoft.com/azure/cosmos-db/tutorial-develop-table-dotnet.

Understanding storage connections

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

Application settings in the configuration pane
Figure 1.13: Application settings in the configuration blade

Navigate to App settings by clicking on the Configuration menu available in the General Settings section of the Platform features tab:

Clicking on the Configuration link in the General Settings section of the Platform features tab
Figure 1.14: Configuration blade

You learned how to save data quickly using Azure Table storage bindings. In the next recipe, you'll learn how to save profile picture paths to queues.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime