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.
Next, select to “Create a new project”,
Search for Azure functions and select the template as above,
Enter a project and solution name.
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:
- using System.IO;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Azure.WebJobs;
- using Microsoft.Azure.WebJobs.Extensions.Http;
- using Microsoft.AspNetCore.Http;
- using Microsoft.Extensions.Logging;
- using Newtonsoft.Json;
- namespace AzureFunctionApp {
- public static class Function1 {
- [FunctionName("Function1")]
- public static async Task < IActionResult > Run(
- [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) {
- log.LogInformation("C# HTTP trigger function processed a request.");
- string name = req.Query["name"];
- string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
- dynamic data = JsonConvert.DeserializeObject(requestBody);
- name = name ?? data?.name;
- 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.";
- return new OkObjectResult(responseMessage);
- }
- }
- }
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,
Using an emulator, the function is run, and it can be accessed using the browser as below,
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,
We will then see the below screen,
Here we will select the option of “Azure Function App (Windows)”. The function App is the location where we will store the functions.
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.
Here I will select the default values and click “Create”.
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.
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.
Once the function is published, we can get the URL to access this function from the portal as below,
Now, in the browser, paste this link and we access our function,
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!