Serverless Functions In Azure

Introduction

 
In today’s article, we will look at Serverless functions. We will look at what they are, what are the advantages of serverless functions, how we can create them in C# using Visual Studio 2019, and how to deploy them in the cloud in Azure. We will create a simple function for this process. However, the same principle will apply for more complex functions.

What are Serverless Functions and their advantages?

 
In the Azure cloud, we have the PAAS infrastructure defined as Platform as a Service. Here we are just concerned with the application and the complete infrastructure is handled by Azure. We are not concerned with the machine maintenance, patching, software upgrades etc. We can also turn on automatic scale out options based on the usage of our application. We only specify the platform properties (Number of CPUs, RAM, Operating system etc.) and the rest is all taken care of by the platform. However, we need to pay for the platform on a time basis. This is irrespective of how much the application is used on the platform. Taking this setup even further, we have the option of Serverless functions deployed in function apps, which allow us to deploy code in the form of functions to carry out various tasks and for this we are only billed on the times this function is used and not on a time basis. This is useful for functions not used too often. The complete infrastructure of scaling these functions is handled by the Azure platform.
 

Creating a Serverless Function

 
We will create a Serverless function using C# in Visual Studio 2019 Community Edition. We will use the default skeleton function created by Visual Studio and go through the main concepts. After getting a good understanding of the basic concepts of triggers and binding, building any type of function will be simple. So, let us begin.

We first start Visual Studio 2019 Community Edition. Also, ensure the Azure workload is added to our installation in order to use the Azure templates.
 
Serverless Functions In Azure
 
Next, select to “Create a new project”,
 
Serverless Functions In Azure
 
Search for Azure functions and select the template as above,
 
Serverless Functions In Azure

Enter a project and solution name.
 
Serverless Functions In Azure
 
The next step is to select the “Trigger type”. This is the action that will execute this function. For this article, we will select “Http trigger”. This trigger will execute via a Http call.
 
We can select from several triggers including Queue trigger which will run every time an item is added to an Azure Queue or a Timer trigger which will run the function on specific times. I would recommend you go through the list of triggers to see what possible triggers could be used. Once, selected the function is created as below:
  1. using System.IO;  
  2. using System.Threading.Tasks;  
  3. using Microsoft.AspNetCore.Mvc;  
  4. using Microsoft.Azure.WebJobs;  
  5. using Microsoft.Azure.WebJobs.Extensions.Http;  
  6. using Microsoft.AspNetCore.Http;  
  7. using Microsoft.Extensions.Logging;  
  8. using Newtonsoft.Json;  
  9. namespace AzureFunctionApp {  
  10.     public static class Function1 {  
  11.         [FunctionName("Function1")]  
  12.         public static async Task < IActionResult > Run(  
  13.             [HttpTrigger(AuthorizationLevel.Function, "get""post", Route = null)] HttpRequest req, ILogger log) {  
  14.             log.LogInformation("C# HTTP trigger function processed a request.");  
  15.             string name = req.Query["name"];  
  16.             string requestBody = await new StreamReader(req.Body).ReadToEndAsync();  
  17.             dynamic data = JsonConvert.DeserializeObject(requestBody);  
  18.             name = name ?? data?.name;  
  19.             string response Message = string.IsNullOrEmpty(name) ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response." : $ "Hello, {name}. This HTTP triggered function executed successfully.";  
  20.             return new OkObjectResult(responseMessage);  
  21.         }  
  22.     }  
  23. }  
The above code is simple. We have specified a Http trigger which allows for the GET and POST actions. The Http request is read, and the name value is extracted from it and then returned as a response message inside a pre-defined string with Hello appended at the start and a message that the trigger executed successfully at the end. This function can be replaced with any complex code as required. The bindings here are simple as they are just http calls. These can be replaced with input bindings from a queue into the output bindings of another queue or Cosmos DB or SQL database. The input binding is the input data source and the output binding is the output destination.
 
We now compile and run the function as below,
 
Serverless Functions In Azure

Using an emulator, the function is run, and it can be accessed using the browser as below,
 
Serverless Functions In Azure
 
Serverless Functions In Azure

Deploying the Serverless Function to Azure


We will now deploy the function we just created to Azure. We will select the option to Publish the Function as below,
 
Serverless Functions In Azure

We will then see the below screen,

Serverless Functions In Azure
 
Serverless Functions In Azure
 
Here we will select the option of “Azure Function App (Windows)”. The function App is the location where we will store the functions.
 
Serverless Functions In Azure
 
Here, I select my Subscription and then create a new Azure function as I do not currently have any resource groups etc. under which this function App would be created which would hold my function.
 
Serverless Functions In Azure
 
Here I will select the default values and click “Create”.
 
Serverless Functions In Azure
 
The final step was to click “Finish” and the function would be deployed to the newly created function App.
 
The above steps would work normally but for me for some strange reason the publish failed. The simplest way to solve this is to go to the function app on the Azure portal, download the deployment profile and use this profile to deploy the function as below.
 
Serverless Functions In Azure
 
Serverless Functions In Azure

From the above click the “Get publish profile” and a file will be downloaded to your machine. We will use this file to publish our function to this function App.
 
Serverless Functions In Azure
 
Once the function is published, we can get the URL to access this function from the portal as below,
 
Serverless Functions In Azure
 
Now, in the browser, paste this link and we access our function,
 
Serverless Functions In Azure
Now we are running the function from the Azure cloud.
 

Summary

 
In this article, we looked at what serverless functions are, what are the advantages of serverless functions, how to create them in Visual Studio 2019, how to test them locally, and then how we can deploy them to Azure and run them in the cloud. As you have seen the process to create them and deploy them to the cloud is very quick and straightforward and in just a few minutes we can have our C# serverless functions running in the cloud. Happy Coding!