Creating Azure Functions in Visual Studio 2017: HTTP Triggered Azure Functions

Posted by

Preface

This article of getting accustomed to serverless functions will help a developer to learn what Azure functions are, how to create an Azure function from Visual Studio, publish and test the function on Azure. The article will also teach how to debug a published Azure function from Visual Studio.

Introduction

With the latest situation of the serverless Azure story, Azure Functions can now be developed in Visual Studio, just like any other. NET project type. This means we can use the familiar and powerful features and workflows of Visual Studio when developing Azure Functions. We can write, unit test, and debug function code locally before publishing it up to the cloud. The purpose of this article is to cover the concept of Azure functions i.e. the serverless functions or precompiled functions supported by Azure.

In this two-article series of learning Azure Functions, we’ll cover we’re going to be learning how to get started with Azure Functions in Visual Studio, we’ll get a high-level overview of Azure Functions, and have a look at the Visual Studio development environment. We’ll be creating a new Azure Function in our Function project, we’ll learn how we can run this function on our local development machine, and how we can publish it to Azure right from within Visual Studio. Once we’ve learned how to create a basic function, in the following article, we’ll learn how we can create precompiled functions that work with the different Azure storage features, such as Blobs and Queues.

Azure

Azure is a cloud platform from Microsoft and provides numerous resources in context on cloud computing. One of the resource is virtual machine i.e. a fully functional machine of your choice with the choice of your configurations and operating system could be created within seconds with just a few clicks and you can access the machine remotely from anywhere with your secure credentials and do whatever you want for e.g. hosting your web site, developing applications, creating production or test environment for your software, etc. Let’s see step by step how we can achieve that.

Azure Functions and Serverless Computing

Talking about the definitions from here,

“Azure Functions is the serverless computing service hosted on the Microsoft Azure public cloud. Azure Functions, and serverless computing, in general, is designed to accelerate and simplify application development.”

The first thing to note about Azure Functions is that they operate in a fully-managed environment. Essentially what this means is that we don’t have to go and create or manage virtual machines. Microsoft provides and provisions all the underlying hardware that our Azure Functions are based on. One of the benefits of this is that it gives us high reliability because we don’t have to manually manage the underlying infrastructure. Another benefit is that we don’t have to worry about going and applying security patches to the underlying infrastructure. Microsoft will take care of this for us. It is, however, up to us to ensure that the systems that we’re building on top of Azure Functions are appropriately secured and managed. Another benefit of this fully- managed environment is that it gives us automatic scaling. The Azure Functions platform will automatically scale our functions out to deal with variations in incoming request volume. If we’re executing our Azure Functions on the Consumption plan, then we’re only going to pay when the functions are executed. Another benefit of Azure Functions is that we need to write less boilerplate code, and one of the reasons for this is that our Azure Functions can easily integrate with a range of Azure services. For example, integrating our function with Azure Blob storage is as simple as configuring the correct attributes on our C# code.


Learning Serverless Azure Functions

Following are the two articles to completely cover HTTP triggered Azure Functions, Queue triggered Azure Functions and Blob triggered Azure Functions.

  1. Creating Azure Functions in Visual Studio 2017
  2. Mastering Blob Triggers and Queue Storage Triggers
    Prerequisites

Azure Account Setup

If one does not have a paid Azure account, one could leverage Azure’s new account’s benefits of giving $200 credits. That means if you are new to Azure and wants to play around with its free trial, you’ll get $200 credits that you can use to explore Azure. If you are new to Azure and do not have an account, follow the following process, else directly login to your portal.

  1. Open the Azure web site i.e. azure.microsoft.com


  1. Click on Start free to create your free Azure account and get $200 as credits.


Creating an account and claiming $200 would need your credit/debit card for verification purposes only and will not deduct any amount from your card. You can play around with this credit and account for 30 days. You’ll see the signup page, where you fill all your information and signup step by step. Once signed-up successfully, you’ll see the link to the portal as shown below.


Click on the portal and you land up on the dashboard and are ready to use/play around with Azure.


Setup Development Environment

Before jumping into writing Azure Functions, let’s make sure we set up our development environment accordingly. We’ll use Visual Studio 2017 here. You can use any edition of Visual Studio 2017 for this tutorial. The pre-requisite is to have Azure Development enabled on your Visual Studio. You can check that in Visual Studio installation itself as shown below.

Case Study

In this article, we’ll create a function which will allow a credit card application to be made. This function will use an HTTP trigger that’s configured to allow only POST requests. This HTTP POST will contain the JSON for the credit card application details. We’re going to decouple the taking of credit card applications from the scoring by way of an Azure storage queue. So once this HTTP function executes, the application is going to be returned to a queue. We’re then going to create a process application function, which will take this function to the queue and determine whether the credit card application is successful or not. If the application is successful, then we’re going to write a blob to Azure Blob storage. This blob will be written to a separate accepted blob container, and if the credit card application was not successful, in other words, it was rejected, then the application will be written to a different blob storage container. We’ll then go and create an accepted application function to process accepted credit card applications, and we’ll also create a rejected application function to process applications that were declined.

Creating Azure Function in Visual Studio 2017

Let’s follow step by step procedure to create an Azure function project and add Azure Functions to it. At the end, we’ll publish the created Azure Functions to Azure portal. We’ll create a module that accepts the Credit card applications and based on certain criteria accepts and rejects the application

Add Azure Function Project

  1. Open the Visual Studio and create a new project.

  1. Choose “Cloud” from the project template type list and then “Azure Functions” as the project type. Give a meaningful name to your project and click “OK”.

2. To start with, choose Empty as a project type and click “OK” to create the project.

  1. Once done, the project will look like as shown in the below image. I gave the name “LearnAzureFunctions” to the project while creating a project and the same is shown as a project in visual studio solution.

Add an Http-triggered Azure Function

Now that our Azure Function project is ready we can add multiple functions to this project. Let’s start adding those to fulfill our case study objective.

  1. Right-click the project and add a new Azure Function as shown in the following image.

  1. Choose the type as Azure Function and give it a meaningful name for e.g. in our case “ApplyForCC”.

  1. Choose the type Http trigger as function type and in the access rights, you might see several options. For now, choose the option for the access rights to be limited to Function only and click “OK”.

  1. Once done, we’ll get our function as shown below. Note that this is an Http trigger function and so could be executed like an API through browser or API clients. If we look closely to it, it has the FunctionName attribute containing the name of the function and Task that returns Http response like Web APIs. The Run method is the method execute when this API is hit, it takes authorization level as a parameter. Since we set the access rights to “Function” level, it showed AuthorizationLevel.Function and has HTTP verbs like getting and post. The method also takes the route as a parameter, the request and the log i.e. TraceWriter class instance to write logs as shown in the method when it says log.Info(“C# HTTP trigger function processed a request.”)

Following is the complete class code generated. The method processes the request and expects a “name” query parameter from the request. If it founds the “name” query parameter, it returns the “OK” response i.e. 200 else it returns “Bad Request” response.

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Threading.Tasks;

using Microsoft.Azure.WebJobs;

using Microsoft.Azure.WebJobs.Extensions.Http;

using Microsoft.Azure.WebJobs.Host;

namespace LearnAzureFunctions

{


public
static
class
ApplyForCC

{

[FunctionName(ApplyForCC)]


public
static
async TaskHttpResponseMessage Run(

[HttpTrigger(AuthorizationLevel.Function,

get, post,

Route = null)]HttpRequestMessage req,

TraceWriter log)

{

log.Info(C#
HTTP trigger function processed a request.);

parse query parameter

string name = req.GetQueryNameValuePairs()

.FirstOrDefault(q = string.Compare(q.Key, name, true) == 0)

.Value;

if (name == null)

{

Get request body

dynamic data = await req.Content.ReadAsAsyncobject();

name = data.name;

}

return name == null

req.CreateResponse(HttpStatusCode.BadRequest, Please pass a name on the query string or in the request body)

req.CreateResponse(HttpStatusCode.OK, Hello + name);

}

}

}

  1. Let’s modify the method a bit to only accept post requests, so remove the “Get” attribute from the parameters list as shown below.

  1. Now, compile the application and run it by clicking on “arrow action button” as shown below or you can also press F5 to run the application.

  1. Once, the function is in running mode, the func.exe console window will be launched. If you monitor it closely, it shows in the details that it found a new function as LearnAzureFunctions.ApplyForCC.Run and after the job host starts, it shows the end point of our ApplyForCC function. We can test this end-point with POST requests via any web API client like Postman. We’ll do that in the following section.

Test and Debug the Http trigger function with Postman

  1. Once the application is up and running, we can test our function via Postman. If you do not have Postman app, do install it to test the API calls. After installing the app, open the app from start explorer as shown below.

  1. Get the function URL from the console window and make a POST request as shown below. Notice that we get the 404 bad request error. If you remember it, the error is returned from the Run method because no parameter named “name” was supplied.

  1. Let’s correct that request and make the request with the name parameter. So, append the query string name = “Akhil” and press send. Note that we get 200 i.e. OK response with a response text saying “Hello Akhil”. So our Azure function works locally.

  1. Now, if you check the console window, we see the request and response there saying Executing “ApplyForCC” and when executed, it says “Executed” and the response sent as well.

  1. You can also debug the method by putting the breakpoint in the function and make a request. We see the name parameter set to “Akhil” as shown below.

Introducing Model

Our Http trigger works fine. We’ll now introduce a model i.e. for credit card application that would be taken as an input by our Azure Function and the application would be processed accordingly.

  1. Add a new class named CCApplication and add the following code i.e. class along with properties to it.

namespace LearnAzureFunctions

{

public
class
CCApplication

{

public
string Name { get; set; }

public
int Age { get; set; }

public
string Occupation { get; set; }

public
float YearlyIncome { get; set; }

}

}

Our solution looks exactly as shown in the following image.

  1. Make some modifications in the Azure Function. Read the credit card application model from the request and log the name of the person in the application and send the response back saying the request for a credit card has been received for that name. Run the application so that our console window is launched before we test it.

Following is the code for the implementation.

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Threading.Tasks;

using Microsoft.Azure.WebJobs;

using Microsoft.Azure.WebJobs.Extensions.Http;

using Microsoft.Azure.WebJobs.Host;

namespace LearnAzureFunctions

{

public
static
class
ApplyForCC

{

[FunctionName(“ApplyForCC”)]

public
static
async Task<HttpResponseMessage> Run(

[HttpTrigger(AuthorizationLevel.Function,

“post”,

Route = null)]HttpRequestMessage req,

TraceWriter log)

{

log.Info(“C# HTTP trigger function processed a request.”);

CCApplication ccApplication = await req.Content.ReadAsAsync<CCApplication>();

log.Info($”Received Credit Card Application from : {ccApplication.Name });

return req.CreateResponse(HttpStatusCode.OK,

$”Application received and submitted for {ccApplication.Name});

}

}

}

  1. Now again go back to Postman to test this function. This time the function does not expect a query parameter but a model from the body of the request. So, define a JSON in the request body and send the request as POST like before.

  1. You can place the debugger in the method to check the parameters of the received request. As we see in the following image.


  1. Now back in the Postman we get the response as expected that the application for a credit card has been received for the name in the model i.e. in our case “Akhil Mittal”.


Publish Azure Function to Azure Portal from Visual Studio

Time to publish the local function developed in Visual Studio as a Function App in the Azure portal. Make sure you have an account in Azure and you are logged in to the portal.

  1. Right-click on the project and you’ll get the option in context menu to Publish. Click that option.


  1. On the next screen, if you are publishing it for the first time, leave the radio button selection as shown below alternatively if you are publishing the existing application, you can select the “Select Existing” radio for that. Select the publish target as “Azure Function App” and click in Publish.


  1. If you are already logged in to your Microsoft account in Visual Studio it is good else, it will ask you to login to the Microsoft account to access Azure portal services before you proceed. The next step will ask you to provide the App Service configurations before you publish the function.
  2. Provide the function name, the subscription should auto-populate, the resource group (you can create new or use an existing one). Select a hosting plan, give it a name for e.g. “CCAppFunctionPlan”, location as “Central US” and I have opted for the size as “Consumption” as you see in the following image. If we select the Consumption plan, notice this warning here telling us that the Consumption App Service Plans are only available for Function Apps, but that’s fine because we’re creating a function app. And what this means is we’ll only be charged when the functions execute. Let’s click OK, and finally, we can select an existing storage account here or we can create a new one. So, let’s go and create a new storage account. And we’ll call this storage account “ccappfunction“, and we’ll leave the Account Type here as the default.


  1. Now, go ahead now and hit Create, and this will create our App Service, and it will also deploy our function app including our ApplyForCC function to Azure.


When the publish is completed a publish profile would be created as shown below.


  1. Go to the Azure portal and on the dashboard, we see our CCAppFunction app service created, and the ccappfunction storage account and CCAppFunctionPlan service plan created successfully.


  1. Double click the CCAppFunction i.e. our App service that can hold multiple functions. In our case, till now it is only on a function that it holds i.e. “ApplyForCC”. On the CCAppFunction page, you’ll see the functions list at the left side and when you expand it, you’ll see the ApplyForCC function there. Click on that function and see the details of that function. On the overview page i.e. the details page of the function, you can see its status as running and the URL of the function as well. Remember that endpoint we were using while testing the function from local, this is the same endpoint now made public by Azure.


Testing the Serverless Azure Function

If we click on the Manage tab, we can see several keys here. If we just go back to Visual Studio and check our function, see that we set the AuthorizationLevel to Function. This means that we need to provide a function key when we call the function once it’s being deployed to Azure. If we just go back to the portal, we can see we’ve got a default function key added automatically for us, and if we want to, we can add additional function keys, and we can see the key value.


  1. Now, click on the ApplyForCC function tab again and get the function URL by clicking in the “Get Function URL” link as shown below. Note that we cannot change the function definition here as it is in read-only mode. Anything that needs to be changed should be done from Visual Studio itself and can be published again.


  1. Copy the URL.


  1. Head back to Postman and make a new POST request with the copied Azure Function URL from the portal. Make sure you have the body has the JSON like we were given earlier.


  1. Once the request is sent, we receive the response that “Application received and submitted for Akhil”. This shows that our function deployed on Azure is actually working and we are getting the responses. Let’s check that.


  1. Go back to the portal, click on Monitor tab and we see that the success count is shown as 1. If you click on that we see the log for our function i.e. called Invocation Log which shows the details of the function like duration, status, last ran and function that got executed.


  1. In the logs section as shown below, we see the logging text that we were doing in the function code itself.


Debugging the Azure Function from Visual Studio

We’ll try to debug the deployed Azure function from Visual Studio here.

  1. Go back to Visual Studio and open “Cloud Explorer” as shown below.


  1. Select your subscription to Azure there in the list and click on AppServices, we see that our function name appears there that is the function deployed on the cloud. Right click on CCAppFunction and click on Attach Debugger.


  1. Once the debugger is attached, a browser will be launched with the function URL as shown below.


  1. Go back to Postman and again make a request like made earlier with the hosted URL of the function app.


  1. Once the request is sent, we see the debugger point is hit in our function in visual studio that means we are debugging the function. You can check the request and the request body for the parameters. Press F5 to continue.


  1. In the Postman, we see the response received as 200.



Conclusion

In this detailed article, we learned what are Azure functions and Function Apps. How to code an Azure function locally in Visual Studio, debug and test it and publish the function to Azure portal. We learned how to test the deployed Azure function and debug the same using Visual Studio. In the next article that is the continuation article, we’ll learn about storage queues and blob storage. Happy Coding!

Source Code: https://github.com/akhilmittal/LearnAzureFunctions

Advertisements

2 comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.