Albert Bennett
Posted on October 6, 2021
If you learned something new feel free to connect with me on linkedin or follow me on dev.to :)
In this post, I will be explaining to the best of my knowledge what a Function App is, and any tips tricks and issues that I have come across whilst using them. More specifically, when setting them up and publishing to them directly from Visual Studios.
Introduction
Simply put, a Function App is a server-side application that is hosted in Azure. In it you create various different Functions.
Each function has a trigger type. A trigger type defines what/ how the function is going to be triggered. The most common type is HttpTrigger. When published to an Azure Function App the trigger becomes an endpoint that can be called.
The Setup
Function Apps like most Azure resources are easy to set up. Simply search for them in the "marketplace", click "Create" and fill in the details. A Function App is created inside of something called a resource group, this is a container for resources in Azure. It's important to make sure that the region of the resource group and the Function app are the same. This will help with performance as the resources will be closer together.
- Plan Type This setting is under Hosting Now there are two options for this field, consumption plan and app service plan. Consumption plan means that you only get charged per thousand calls as opposed to an app service plan which incurs a monthly fee. There are benefits to using one over the other. Pricing being one but, Functions apps on a consumption plan have this thing called a cold start. Basically when the Function App has been left unused for so many minutes it gets turned off. So when the next request comes in it will take time to spin up the required resources. Function apps on an app service plan don't have this issue, unless their "always on" property is turned off.
- Application Insights This setting is under Monitoring. This is a service that is used to monitor your Azure Function App. It is a means of catching errors that are thrown, and enable you to debug the function app and see where it is failing.
- Storage Account This setting is under Hosting. This is the place where the code/ resources for the Azure Functions will be published to. You don't have to create a new one for each Function App. Instead try to have only one per resource group. It will help when trying to manage resources and make the clean up/ maintenance of your resource group easier.
Http Triggers
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 responseMessage = 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);
}
}
This is a sample of what the default Http trigger function looks like. This project called Azure Function App can be created as soon as you have the Azure Cli tools and Azure SDK installed.
- The "FunctionName" attribute defines the name of the function when published.
- "get", "post" refer to the http methods that a request can have to execute the function. Authorization Levels Each http trigger has an "AuthorizationLevel". The "AuthorizationLevel" defines what can make calls/ access to it.
- Anonymous
- Function
- Admin
- User
- System
Before I go on to what each "AuthorizationLevel" is it is worth noting that with each Function App there are two sets of authentication keys. The host key and the function key. The host key and "_master" key is scoped at the function app level, meaning that there should only be one of each host key per function app (2 total). Whereas the function key is scoped on a function level, as such every function can have there own unique function key.
- Anonymous triggers can be called by any valid http request
- Function triggers can be called by any valid http request that passes on the function key as either a header or in the query parameters.
- Admin triggers can be called by any valid http request that passed the host key.
- User triggers can be called by any valid http request that has a valid bearer token.
- System triggers can be called by any valid http request that passes the master key.
Timer Trigger
[FunctionName("Function2")]
public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
{
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
}
These are Functions that run on a timer. This timer is set up in the binding for the function. In our example the function is set to trigger once every 5 minutes. This type of timer is called a cron job. How this is configured is as follows:
| Minute | Hour | Day of the Month | Month | Day of the Week |
If you wanted the function to run every 5 seconds you could structure the cron job as:
*/5 * * * *
Bindings
Bindings allows your functions to communicate with other Azure resources without you having to write the boiler plate code to get the connection set-up. I recently wrote a blog post about a binding that I had written for the Azure WebPubSub Service that you can find here. The bindings for function apps come in all shapes and sizes so it is worth it to check out the C# documentation about a particular service before trying to write any code to integrate the services yourself.
The Extra Files
With each azure function app that you create there are two extra files. local.settings.json, and host.json.
- The local.settings.json file defines the application settings and can be retrieved by using Environment.GetEnvironmentVariable. This file (by default) is not published to the function app. As such you can hold sensitive information in it without the risk of exposure. However you would need to add whatever application settings (connection strings, passwords) that you have to the configuration section of the function app in Azure: There is also a one-liner that you can add to the app settings if you wanted to retrieve a secret from key vault instead of storing the actual value of in the application settings of the function app:
@Microsoft.KeyVault(VaultName=vault name;SecretName=secret name in keyvault)
- The host.json file defines how the function app is to be hosted. There is normally not much in it. I've left an example of what a host file looks like below if you are curious:
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
}
}
Publishing Code from Visual Studios
To publish you can find the publishing option under the "Build" tab in VS (Visual Studios). Select use existing, then click publish. Fill out the details and find your function app in the drop-down menu. Click "ok" and away you go. In a few minutes... the process can take a while...
Now, there are several gotchas when publishing directly from VS namely. The problem of locked files. These are files that are currently in use by the function and cannot be overwritten, which causes us problems.
To overcome this we are going to need to add an app setting when we are publishing to our function it is MSDEPLOY_RENAME_LOCKED_FILES with a value of 1:
If that doesn't work, stop the function app in the portal then try to publish again. Then start it again.
I hope that helps you understand the basics of function apps.
If you have any questions leave a comment and, I'll get back to you as soon as I can.
Posted on October 6, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.