Tutorial: Azure Functions - Setup a Serverless function to calculate age in minutes

Azure Function is Microsoft’s response to AWS Lambda: It gives you the possibility to create a serverless architecture. Now before you go bonkers: it’s called serverless, because you don’t need to purchase, rent or provision servers – Not because there are really no servers in the architecture. Marketing worked over hours and decided that serverless sounds a whole lot better than Functions-As-A-Service. I agree with marketing there. Serverless is interesting because you get charged per use, so zero-usage means zero dollar. In fact, the first 400,000 GB-s are free each month (Azure Pricing)

In this tutorial, I am going to show you how you can easily make your own Azure Function in Visual Studio. This function will calculate the age in minutes based on a birthdate and birthtime. First it will run locally and then it will be published to the Azure Cloud. The function will be written in C# and will be triggered as a webhook

Of course, Instead of using C#, you can use JavaScript, F#, Python, PHP, Bash, PowerShell – And you could just create the function in the Azure Portal. Also there are many triggers available: schedules, azure events, and more.

This tutorial is just a beginner’s guide of how to work with Azure functions. Before you start, use a version of Visual Studio 2017 and make sure you have the extension “Azure Functions and Web Job Tools” installed. You can check this at the menu item Tools > “Extensions and Updates”.

1. Let’s create a new project of type Visual C#, Cloud > “Azure Functions” Name it AgeInMinutesCalculator.

2. Add a New Item to the newly created Project

function02

3. Pick “Azure Function” as the new Item and call it AgeInMinutes.cs

function03

4. Pick a trigger on which the function should act. For our example you need to pick “Http trigger with parameters”. The Access rights on the right will tell azure how access is set: You can choose from Anonymous, Function or Admin. We’ll leave it set to Function – this means you need to have a function-API-key to call it.

function04

5. Create a new Class in a similar fashion, by right clicking the project and choosing “Add > New Class”.

6. Call this class MinutesCalculator.cs – From this class we will instantiate an object that holds the BirthDateTime, the amount of minutes and a nicely formatted text of the age in minutes.

Because calculating an age in minutes is actually very simple in C#, we do that directly in the init.

class MinutesCalculator
{
public DateTime BirthDateTime;
public double Minutes;
public string Text;
public MinutesCalculator(DateTime birthDateTime)
{
BirthDateTime = birthDateTime;
Minutes = (DateTime.Now - BirthDateTime).TotalMinutes;
Text = GetAgeInMinutesString();
}
public string GetAgeInMinutesString()
{
if (Minutes >= 0)
{
return ("You are " + Minutes.ToString("N0") + " minutes old");
}
else
{
return ("The birthdate is in the future");
}
}
}

7. Next in the AgeInMintes.cs we will change the code into the following

public static class AgeInMinute
{
[FunctionName("AgeInMinutes")]
public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = "BirthDate/{birthDate}/BirthTime/{birthTime}")]HttpRequestMessage req, DateTime birthDate, string birthTime, TraceWriter log)
{
log.Info("C# HTTP trigger function processed a request.");
try
{
var birthDateTime = birthDate.ToString("yyyy-MM-dd") + "T" + birthTime.Substring(0, 2) + ":" + birthTime.Substring(2, 2);
DateTime BirthdateTime = Convert.ToDateTime(birthDateTime);
MinutesCalculator MinutesCalculator = new MinutesCalculator(BirthdateTime);
string jsonToReturn = JsonConvert.SerializeObject(MinutesCalculator);
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(jsonToReturn, Encoding.UTF8, "application/json")
};
}
catch
{
return req.CreateErrorResponse(HttpStatusCode.BadRequest, "Didn't Understand birthDateTime, BirthDate/yyyy-MM-dd/BirthTime/HHmm (eg BirthDate/1970-08-30/BirthTime/0922)");
}
}
}

The FunctionName will be the name of the Azure Function. Inside the Run method we tell the function it should respond to a HttpTrigger with the AuthorizationLevel.Function and the method “get” – By default it also contained Post, but for our example I’ve removed that. The Route defines what the URL should look like to call the Function and what the accepted parameters are. In this case we define the url to be something like /BirthDate/{birthDate}/BirthTime/{birthTime} – where {birthdate} should be a DateTime and {birthTime} should be a string.

The reason why I created a separate date and time parameter is because the usage of a “:” in the parameter would cause a security error to go off. (See this stackoverflow here). By accepting a date and a time in the format of 4 digits (eg 0402 or 1758), I worked around that. There are other ways, but I preferred this solution.

The function works as follows: It creates a string birthDateTime by concatting the birthDate, a “T”, the first digits of birthtime, a “:” and the last two digits. It tries to convert this to an actual DateTime. If that works, it will instantiate the object MinutesCalculator with that DateTime. If it somehow fails, it suspects the format is incorrect and the function will return a reply statement in the order of“ it didn’t go so well, please use this format”. If the object is instantiated correctly it will already have the minutes and text set up correctly. So we can just JSON serialize the MinutesCalculator object and we’ll return that as the content.

8. Now let’s run this Azure Function locally, by clicking the green “Run” button on top.

function05

9. This will start a nice PowerShell prompt with an impressive ASCII Art of an Azure Functions symbol. It also tells us what URL the locally hosted azure function is listening on. Also, note that the localhost has authorization set to anonymous.

function06

10. You can now test this via a browser or postman, by sending a GET to the URL, in which you changed the parameters to some values. For example: localhost:7071/api/BirthDate/1974-03-07/BirthTime/1115 .

This will return a nice json reply.

function09

11. Now that we saw it working locally, let’s publish this to Azure. That’s very simple! rightclick on the Project and click “Publish…”

12. Select “Azure Function App” and choose “Create New”, then click the Publish-button.

13. In the next step you are asked to setup the App Service. In here, it’s very important that you click “New” next to App Service Plan. Here you need to pick the option “Consumption”. The Consumption option is what makes the Azure Function Serverless and pay-per-use.

14. This will publish the Azure Function to Azure. If the publish was a success, you will see this page:

function12

15. You can visit your Azure Function in the Azure Portal (portal.azure.com). On the actual function page on the right next to the button “Run” there is a link called “ Get Function URL”. Click that to see the URL to call the Azure Function.

function13

16. The URL will show and it will also contain “?code=” containing the Function API-key, you need because we set the Authorization Level of the function to Function. You can also set postman up to send this code as an headerkey “x-functions-key”

17. By calling this URL with the specific parameters, you’ll get a json response from the Azure Function running in Azure.

function15

And if you’re sending the wrong format, you’ll get a relatively cryptic error message.

function17

And an example of using x-functions-key via postman.

And with that, you are now left with a running serverless Azure Function!