Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Events
Videos
Audiobooks
Packt Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Azure Serverless Computing Cookbook
Azure Serverless Computing Cookbook

Azure Serverless Computing Cookbook: Build and monitor Azure applications hosted on serverless architecture using Azure functions , Third Edition

Arrow left icon
Profile Icon Praveen Kumar Sreeram Profile Icon Kasam Shaikh Profile Icon Greg Leonardo
Arrow right icon
₹999.99 ₹3455.99
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (1 Ratings)
eBook Jun 2020 458 pages 3rd Edition
eBook
₹999.99 ₹3455.99
Paperback
₹4319.99
eBook + Subscription
₹1000 Monthly
Arrow left icon
Profile Icon Praveen Kumar Sreeram Profile Icon Kasam Shaikh Profile Icon Greg Leonardo
Arrow right icon
₹999.99 ₹3455.99
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (1 Ratings)
eBook Jun 2020 458 pages 3rd Edition
eBook
₹999.99 ₹3455.99
Paperback
₹4319.99
eBook + Subscription
₹1000 Monthly
eBook
₹999.99 ₹3455.99
Paperback
₹4319.99
eBook + Subscription
₹1000 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Azure Serverless Computing Cookbook

2. Working with notifications using the SendGrid and Twilio services

In this chapter, we will look at the following:

  • Sending an email notification using SendGrid service
  • Sending an email notification dynamically to the end user
  • Implementing email logging in Azure Blob Storage
  • Modifying the email content to include an attachment
  • Sending an SMS notification to the end user using the Twilio service

Introduction

One of the key features required for the smooth running of business applications is to have a reliable communication system between the business and its customers. The communication channel usually operates two-way, by either sending a message to the administrators managing the application or by sending alerts to customers via emails or SMS to their mobile phones.

Azure can integrate with two popular communication services: SendGrid for emails, and Twilio for working with text messages. In this chapter, we will learn how to leverage both of these communication services to send messages between business administrators and end users.

Figure 2.1 is the architecture that we will be using for utilizing SendGrid and Twilio Output Bindings with HTTP and queue triggers:

  1. Client applications (web/mobile) make Http Requests, which trigger the Http Trigger.
  2. The Http Trigger creates a message to the Queue.
  3. A Queue Trigger is invoked as soon as a message arrives at the queue.
  4. Send Grid Output Bindings is executed.
  5. An Email is sent to the end user.
  6. Twilio Output Bindings is executed.
  7. An SMS is sent to the end user:
    Architecture of SendGrid and Twilio output bindings
Figure 2.1: Architecture of SendGrid and Twilio output bindings

Sending an email notification using SendGrid service

In this recipe, we will learn how to create a SendGrid output binding and send an email notification, containing static content, to the website administrator. Since our use case involves just one administrator, we will be hard-coding the email address of the administrator in the To address field of the SendGrid output (message) binding.

Getting ready

We'll perform the following steps before moving on to the next section:

  1. We will create a SendGrid account API key from the Azure portal.
  2. We will generate an API key from the SendGrid portal.
  3. We will configure the SendGrid API key with the Azure Function app.

Creating a SendGrid account API key from the Azure portal

In this section, we'll be creating a Send service and also generate the API by performing the following steps:

  1. Navigate to the Azure portal and create a SendGrid Email Delivery account by searching for it in the marketplace, as shown in Figure 2.2:
    Searching for SendGrid email delivery in the Marketplace
    Figure 2.2: Searching for SendGrid Email Delivery in the marketplace
  2. In the SendGrid Email Delivery blade, click on the Create button to navigate to Create SendGrid Account. Select Free in the Pricing Tier options, provide all the other details, and then click on the Review + Create button to review this information. Finally, click on the Create button, as shown in Figure 2.3:
    Creating a SendGrid email delivery account by clicking on the Review+Create button
    Figure 2.3: Creating a SendGrid email delivery account

    Note

    At the time of writing, the SendGrid free account allows you to send 25,000 free emails per month. If you would like to send more emails, then you can review and change the pricing plans based on your needs.

  3. Make a note of the password entered in the previous step. Once the account is created successfully, navigate to SendGrid Account. You can use the search box available at the top.

SendGrid is not a native Azure service. So, we need to navigate to the SendGrid website to generate the API key. Let's learn how to do that next.

Generating credentials and the API key from the SendGrid portal

Let's generate the API key by performing the following steps:

  1. In order to utilize the SendGrid account in the Azure Functions runtime, we need to provide the SendGrid credentials as input for Azure Functions. You can generate those details from the SendGrid portal. Let's navigate to the SendGrid portal by clicking on the Manage button in the Essentials blade of SendGrid Account, as shown in Figure 2.4:
    Clicking on the Manage button in the Essentials pane of the SendGrid account
    Figure 2.4: Acquiring SendGrid credentials in the Manage blade
  2. In the SendGrid portal, click on the Account Details menu under Settings and copy the username, as shown in Figure 2.5:
    Clicking on the Account details pane and copying the SendGrid credentials
    Figure 2.5: Copying the SendGrid credentials
  3. In the SendGrid portal, the next step is to generate the API keys. Now, click on API Keys under the Settings section of the left-hand side menu, as shown in Figure 2.6:
    Generating the API keys
    Figure 2.6: Generating API keys
  4. On the API Keys page, click on Create API Key, as shown in Figure 2.7:
    Creating the API keys
    Figure 2.7: Creating API keys
  5. In the Create API Key pop-up window, provide a name and choose API Key Permissions, and then click on the Create & View button.
  6. After a moment, you will be able to see the API key. Click on the key to copy it to the clipboard, as shown in Figure 2.8:
    Copying the API keys
Figure 2.8: Copying the API key

Having copied the API key, we'll now configure it.

Configuring the SendGrid API key with the Azure Function app

Let's now configure the SendGrid API key by performing the following steps:

  1. Create a new App settings configuration in the Azure Function app by navigating to the Configuration blade, under the Platform features section of the function app, as shown in Figure 2.9:
    Creating a new app setting configuration
    Figure 2.9: Creating a new app setting configuration
  2. Click on the Save button after adding the App settings from the preceding step.

How to do it...

In this section, we will perform the following tasks:

  1. We will create a storage queue binding to the HTTP trigger.
  2. We will create a queue trigger to process the message of the HTTP trigger.
  3. We will create a SendGrid output binding to the queue trigger.

Creating a storage queue binding to the HTTP trigger

Let's create the queue bindings now. This will allow us to create a message to be added to the queue.

Perform the following steps:

  1. Navigate to the Integrate tab of the RegisterUser function and click on the New Output button to add a new output binding.
  2. Choose Azure Queue Storage and click on the Select button to add the binding and provide the values shown in Figure 2.10, and then click on the Save button. Please make a note of the Queue name (in this case, notificationqueue), which will be used in a moment:
    Creating a new output binding by adding various details
    Figure 2.10: Adding a new output binding
  3. Navigate to the Run method of the RegisterUser function and make the following highlighted changes. You added another queue output binding and added an empty message to trigger the queue trigger function. For now, you have not added a message to the queue. We will make changes to the NotificationQueueItem.AddAsync(""); method in the Sending an email notification dynamically to the end user recipe of the chapter:
    public static async Task<IActionResult> Run(
      HttpRequest req,
      CloudTable objUserProfileTable,
      IAsyncCollector<string> objUserProfileQueueItem,
      IAsyncCollector<string> NotificationQueueItem,
      ILogger log)
    {
         log.LogInformation("C# HTTP trigger function processed a request.");
        string firstname=null,lastname = null;
         ...
         ...
         await NotificationQueueItem.AddAsync("");
    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");
    }

Let's now proceed to create the queue trigger.

Creating a queue trigger to process the message of the HTTP trigger

In this section, you'll learn how to create a queue trigger by performing the following steps:

  1. Create an Azure Queue Storage Trigger by choosing the template shown in Figure 2.11:
    Creating an Azure Queue Storage Trigger
    Figure 2.11: Creating an Azure Queue Storage Trigger
  2. In the next step, provide the name of the queue trigger and provide the name of the queue that needs to be monitored for sending the notifications. Once you have provided all the details, click on the Create button to create the function:
    Creating a new function by adding a Queue name
    Figure 2.12: Creating a new function
  3. After creating the queue trigger function, run the RegisterUser function to see whether the queue trigger is being invoked. Open the RegisterUser function in a new tab and test it by clicking on the Run button. In the Logs window of the SendNotifications tab, you should see something similar to Figure 2.13:
    Invoking the queue trigger by running theRegisterUser function
Figure 2.13: Invoking the queue trigger by running the RegisterUser function

Once we have ensured that the queue trigger is working as expected, we need to create the SendGrid bindings to send the email in the following section.

Creating a SendGrid output binding to the queue trigger

Perform the following steps to create the SendGrid output bindings to send the email:

  1. Navigate to the Integrate tab of the SendNotifications function and click on the New Output button to add a new output binding.
  2. Choose the SendGrid binding and click on the Select button to add the binding.
  3. The next step is to install the SendGrid extensions (these are packages related to SendGrid). Click on the Install button to install the extensions if prompted, as shown in Figure 2.14. It might take a few minutes to install the extensions:
    Notification to install extensions in SendGrid bindings
    Figure 2.14: Notification to install extensions in the SendGrid bindings

    Note

    If there is no prompt notification, please delete the output binding and recreate it. You could also install the extensions manually by going through the instructions mentioned in https://docs.microsoft.com/azure/azure-functions/install-update-binding-extensions-manual.

  4. Provide the following parameters in the SendGrid output (message) binding:
    • Message parameter name: Leave the default value, which is message. We will be using this parameter in the Run method in a moment.
    • SendGrid API Key: Choose the App settings key that you created in the Configuration blade for storing the SendGrid API Key.
    • To address: Provide the email address of the administrator.
    • From address: Provide the email address from where you would like to send the email. This might be something like donotreply@example.com.
    • Message subject: Provide the subject that you would like to have displayed in the email subject.
    • Message Text: Provide the email body text that you would like to have in the body of the email.

      This is how the SendGrid output (message) binding should appear after providing all the fields:

      Adding various details in the SendGrid output (message) binding
Figure 2.15: Adding details in the SendGrid output (message) binding
  1. Once you review the values, click on Save to save the changes.
  2. Navigate to the Run method of the SendNotifications function and make the following changes:
    • Add a new reference for SendGrid, along with the SendGrid.Helpers.Mail namespace.
    • Add a new out parameter message of the SendGridMessage type.
    • Create an object of the SendGridMessage type. We will look at how to use this object in the next recipe, Sending an email notification dynamically to the end user.
  3. The following is the complete code of the Run method:
    #r "SendGrid"
    using System;
    using SendGrid.Helpers.Mail;
    public static void Run(string myQueueItem,out SendGridMessage message, ILogger log)
    {
        log.LogInformation($"C# Queue trigger function processed:
    {myQueueItem}");
        message = new SendGridMessage();
    }
  4. Now, let's test the functionality of sending the email by navigating to the RegisterUser function and submitting a request with some test values, as follows:
    {
    "firstname": "Bill",
    "lastname": "Gates",
    "ProfilePicUrl":"URL Here"
    }

How it works...

The aim of this recipe is to send an email notification to the administrator, updating them that a new registration was created successfully.

We have used one of the Azure function output bindings, named SendGrid, as a Simple Mail Transfer Protocol (SMTP) server for sending our emails by hard-coding the following properties in the SendGrid output (message) bindings:

  • The "from" email address
  • The "to" email address
  • The subject of the email
  • The body of the email

The SendGrid output (message) bindings will use the API key provided in the App settings to invoke the required APIs of the SendGrid library in order to send the emails.

Sending an email notification dynamically to the end user

In the previous recipe, we hard-coded most of the attributes related to sending an email to an administrator as there was just one administrator. In this recipe, we will modify the previous recipe to send a Thank you for registration email to the users themselves.

Getting ready

Make sure that the following steps are configured properly:

  • The SendGrid account is created and an API key is generated in the SendGrid portal.
  • An App settings configuration is created in the configuration of the function app.
  • The App settings key is configured in the SendGrid output (message) bindings.

How to do it…

In this recipe, we will update the code in the run.csx file of the following Azure functions:

  • RegisterUser
  • SendNotifications

Accepting the new email parameter in the RegisterUser function

Let's make changes to the RegisterUser function to accept the email parameter by performing the following steps:

  1. Navigate to the RegisterUser function, in the run.csx file, and add a new string variable that accepts a new input parameter, named email, from the request object, as follows. Also, note that we are serializing the UserProfile object and storing the JSON content to the queue message:
    string firstname=null,lastname = null, email = null;
    ...
    ...
    email = inputJson.email;
    ...
    ...
    UserProfile objUserProfile = new UserProfile(firstname, lastname, string profilePicUrl,email);
    ...
    ...
    await NotificationQueueItem.AddAsync(JsonConvert.SerializeObject(objUserProfile))
    ;
  2. Update the following code to the UserProfile class and click on the Save button to save the changes:
    public class UserProfile : TableEntity
    {
        public UserProfile (string firstname, string lastname, string profilePicUrl, string email)
    {
    ....
    ....
        this.ProfilePicUrl = profilePicUrl;
        this.Email = email;
    }
    ....
    ....
    public string ProfilePicUrl {get; set;}
    public string Email {get; set;}
    }

Let's now move on to retrieve the user profile information.

Retrieving the UserProfile information in the SendNotifications trigger

In this section, we will perform the following steps to retrieve the user information:

  1. Navigate to the SendNotifications function, in the run.csx file, and add the NewtonSoft.Json reference and also the namespace.
  2. The queue trigger will receive the input in the form of a JSON string. We will use the JsonConvert.Deserializeobject method to convert the string into a dynamic object so that we can retrieve the individual properties. Replace the existing code with the following code where we are dynamically populating the properties of SendGridMessage from the code:
    #r "SendGrid"
    #r "Newtonsoft.Json" using System;
    using SendGrid.Helpers.Mail;
    using Newtonsoft.Json;
    public static void Run(string myQueueItem,out SendGridMessage message, ILogger log)
    {
    log.LogInformation($"C# Queue trigger function processed:
    {myQueueItem}");
    dynamic inputJson = JsonConvert.DeserializeObject(myQueueItem); string FirstName=null, LastName=null, Email = null; FirstName=inputJson.FirstName;
    LastName=inputJson.LastName; Email=inputJson.Email;
    log.LogInformation($"Email{inputJson.Email}, {inputJson.FirstName
    + " " + inputJson.LastName}");
    message = new SendGridMessage();
    message.SetSubject("New User got registered successfully."); message.SetFrom("donotreply@example.com"); message.AddTo(Email,FirstName + " " + LastName);
    message.AddContent("text/html", "Thank you " + FirstName + " " + LastName +" so much for getting registered to our site.");
    }
  3. After making all of the aforementioned highlighted changes to the SendNotifications function, click Save. In order to test this, you need to execute the RegisterUser function. Let's run a test by adding a new input field email to the test request payload of the RegisterUser function, shown as follows:
    {
    "firstname": "Praveen",
    "lastname": "Sreeram",
    "email":"example@gmail.com",
    "ProfilePicUrl":"A valid url here"
    }
  4. This is the screenshot of the email that I have received:
    Email notification of successful registration
Figure 2.16: Email notification of successful registration

How it works...

We have updated the code of the RegisterUser function to accept another new parameter, named email.

The function accepts the email parameter and sends the email to the end user using the SendGrid API. We have also configured all the other parameters, such as the From address, subject, and body (content) in the code so that it can be customized dynamically based on the requirements.

We can also clear the fields in the SendGrid output bindings, as shown in Figure 2.17:

Clearing the fields in the SendGrid output bindings
Figure 2.17: Clearing the fields in the SendGrid output bindings

Note

The values specified in the code will take precedence over the values specified in the preceding step.

There's more...

You can also add HTML content in the body to make your email look more attractive. The following is a simple example where I have just applied a bold (<b>) tag to the name of the end user:

message.AddContent("text/html", "Thank you <b>" + FirstName + "</b><b> " + LastName +" </b>so much for getting registered to our site.");

Figure 2.18 shows the email, with my name in bold:

Customizing the email notification
Figure 2.18: Customizing the email notification

In this recipe, you have learned how to send an email notification dynamically to the end user. Let's now move on to the next recipe.

Implementing email logging in Azure Blob Storage

Most of the business applications for automated emails are likely to involve sending emails containing various notifications and alerts to the end user. At times, it is not uncommon for users to not receive any emails, even though we, as developers, don't see any error in the application while sending such notification alerts.

There might be multiple reasons why such users might not have received the email. Each of the email service providers has different spam filters that can block the emails from the end user's inbox. As these emails may have important information to convey, it makes sense to store the email content of all the emails that are sent to the end users, so that we can retrieve the data at a later stage for troubleshooting any unforeseen issues.

In this recipe, you will learn how to create a new email log file with the .log extension for each new registration. This log file can be used as redundancy for the data stored in Table storage. You will also learn how to store email log files as a blob in a storage container, alongside the data entered by the end user during registration.

How to do it...

Perform the following steps:

  1. Navigate to the Integrate tab of the SendNotifications function, click on New Output, and choose Azure Blob Storage. If prompted, you will have to install Storage Extensions, so please install the extensions to continue forward.
  2. Provide the requisite parameters in the Azure Blob Storage output section, as shown in Figure 2.19. Note the .log extension in the Path field:
    Adding various details in the Azure Blob Storage output
    Figure 2.19: Adding details in the Azure Blob Storage output
  3. Navigate to the code editor of the run.csx file of the SendNotifications function and make the following changes:

    Add a new parameter, outputBlob, of the TextWriter type to the Run method.

    Add a new string variable named emailContent. This variable is used to frame the content of the email. We will also use the same variable to create the log file content that is finally stored in the blob.

    Frame the email content by appending the required static text and the input parameters received in the request body, as follows:

    public static void Run(string myQueueItem,out SendGridMessage message, TextWriter outputBlob, ILogger log)
    ....
    ....
    string FirstName=null, LastName=null, Email = null;
    string emailContent;
    ....
    ....
    emailContent = "Thank you <b>" + FirstName + " " + LastName +"</b> for your registration.<br><br>" + "Below are the details that you have provided
    us<br> <br>"+ "<b>First name:</b> " +
        FirstName + "<br>" + "<b>Last name:</b> " +
        LastName + "<br>" + "<b>Email Address:</b> " + 
        inputJson.Email + "<br><br> <br>" + "Best
    Regards," + "<br>" + "Website Team";
    message.AddContent(new Content("text/html",emailContent));
    outputBlob.WriteLine(emailContent);
  4. In the RegisterUser function, run a test using the same request payload that we used in the previous recipe.
  5. After running the test, the log file will be created in the container named userregistrationemaillogs:
    Displaying the log file created in the container named userregistrationemaillogs
Figure 2.20: Displaying the log file created in userregistrationemaillogs

How it works…

We have created new Azure Blob Storage output bindings. As soon as a new request is received, the email content is created and written to a new .log file that is stored as a blob in the container specified in the Path field of the output bindings.

Modifying the email content to include an attachment

In this recipe, you will learn how to send a file as an attachment to the registered user. In our previous recipe, we created a log file of the email content, which we will use as an email attachment for this instance. However, in real-world applications, you might not intend to send log files to the end user.

Note

At the time of writing, SendGrid recommends that the size of the attachment shouldn't exceed 10 MB, though technically, your email can be as large as 20 MB.

Getting ready

This is a continuation of the Implementing email logging in Azure Blob Storage recipe. If you are reading this first, make sure to go through the previous recipes of this chapter beforehand.

How to do it...

In this section, we will need to perform the following steps before moving to the next section:

  1. Make the changes to the code to create a log file with the RowKey of the table. We will achieve this using the IBinder interface. The IBinder interface helps us in customizing the name of the file.
  2. Send this file as an attachment to the email.

Customizing the log file name using the IBinder interface

Perform the following steps:

  1. Navigate to the run.csx file of the SendNotifications function.
  2. Remove the TextWriter object and replace it with the variable binder of the IBinder type. The following is the new signature of the Run method:
    #r "SendGrid"
    #r "Newtonsoft.Json"
    #r "Microsoft.Azure.WebJobs.Extensions.Storage"
    using System;
    using SendGrid.Helpers.Mail;
    using Newtonsoft.Json;
    using Microsoft.Azure.WebJobs.Extensions.Storage;
    public static void Run(string myQueueItem,
    out SendGridMessage message,
    IBinder binder,
    ILogger log)
  3. Since you have removed the TextWriter object, the outputBlob.WriteLine(emailContent); function will no longer work. Let's replace it with the following piece of code:
    using (var emailLogBloboutput = binder.Bind<TextWriter>(new BlobAttribute($"userregistrationemaillogs/
    { inputJson.RowKey}.log")))
    {
    emailLogBloboutput.WriteLine(emailContent);
    }
  4. In the RegisterUser function, run a test using the same request payload that we used in the previous recipes.
  5. You can see the email log file that is created using the RowKey of the new record stored in Azure Table storage, as shown in Figure 2.21:
    Email log file created using RowKey stored in Azure Table storage
Figure 2.21: Email log file stored in Azure Table storage

Adding an attachment to the email

To add an attachment to the email, perform the following steps:

  1. Add the following code to the Run method of the SendNotifications function, and save the changes by clicking on the Save button:
    message.AddAttachment(FirstName +"_"+LastName+".log", System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(emailContent)),
          "text/plain",
          "attachment",
          "Logs"
          );
  2. Run a test using the same request payload that we used in the previous recipes.
  3. Figure 2.22 shows the email, along with the attachment:
    Displaying the email along with the attachment
Figure 2.22: Displaying an email along with the attachment

Note

Learn more about the SendGrid API at https://sendgrid.com/docs/API_Reference/api_v3.html.

In this recipe, you have learned how to add an attachment to the email. Let's now move on to the next recipe.

Sending an SMS notification to the end user using the Twilio service

In most of the previous recipes of this chapter, we have worked with SendGrid triggers to send emails in different scenarios. In this recipe, you will learn how to send notifications via text messages, using one of the leading cloud communication platforms, named Twilio.

Note

Twilio is a cloud communication platform-as-a-service platform. Twilio allows software developers to programmatically make and receive phone calls, send and receive text messages, and perform other communication functions using its web service APIs. Learn more about Twilio at https://www.twilio.com/.

Getting ready

In order to use the Twilio SMS output (objsmsmessage) binding, you need to do the following:

  1. Create a trial Twilio account at https://www.twilio.com/try-twilio.
  2. Following the successful creation of the account, grab the ACCOUNT SID and AUTH TOKEN from the Twilio Dashboard and save it for future reference, as shown in Figure 2.23. You need to create two App settings in the Configuration blade of the function app for both of these settings:
    Copying ACCOUNT SID and AUTH TOKEN from the Twilio dashboard
    Figure 2.23: Twilio dashboard
  3. In order to start sending messages, you need to create an active number within Twilio, which will be used as the From number that you will use to send the SMS. You can create and manage numbers in the Phone Numbers Dashboard. Navigate to https://www.twilio.com/console/phone-numbers/incoming and click on the Get Started button.

    On the Get Started with Phone Numbers page, click on Get your first Twilio phone number, as shown in Figure 2.24:

    Activating the number using Twilio
    Figure 2.24: Activating your number using Twilio
  4. Once you get your number, it will be listed as follows:
    Displaying the activated number
    Figure 2.25: Displaying the activated number
  5. The final step is to verify a number to which you would like to send an SMS. Click on the + icon, as shown in Figure 2.26, provide your number, and then click on the Call Me button:
    Verification of the phone number
    Figure 2.26: Verifying a phone number
  6. You can have only one number in your trial account, which can be verified on Twilio's verified page: https://www.twilio.com/console/phone-numbers/verified. Figure 2.27 shows the list of verified numbers:
    Displaying the verified caller IDs
Figure 2.27: Verified caller IDs

How to do it...

Perform the following steps:

  1. Navigate to the Application settings blade of the function app and add two keys for storing TwilioAccountSID and TwilioAuthToken, as shown in Figure 2.28:
    Adding two keys for storing TwilioAccountSID and TwilioAuthToken
    Figure 2.28: Adding two keys for storing TwilioAccountSID and TwilioAuthToken
  2. Go to the Integrate tab of the SendNotifications function, click on New Output, and choose Twilio SMS.
  3. Click on Select and provide the following values to the Twilio SMS output bindings. Please install the extensions of Twilio. To manually install the extensions, refer to the https://docs.microsoft.com/azure/azure-functions/install-update-binding-extensions-manual article. The From number is the one that is generated in the Twilio portal, which we discussed in the Getting ready section of this recipe:
    Adding various parameters in the Twilio SMS output pane
    Figure 2.29: Twilio SMS output blade
  4. Navigate to the code editor and add the following lines of code. In the following code, I have hard-coded the To number. However, in real-world scenarios, you would dynamically receive the end user's mobile number and send the SMS via code:
    ...
    ...
    #r "Twilio"
    #r "Microsoft.Azure.WebJobs.Extensions.Twilio"
    ...
    ...
    using Microsoft.Azure.WebJobs.Extensions.Twilio; using Twilio.Rest.Api.V2010.Account;
    using Twilio.Types;
    public static void Run(string myQueueItem,
    out SendGridMessage message, IBinder binder,
    out CreateMessageOptions objsmsmessage,
    ILogger log)
    ...
    ...
    ...
    message.AddAttachment(FirstName +"_"+LastName+".log", System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(emailContent)),
          "text/plain",
          "attachment",
          "Logs"
          );
    objsmsmessage = new CreateMessageOptions(new PhoneNumber("+91 98492*****"));
    objsmsmessage.Body = "Hello.. Thank you for getting registered.";
    }
  5. Now, do a test run of the RegisterUser function using the same request payload.
  6. Figure 2.30 shows the SMS that I have received:
    SMS received from the Twilio account
Figure 2.30: SMS received from the Twilio account

How it works...

We have created a new Twilio account and copied the account ID and app key to the App settings of the Azure Function app. The account ID and app key will be used by the function app runtime in order to connect to the Twilio API to send the SMS.

For the sake of simplicity, I have hard-coded the phone number in the output bindings. However, in real-world applications, you would send the SMS to the phone number provided by the end users.

Watch the following video to view a working implementation: https://www.youtube.com/watch?v=ndxQXnoDIj8.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Test, troubleshoot, and monitor Azure functions to deliver high-quality and reliable cloud-centric applications
  • Understand Visual Studio's integrated developer experience for Azure functions
  • Explore best practices for organizing and refactoring code within the Azure functions

Description

This third edition of Azure Serverless Computing Cookbook guides you through the development of a basic back-end web API that performs simple operations, helping you understand how to persist data in Azure Storage services. You'll cover the integration of Azure Functions with other cloud services, such as notifications (SendGrid and Twilio), Cognitive Services (computer vision), and Logic Apps, to build simple workflow-based applications. With the help of this book, you'll be able to leverage Visual Studio tools to develop, build, test, and deploy Azure functions quickly. It also covers a variety of tools and methods for testing the functionality of Azure functions locally in the developer's workstation and in the cloud environment. Once you're familiar with the core features, you'll explore advanced concepts such as durable functions, starting with a "hello world" example, and learn about the scalable bulk upload use case, which uses durable function patterns, function chaining, and fan-out/fan-in. By the end of this Azure book, you'll have gained the knowledge and practical experience needed to be able to create and deploy Azure applications on serverless architectures efficiently.

Who is this book for?

If you are a cloud developer or architect who wants to build cloud-native systems and deploy serverless applications with Azure functions, this book is for you. Prior experience with Microsoft Azure core services will help you to make the most out of this book.

What you will learn

  • Implement continuous integration and continuous deployment (CI/CD) of Azure functions
  • Develop different event-based handlers in a serverless architecture
  • Integrate Azure functions with different Azure services to develop enterprise-level applications
  • Accelerate your cloud application development using Azure function triggers and bindings
  • Automate mundane tasks at various levels, from development to deployment and maintenance
  • Develop stateful serverless applications and self-healing jobs using durable functions

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 19, 2020
Length: 458 pages
Edition : 3rd
Language : English
ISBN-13 : 9781800203150
Vendor :
Microsoft
Concepts :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jun 19, 2020
Length: 458 pages
Edition : 3rd
Language : English
ISBN-13 : 9781800203150
Vendor :
Microsoft
Concepts :

Packt Subscriptions

See our plans and pricing
Modal Close icon
₹800 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
₹4500 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts
₹5000 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 12,065.97
Azure for Architects
₹4319.99
Azure DevOps Explained
₹3425.99
Azure Serverless Computing Cookbook
₹4319.99
Total 12,065.97 Stars icon

Table of Contents

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

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(1 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
USHA Oct 06, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great Book 👍, the author has explained very deeply each and every topic, best time to read and update your self to learn serverless infrastructure in the very easiest way.I strongly recommend this book to everyone who wants to understand each concept in depth.Special thanks to Author 💐
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.

Modal Close icon
Modal Close icon