Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions

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'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 resources 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.
 
Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
 

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 want 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, otherwise directly login to your portal.

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

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions

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

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions

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.

Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions 

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

Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
 

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.

Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
 

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 a step by step procedure to create an Azure function project and add Azure Functions to it. In the end, we’ll publish the created Azure Functions to the 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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  1. Choose “Cloud” from the project template type list and then “Azure Functions” as the project Give a meaningful name to your project and click “OK”.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  1. To start with, choose Empty as a project type and click “OK” to create the project.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  1. Once done, the project will look like as shown in the below. I gave the name “LearnAzureFunctions” to the project while creating a project and the same is shown as a project in Visual Studio Solution.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions

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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  1. Choose the type as Azure Function and give it a meaningful name for e.g. in our case “ApplyForCC”.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  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”.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  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 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.”)

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions

    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.
    1. using System.Linq;  
    2. using System.Net;  
    3. using System.Net.Http;  
    4. using System.Threading.Tasks;  
    5. using Microsoft.Azure.WebJobs;  
    6. using Microsoft.Azure.WebJobs.Extensions.Http;  
    7. using Microsoft.Azure.WebJobs.Host;  
    8.   
    9. namespace LearnAzureFunctions  
    10. {  
    11.   public static class ApplyForCC  
    12.   {  
    13.     [FunctionName(ApplyForCC)]  
    14.     public static async TaskHttpResponseMessage Run(  
    15.       [HttpTrigger(AuthorizationLevel.Function,  
    16.           get, post,  
    17.           Route = null)]HttpRequestMessage req,  
    18.       TraceWriter log)  
    19.     {  
    20.       log.Info(C# HTTP trigger function processed a request.);  
    21.   
    22.   
    23.        parse query parameter  
    24.   
    25.       string name = req.GetQueryNameValuePairs()  
    26.           .FirstOrDefault(q = string.Compare(q.Key, name, true) == 0)  
    27.           .Value;  
    28.   
    29.       if (name == null)  
    30.       {  
    31.         Get request body  
    32.        dynamic data = await req.Content.ReadAsAsyncobject();  
    33.         name = data.name;  
    34.       }  
    35.   
    36.       return name == null  
    37.                  req.CreateResponse(HttpStatusCode.BadRequest, Please pass a name on the query string or in the request body)  
    38.                  req.CreateResponse(HttpStatusCode.OK, Hello + name);  
    39.     }  
    40.   }  
    41. }  
  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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  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

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions

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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions

Introducing Model

Our Http trigger works fine. We’ll now introduce a model; i.e. for credit card applications, that would be taken as 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.
    1. namespace LearnAzureFunctions  
    2. {  
    3.   public class CCApplication  
    4.   {  
    5.     public string Name { getset; }  
    6.     public int Age { getset; }  
    7.     public string Occupation { getset; }  
    8.     public float YearlyIncome { getset; }  
    9.   
    10.   }  
    11. }  
    Our solution looks exactly as shown in the following image.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions

    Following is the code for the implementation.
    1. using System.Linq;  
    2. using System.Net;  
    3. using System.Net.Http;  
    4. using System.Threading.Tasks;  
    5. using Microsoft.Azure.WebJobs;  
    6. using Microsoft.Azure.WebJobs.Extensions.Http;  
    7. using Microsoft.Azure.WebJobs.Host;  
    8.   
    9. namespace LearnAzureFunctions  
    10. {  
    11.   public static class ApplyForCC  
    12.   {  
    13.     [FunctionName("ApplyForCC")]  
    14.     public static async Task<HttpResponseMessage> Run(  
    15.       [HttpTrigger(AuthorizationLevel.Function,  
    16.           "post",  
    17.           Route = null)]HttpRequestMessage req,  
    18.       TraceWriter log)  
    19.     {  
    20.       log.Info("C# HTTP trigger function processed a request.");  
    21.   
    22.       CCApplication ccApplication = await req.Content.ReadAsAsync<CCApplication>();  
    23.       log.Info($"Received Credit Card Application from : {ccApplication.Name }");  
    24.       return req.CreateResponse(HttpStatusCode.OK,  
    25.         $"Application received and submitted for {ccApplication.Name}");  
    26.     }  
    27.   }  
    28. }  
  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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  1. You can place the debugger in the method to check the parameters of the received request, as we see in the following image.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  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”.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions

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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  1. If you are already logged in to your Microsoft account in Visual Studio it is good, else it will ask you to log in 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.
  1. 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. 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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions

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

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  1. Double click the CCAppFunctione. our App service that can hold multiple functions. In our case, so far 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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions

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.

Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions 
  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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  1. Copy the URL.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  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,

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  1. In the logs section as shown below, we see the logging text that we were doing in the function code itself.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions

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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  1. Once the debugger is attached, a browser will be launched with the function URL as shown below.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  1. Go back to Postman and again make a request like made earlier with the hosted URL of the function

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  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.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions
  1. In the Postman, we see the response received as 200.

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions

    Creating Azure Functions In Visual Studio 2017 - HTTP Triggered Azure Functions

Conclusion

 
In this detailed article, we learned what Azure Functions and Function Apps are, and 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!